diff --git a/CHANGELOG.md b/CHANGELOG.md index 50f3793..f26cc8c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,18 @@ ## Unreleased +- Align bot and group chat attachments with the server's file API: upload raw bytes, send file IDs, retain successful uploads for retry, and fetch transcript images by file ID. Deleted files display a placeholder and hide cached images. +- Update the contract generator to 1.3.0 with upload headers, binary request bodies, binary downloads, and the group snapshot event schema. +- Replace installation-linked notification presence with independent foreground chat views for bot and group chats. Acknowledge exact visible reply text and loaded request cards, retain per-chat acknowledgement retries, and clear old views before ending sessions. Presence works without notification permission or FCM registration. + +- Refresh task run labels while the task list is open. + +- Use server previews for task timing and reasoning, and server-provided reply citations. + +- Share generated transcript blocks and job activity types across HTTP and event streams. + +- Use server projections for job activity, chat work state, and task timing. + ## 0.2.0 - Remove the pages that configure the server or the account: Providers, Judge model, Vision model, Web search, Credentials, Logins, Password managers, Integrations, Coding, Message gateways, Event relay, and Users. The web app is the only client that configures them. Settings gains a Server settings row that opens the web app's settings in the browser, and the links that led to a removed page, such as Provider Settings on a failed reply, the bot editor's web search, integrations, and credentials notes, and Connect a password manager, open the matching web page. The `oauth/callback` deep link is gone with MCP sign-in. Bots' requests for credentials and logins are still answered in the chat. diff --git a/README.md b/README.md index a66df8d..ec3d541 100644 --- a/README.md +++ b/README.md @@ -24,9 +24,15 @@ Open the navigation drawer › **Settings**, enter the server URL (`http://10.0. The app doesn't configure the server or the account. Providers, credentials, logins, password managers, integrations, coding, users, message gateways, and the event relay are set in the web app: **Settings** › **Server settings** opens it in the browser. +## Chat files + +Bot and group chats upload attachments as raw bytes, then send their file IDs with the message. Failed sends retain attachments for retry. Retries reuse confirmed uploads and the message request ID. Deleted transcript files display **File deleted** instead of an image. + +Library browsing is not included. + ## Shared API contract -`contract/assets/` holds a copy of the `bot` contract files from `bot/openapi/`. A running server also serves its document at `GET /openapi.json`. `scripts/generate-contract.py` generates Kotlin wire models and operations without external build-time dependencies. +`contract/assets/` holds the HTTP contract and bot, group, activity, and heartbeat event schemas from `bot/openapi/`. A running server also serves its document at `GET /openapi.json`. `scripts/generate-contract.py` generates Kotlin wire models and operations without external build-time dependencies, including upload headers and binary bodies. ```bash python3 scripts/contract.py generate # Regenerate from contract/assets/ @@ -50,6 +56,10 @@ CRUMBLE_KEYSTORE_PATH=~/crumble-release.jks CRUMBLE_KEYSTORE_PASSWORD=... ./grad Without `app/google-services.json`, the app builds cleanly and posts local notifications while connected to `/v1/events`. To enable background delivery via Firebase Cloud Messaging (FCM), place `google-services.json` registering `ng.crumbli.android` and `ng.crumbli.android.dev` in `app/` and set `CRUMBLE_FCM_SERVICE_ACCOUNT_PATH` on the server (see `bot/docs/native-push.md`). +The app reports foreground bot and group chats through the chat-attention API, independently of notification permission and FCM registration. The server uses these reports to suppress account-wide pushes and waits at least three seconds before delivery. + +Seen acknowledgements identify the exact reply text or loaded request card visible in the chat viewport. Loading states, collapsed summaries, offscreen content, and unsupported group cards do not count as seen. Acknowledgement retries retain their original chat; account changes discard the old account's pending work. + ## License Licensed under the [GNU Affero General Public License v3.0](LICENSE) (`AGPL-3.0-only`). Third-party components retain their respective licenses. diff --git a/app/src/main/java/dev/crumble/android/MainActivity.kt b/app/src/main/java/dev/crumble/android/MainActivity.kt index 38b4362..3f885d1 100644 --- a/app/src/main/java/dev/crumble/android/MainActivity.kt +++ b/app/src/main/java/dev/crumble/android/MainActivity.kt @@ -20,11 +20,9 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.ui.Modifier import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.snapshotFlow import androidx.core.content.ContextCompat -import androidx.lifecycle.lifecycleScope -import androidx.lifecycle.Lifecycle -import androidx.lifecycle.repeatOnLifecycle import androidx.lifecycle.viewmodel.initializer import androidx.lifecycle.viewmodel.viewModelFactory import dev.crumble.android.model.AppModel @@ -32,10 +30,8 @@ import dev.crumble.android.model.ThemeChoice import dev.crumble.android.storage.AndroidKeyStoreCredentials import dev.crumble.android.theme.CrumbleTheme import dev.crumble.android.ui.CrumbleAppScreen +import dev.crumble.android.ui.LocalAttentionWindowID import dev.crumble.android.push.PushRuntime -import kotlinx.coroutines.delay -import kotlinx.coroutines.isActive -import kotlinx.coroutines.launch private val LIGHT_BAR_SCRIM = Color.argb(0xe6, 0xff, 0xff, 0xff) private val DARK_BAR_SCRIM = Color.argb(0x80, 0x1b, 0x1b, 0x1b) @@ -72,6 +68,7 @@ class MainActivity : ComponentActivity() { } private val model: AppModel get() = owner.model + private var attentionViewID: String? = null private val notificationPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestPermission(), @@ -82,6 +79,9 @@ class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) + attentionViewID = model.newAttentionView() + model.appActive = false + model.updateChatAttention() if (push.repliesWanted) requestNotificationPermissionIfNeeded() @@ -93,23 +93,17 @@ class MainActivity : ComponentActivity() { model.followActivity() handleIncomingIntent(intent) } - lifecycleScope.launch { - repeatOnLifecycle(Lifecycle.State.RESUMED) { - while (isActive) { - push.refreshPresence() - delay(30_000) - } - } - } - enableEdgeToEdge() setContent { LaunchedEffect(model) { snapshotFlow { model.client }.collect { api -> api?.let { push.configure(it) } } } LaunchedEffect(model) { - snapshotFlow { model.appActive to model.route }.collect { (active, route) -> - push.updatePresence(active, route) + snapshotFlow { Triple(model.client, model.appActive, model.route) }.collect { (_, active, route) -> + if (model.attentionWindowID == attentionViewID) { + push.updateVisibility(active, route) + model.updateChatAttention() + } } } val dark = when (model.theme) { @@ -123,7 +117,9 @@ class MainActivity : ComponentActivity() { modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background, ) { - CrumbleAppScreen(model = model) + CompositionLocalProvider(LocalAttentionWindowID provides attentionViewID) { + CrumbleAppScreen(model = model) + } } } } @@ -136,17 +132,21 @@ class MainActivity : ComponentActivity() { override fun onResume() { super.onResume() + if (model.attentionWindowID != attentionViewID) return model.appActive = true model.notificationsAllowed = push.notificationsAllowed() model.client?.let { push.configure(it) } - push.updatePresence(true, model.route) + push.updateVisibility(true, model.route) + model.updateChatAttention() } override fun onPause() { super.onPause() + if (model.attentionWindowID != attentionViewID) return model.appActive = false model.saveDrafts() - push.updatePresence(false, model.route) + push.updateVisibility(false, model.route) + model.updateChatAttention() } override fun onDestroy() { diff --git a/app/src/main/java/dev/crumble/android/generated/ContractBoundary.kt b/app/src/main/java/dev/crumble/android/generated/ContractBoundary.kt index b9d327e..ec63035 100644 --- a/app/src/main/java/dev/crumble/android/generated/ContractBoundary.kt +++ b/app/src/main/java/dev/crumble/android/generated/ContractBoundary.kt @@ -1,4 +1,4 @@ -// Generated by scripts/generate-contract.py 1.2.0. Do not edit. +// Generated by scripts/generate-contract.py 1.3.0. Do not edit. package dev.crumble.android.generated import dev.crumble.android.network.HttpRequestData @@ -10,8 +10,8 @@ import kotlinx.serialization.json.Json interface ContractBoundary { val json: Json fun escape(value: String): String - fun request(method: String, path: String, body: ByteArray?, timeoutMs: Int): HttpRequestData - suspend fun send(method: String, path: String, body: ByteArray?, timeoutMs: Int): ByteArray + fun request(method: String, path: String, body: ByteArray?, timeoutMs: Int, headers: Map = emptyMap()): HttpRequestData + suspend fun send(method: String, path: String, body: ByteArray?, timeoutMs: Int, headers: Map = emptyMap()): ByteArray } @Serializable(with = OptionalFieldCodec::class) diff --git a/app/src/main/java/dev/crumble/android/generated/ContractModels.kt b/app/src/main/java/dev/crumble/android/generated/ContractModels.kt index 21a16e0..f1d8059 100644 --- a/app/src/main/java/dev/crumble/android/generated/ContractModels.kt +++ b/app/src/main/java/dev/crumble/android/generated/ContractModels.kt @@ -1,5 +1,5 @@ @file:OptIn(kotlinx.serialization.ExperimentalSerializationApi::class) -// Generated by scripts/generate-contract.py 1.2.0. Do not edit. +// Generated by scripts/generate-contract.py 1.3.0. Do not edit. package dev.crumble.android.generated import kotlinx.serialization.* @@ -463,14 +463,6 @@ data class AssignSkillBotResponse( val `skipped`: Boolean, ) -@Serializable -data class AttachmentInfo( - val `name`: String, - val `mimeType`: String, - val `size`: Double, - val `kind`: String, -) - @Serializable data class BotAvatarDefinition( val `definition`: BotAvatarDefinitionDefinition, @@ -673,10 +665,18 @@ data class ChatSnapshot( val `partial`: String, val `usage`: JsonElement? = null, val `status`: String, + val `working`: String, val `updatedAt`: Double, val `error`: String?, ) +@Serializable +data class Citation( + val `href`: String, + val `title`: String, + val `site`: String, +) + @Serializable data class CodingJob( val `name`: String, @@ -1336,6 +1336,640 @@ data class GroupMessageReceipt( val `entryId`: String, ) +@Serializable(with = GroupSnapshotEventPayloadCodec::class) +data class GroupSnapshotEventPayload( + val `messages`: List, + val `hasMore`: Boolean, + val `oldestEntryId`: String?, + val `groupChat`: GroupSnapshotEventPayloadGroupChat, + val `activity`: GroupSnapshotEventPayloadActivity, + val `updatedAt`: Double, + val additionalProperties: Map = emptyMap(), +) +@Serializable +private data class GroupSnapshotEventPayloadFields( + val `messages`: List, + val `hasMore`: Boolean, + val `oldestEntryId`: String?, + val `groupChat`: GroupSnapshotEventPayloadGroupChat, + val `activity`: GroupSnapshotEventPayloadActivity, + val `updatedAt`: Double, +) +object GroupSnapshotEventPayloadCodec : KSerializer { + private val declared = setOf("messages", "hasMore", "oldestEntryId", "groupChat", "activity", "updatedAt") + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("GroupSnapshotEventPayload") + override fun deserialize(decoder: Decoder): GroupSnapshotEventPayload { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement().jsonObject + val fields = input.json.decodeFromJsonElement(JsonObject(element.filterKeys { it in declared })) + val additional = element.filterKeys { it !in declared }.mapValues { input.json.decodeFromJsonElement(it.value) } + return GroupSnapshotEventPayload(fields.`messages`, fields.`hasMore`, fields.`oldestEntryId`, fields.`groupChat`, fields.`activity`, fields.`updatedAt`, additional) + } + override fun serialize(encoder: Encoder, value: GroupSnapshotEventPayload) { + val output = encoder as JsonEncoder + val fields = output.json.encodeToJsonElement(GroupSnapshotEventPayloadFields(value.`messages`, value.`hasMore`, value.`oldestEntryId`, value.`groupChat`, value.`activity`, value.`updatedAt`)).jsonObject + val additional = value.additionalProperties.mapValues { output.json.encodeToJsonElement(it.value) } + output.encodeJsonElement(JsonObject(additional + fields)) + } +} + +@Serializable(with = GroupSnapshotEventPayloadActivityCodec::class) +data class GroupSnapshotEventPayloadActivity( + val `paused`: Boolean, + val `botTurns`: Double, + val `members`: List, + val additionalProperties: Map = emptyMap(), +) +@Serializable +private data class GroupSnapshotEventPayloadActivityFields( + val `paused`: Boolean, + val `botTurns`: Double, + val `members`: List, +) +object GroupSnapshotEventPayloadActivityCodec : KSerializer { + private val declared = setOf("paused", "botTurns", "members") + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("GroupSnapshotEventPayloadActivity") + override fun deserialize(decoder: Decoder): GroupSnapshotEventPayloadActivity { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement().jsonObject + val fields = input.json.decodeFromJsonElement(JsonObject(element.filterKeys { it in declared })) + val additional = element.filterKeys { it !in declared }.mapValues { input.json.decodeFromJsonElement(it.value) } + return GroupSnapshotEventPayloadActivity(fields.`paused`, fields.`botTurns`, fields.`members`, additional) + } + override fun serialize(encoder: Encoder, value: GroupSnapshotEventPayloadActivity) { + val output = encoder as JsonEncoder + val fields = output.json.encodeToJsonElement(GroupSnapshotEventPayloadActivityFields(value.`paused`, value.`botTurns`, value.`members`)).jsonObject + val additional = value.additionalProperties.mapValues { output.json.encodeToJsonElement(it.value) } + output.encodeJsonElement(JsonObject(additional + fields)) + } +} + +@Serializable(with = GroupSnapshotEventPayloadActivityMembersItemCodec::class) +data class GroupSnapshotEventPayloadActivityMembersItem( + val `agentId`: String, + val `status`: String, + val `error`: String?, + val additionalProperties: Map = emptyMap(), +) +@Serializable +private data class GroupSnapshotEventPayloadActivityMembersItemFields( + val `agentId`: String, + val `status`: String, + val `error`: String?, +) +object GroupSnapshotEventPayloadActivityMembersItemCodec : KSerializer { + private val declared = setOf("agentId", "status", "error") + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("GroupSnapshotEventPayloadActivityMembersItem") + override fun deserialize(decoder: Decoder): GroupSnapshotEventPayloadActivityMembersItem { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement().jsonObject + val fields = input.json.decodeFromJsonElement(JsonObject(element.filterKeys { it in declared })) + val additional = element.filterKeys { it !in declared }.mapValues { input.json.decodeFromJsonElement(it.value) } + return GroupSnapshotEventPayloadActivityMembersItem(fields.`agentId`, fields.`status`, fields.`error`, additional) + } + override fun serialize(encoder: Encoder, value: GroupSnapshotEventPayloadActivityMembersItem) { + val output = encoder as JsonEncoder + val fields = output.json.encodeToJsonElement(GroupSnapshotEventPayloadActivityMembersItemFields(value.`agentId`, value.`status`, value.`error`)).jsonObject + val additional = value.additionalProperties.mapValues { output.json.encodeToJsonElement(it.value) } + output.encodeJsonElement(JsonObject(additional + fields)) + } +} + +@Serializable(with = GroupSnapshotEventPayloadGroupChatCodec::class) +data class GroupSnapshotEventPayloadGroupChat( + val `id`: String, + val `name`: String, + val `memberIds`: List, + val `createdAt`: String, + val `updatedAt`: String, + val additionalProperties: Map = emptyMap(), +) +@Serializable +private data class GroupSnapshotEventPayloadGroupChatFields( + val `id`: String, + val `name`: String, + val `memberIds`: List, + val `createdAt`: String, + val `updatedAt`: String, +) +object GroupSnapshotEventPayloadGroupChatCodec : KSerializer { + private val declared = setOf("id", "name", "memberIds", "createdAt", "updatedAt") + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("GroupSnapshotEventPayloadGroupChat") + override fun deserialize(decoder: Decoder): GroupSnapshotEventPayloadGroupChat { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement().jsonObject + val fields = input.json.decodeFromJsonElement(JsonObject(element.filterKeys { it in declared })) + val additional = element.filterKeys { it !in declared }.mapValues { input.json.decodeFromJsonElement(it.value) } + return GroupSnapshotEventPayloadGroupChat(fields.`id`, fields.`name`, fields.`memberIds`, fields.`createdAt`, fields.`updatedAt`, additional) + } + override fun serialize(encoder: Encoder, value: GroupSnapshotEventPayloadGroupChat) { + val output = encoder as JsonEncoder + val fields = output.json.encodeToJsonElement(GroupSnapshotEventPayloadGroupChatFields(value.`id`, value.`name`, value.`memberIds`, value.`createdAt`, value.`updatedAt`)).jsonObject + val additional = value.additionalProperties.mapValues { output.json.encodeToJsonElement(it.value) } + output.encodeJsonElement(JsonObject(additional + fields)) + } +} + +@Serializable(with = GroupSnapshotEventPayloadMessagesItemCodec::class) +data class GroupSnapshotEventPayloadMessagesItem( + val `id`: String, + val `entryId`: String, + val `requestId`: String? = null, + val `role`: String, + val `content`: String, + val `blocks`: List? = null, + val `stopReason`: String? = null, + val `timestamp`: Double? = null, + val `kind`: String? = null, + val `replyTo`: String? = null, + val `replyPreview`: String? = null, + val `replyReferences`: List, + val `origin`: GroupSnapshotEventPayloadMessagesItemOrigin? = null, + val `communication`: GroupSnapshotEventPayloadMessagesItemCommunication? = null, + val `jobQuestion`: GroupSnapshotEventPayloadMessagesItemJobQuestion? = null, + val `heldAction`: GroupSnapshotEventPayloadMessagesItemHeldAction? = null, + val `call`: GroupSnapshotEventPayloadMessagesItemCall? = null, + val `files`: List? = null, + val `toolCallId`: String? = null, + val `toolName`: String? = null, + val `isError`: Boolean? = null, + val `toolDetails`: JsonElement? = null, + val `presentation`: MessagePresentation? = null, + val `sources`: List? = null, + val additionalProperties: Map = emptyMap(), +) +@Serializable +private data class GroupSnapshotEventPayloadMessagesItemFields( + val `id`: String, + val `entryId`: String, + val `requestId`: String? = null, + val `role`: String, + val `content`: String, + val `blocks`: List? = null, + val `stopReason`: String? = null, + val `timestamp`: Double? = null, + val `kind`: String? = null, + val `replyTo`: String? = null, + val `replyPreview`: String? = null, + val `replyReferences`: List, + val `origin`: GroupSnapshotEventPayloadMessagesItemOrigin? = null, + val `communication`: GroupSnapshotEventPayloadMessagesItemCommunication? = null, + val `jobQuestion`: GroupSnapshotEventPayloadMessagesItemJobQuestion? = null, + val `heldAction`: GroupSnapshotEventPayloadMessagesItemHeldAction? = null, + val `call`: GroupSnapshotEventPayloadMessagesItemCall? = null, + val `files`: List? = null, + val `toolCallId`: String? = null, + val `toolName`: String? = null, + val `isError`: Boolean? = null, + val `toolDetails`: JsonElement? = null, + val `presentation`: MessagePresentation? = null, + val `sources`: List? = null, +) +object GroupSnapshotEventPayloadMessagesItemCodec : KSerializer { + private val declared = setOf("id", "entryId", "requestId", "role", "content", "blocks", "stopReason", "timestamp", "kind", "replyTo", "replyPreview", "replyReferences", "origin", "communication", "jobQuestion", "heldAction", "call", "files", "toolCallId", "toolName", "isError", "toolDetails", "presentation", "sources") + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("GroupSnapshotEventPayloadMessagesItem") + override fun deserialize(decoder: Decoder): GroupSnapshotEventPayloadMessagesItem { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement().jsonObject + val fields = input.json.decodeFromJsonElement(JsonObject(element.filterKeys { it in declared })) + val additional = element.filterKeys { it !in declared }.mapValues { input.json.decodeFromJsonElement(it.value) } + return GroupSnapshotEventPayloadMessagesItem(fields.`id`, fields.`entryId`, fields.`requestId`, fields.`role`, fields.`content`, fields.`blocks`, fields.`stopReason`, fields.`timestamp`, fields.`kind`, fields.`replyTo`, fields.`replyPreview`, fields.`replyReferences`, fields.`origin`, fields.`communication`, fields.`jobQuestion`, fields.`heldAction`, fields.`call`, fields.`files`, fields.`toolCallId`, fields.`toolName`, fields.`isError`, fields.`toolDetails`, fields.`presentation`, fields.`sources`, additional) + } + override fun serialize(encoder: Encoder, value: GroupSnapshotEventPayloadMessagesItem) { + val output = encoder as JsonEncoder + val fields = output.json.encodeToJsonElement(GroupSnapshotEventPayloadMessagesItemFields(value.`id`, value.`entryId`, value.`requestId`, value.`role`, value.`content`, value.`blocks`, value.`stopReason`, value.`timestamp`, value.`kind`, value.`replyTo`, value.`replyPreview`, value.`replyReferences`, value.`origin`, value.`communication`, value.`jobQuestion`, value.`heldAction`, value.`call`, value.`files`, value.`toolCallId`, value.`toolName`, value.`isError`, value.`toolDetails`, value.`presentation`, value.`sources`)).jsonObject + val additional = value.additionalProperties.mapValues { output.json.encodeToJsonElement(it.value) } + output.encodeJsonElement(JsonObject(additional + fields)) + } +} + +@Serializable(with = GroupSnapshotEventPayloadMessagesItemCallCodec::class) +data class GroupSnapshotEventPayloadMessagesItemCall( + val `callId`: String, + val `direction`: String, + val `callee`: String? = null, + val additionalProperties: Map = emptyMap(), +) +@Serializable +private data class GroupSnapshotEventPayloadMessagesItemCallFields( + val `callId`: String, + val `direction`: String, + val `callee`: String? = null, +) +object GroupSnapshotEventPayloadMessagesItemCallCodec : KSerializer { + private val declared = setOf("callId", "direction", "callee") + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("GroupSnapshotEventPayloadMessagesItemCall") + override fun deserialize(decoder: Decoder): GroupSnapshotEventPayloadMessagesItemCall { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement().jsonObject + val fields = input.json.decodeFromJsonElement(JsonObject(element.filterKeys { it in declared })) + val additional = element.filterKeys { it !in declared }.mapValues { input.json.decodeFromJsonElement(it.value) } + return GroupSnapshotEventPayloadMessagesItemCall(fields.`callId`, fields.`direction`, fields.`callee`, additional) + } + override fun serialize(encoder: Encoder, value: GroupSnapshotEventPayloadMessagesItemCall) { + val output = encoder as JsonEncoder + val fields = output.json.encodeToJsonElement(GroupSnapshotEventPayloadMessagesItemCallFields(value.`callId`, value.`direction`, value.`callee`)).jsonObject + val additional = value.additionalProperties.mapValues { output.json.encodeToJsonElement(it.value) } + output.encodeJsonElement(JsonObject(additional + fields)) + } +} + +@Serializable(with = GroupSnapshotEventPayloadMessagesItemCommunicationCodec::class) +data class GroupSnapshotEventPayloadMessagesItemCommunication( + val `executionId`: String, + val `fromAgentId`: String, + val `fromName`: String, + val `toAgentId`: String, + val `toName`: String, + val `status`: String, + val additionalProperties: Map = emptyMap(), +) +@Serializable +private data class GroupSnapshotEventPayloadMessagesItemCommunicationFields( + val `executionId`: String, + val `fromAgentId`: String, + val `fromName`: String, + val `toAgentId`: String, + val `toName`: String, + val `status`: String, +) +object GroupSnapshotEventPayloadMessagesItemCommunicationCodec : KSerializer { + private val declared = setOf("executionId", "fromAgentId", "fromName", "toAgentId", "toName", "status") + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("GroupSnapshotEventPayloadMessagesItemCommunication") + override fun deserialize(decoder: Decoder): GroupSnapshotEventPayloadMessagesItemCommunication { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement().jsonObject + val fields = input.json.decodeFromJsonElement(JsonObject(element.filterKeys { it in declared })) + val additional = element.filterKeys { it !in declared }.mapValues { input.json.decodeFromJsonElement(it.value) } + return GroupSnapshotEventPayloadMessagesItemCommunication(fields.`executionId`, fields.`fromAgentId`, fields.`fromName`, fields.`toAgentId`, fields.`toName`, fields.`status`, additional) + } + override fun serialize(encoder: Encoder, value: GroupSnapshotEventPayloadMessagesItemCommunication) { + val output = encoder as JsonEncoder + val fields = output.json.encodeToJsonElement(GroupSnapshotEventPayloadMessagesItemCommunicationFields(value.`executionId`, value.`fromAgentId`, value.`fromName`, value.`toAgentId`, value.`toName`, value.`status`)).jsonObject + val additional = value.additionalProperties.mapValues { output.json.encodeToJsonElement(it.value) } + output.encodeJsonElement(JsonObject(additional + fields)) + } +} + +@Serializable(with = GroupSnapshotEventPayloadMessagesItemFilesItemCodec::class) +sealed class GroupSnapshotEventPayloadMessagesItemFilesItem { + data class Variant1(val value: GroupSnapshotEventPayloadMessagesItemFilesItemVariant1) : GroupSnapshotEventPayloadMessagesItemFilesItem() + data class Variant2(val value: GroupSnapshotEventPayloadMessagesItemFilesItemVariant2) : GroupSnapshotEventPayloadMessagesItemFilesItem() +} +object GroupSnapshotEventPayloadMessagesItemFilesItemCodec : KSerializer { + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("GroupSnapshotEventPayloadMessagesItemFilesItem") + override fun deserialize(decoder: Decoder): GroupSnapshotEventPayloadMessagesItemFilesItem { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement() + return when { + (element is JsonObject && element["id"] != null && element["name"] != null && element["mimeType"] != null && element["size"] != null) -> GroupSnapshotEventPayloadMessagesItemFilesItem.Variant1(input.json.decodeFromJsonElement(element)) + (element is JsonObject && element["id"] != null && element["deleted"] != null && element["deleted"] == Json.parseToJsonElement("true")) -> GroupSnapshotEventPayloadMessagesItemFilesItem.Variant2(input.json.decodeFromJsonElement(element)) + else -> throw SerializationException("Unknown GroupSnapshotEventPayloadMessagesItemFilesItem variant") + } + } + override fun serialize(encoder: Encoder, value: GroupSnapshotEventPayloadMessagesItemFilesItem) { + val output = encoder as JsonEncoder + output.encodeJsonElement(when (value) { + is GroupSnapshotEventPayloadMessagesItemFilesItem.Variant1 -> output.json.encodeToJsonElement(value.value) + is GroupSnapshotEventPayloadMessagesItemFilesItem.Variant2 -> output.json.encodeToJsonElement(value.value) + }) + } +} + +@Serializable(with = GroupSnapshotEventPayloadMessagesItemFilesItemVariant1Codec::class) +data class GroupSnapshotEventPayloadMessagesItemFilesItemVariant1( + val `id`: String, + val `name`: String, + val `mimeType`: String, + val `size`: Double, + val additionalProperties: Map = emptyMap(), +) +@Serializable +private data class GroupSnapshotEventPayloadMessagesItemFilesItemVariant1Fields( + val `id`: String, + val `name`: String, + val `mimeType`: String, + val `size`: Double, +) +object GroupSnapshotEventPayloadMessagesItemFilesItemVariant1Codec : KSerializer { + private val declared = setOf("id", "name", "mimeType", "size") + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("GroupSnapshotEventPayloadMessagesItemFilesItemVariant1") + override fun deserialize(decoder: Decoder): GroupSnapshotEventPayloadMessagesItemFilesItemVariant1 { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement().jsonObject + val fields = input.json.decodeFromJsonElement(JsonObject(element.filterKeys { it in declared })) + val additional = element.filterKeys { it !in declared }.mapValues { input.json.decodeFromJsonElement(it.value) } + return GroupSnapshotEventPayloadMessagesItemFilesItemVariant1(fields.`id`, fields.`name`, fields.`mimeType`, fields.`size`, additional) + } + override fun serialize(encoder: Encoder, value: GroupSnapshotEventPayloadMessagesItemFilesItemVariant1) { + val output = encoder as JsonEncoder + val fields = output.json.encodeToJsonElement(GroupSnapshotEventPayloadMessagesItemFilesItemVariant1Fields(value.`id`, value.`name`, value.`mimeType`, value.`size`)).jsonObject + val additional = value.additionalProperties.mapValues { output.json.encodeToJsonElement(it.value) } + output.encodeJsonElement(JsonObject(additional + fields)) + } +} + +@Serializable(with = GroupSnapshotEventPayloadMessagesItemFilesItemVariant2Codec::class) +data class GroupSnapshotEventPayloadMessagesItemFilesItemVariant2( + val `id`: String, + val `deleted`: Boolean, + val additionalProperties: Map = emptyMap(), +) +@Serializable +private data class GroupSnapshotEventPayloadMessagesItemFilesItemVariant2Fields( + val `id`: String, + val `deleted`: Boolean, +) +object GroupSnapshotEventPayloadMessagesItemFilesItemVariant2Codec : KSerializer { + private val declared = setOf("id", "deleted") + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("GroupSnapshotEventPayloadMessagesItemFilesItemVariant2") + override fun deserialize(decoder: Decoder): GroupSnapshotEventPayloadMessagesItemFilesItemVariant2 { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement().jsonObject + val fields = input.json.decodeFromJsonElement(JsonObject(element.filterKeys { it in declared })) + val additional = element.filterKeys { it !in declared }.mapValues { input.json.decodeFromJsonElement(it.value) } + return GroupSnapshotEventPayloadMessagesItemFilesItemVariant2(fields.`id`, fields.`deleted`, additional) + } + override fun serialize(encoder: Encoder, value: GroupSnapshotEventPayloadMessagesItemFilesItemVariant2) { + val output = encoder as JsonEncoder + val fields = output.json.encodeToJsonElement(GroupSnapshotEventPayloadMessagesItemFilesItemVariant2Fields(value.`id`, value.`deleted`)).jsonObject + val additional = value.additionalProperties.mapValues { output.json.encodeToJsonElement(it.value) } + output.encodeJsonElement(JsonObject(additional + fields)) + } +} + +@Serializable(with = GroupSnapshotEventPayloadMessagesItemHeldActionCodec::class) +data class GroupSnapshotEventPayloadMessagesItemHeldAction( + val `id`: String, + val `job`: String, + val additionalProperties: Map = emptyMap(), +) +@Serializable +private data class GroupSnapshotEventPayloadMessagesItemHeldActionFields( + val `id`: String, + val `job`: String, +) +object GroupSnapshotEventPayloadMessagesItemHeldActionCodec : KSerializer { + private val declared = setOf("id", "job") + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("GroupSnapshotEventPayloadMessagesItemHeldAction") + override fun deserialize(decoder: Decoder): GroupSnapshotEventPayloadMessagesItemHeldAction { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement().jsonObject + val fields = input.json.decodeFromJsonElement(JsonObject(element.filterKeys { it in declared })) + val additional = element.filterKeys { it !in declared }.mapValues { input.json.decodeFromJsonElement(it.value) } + return GroupSnapshotEventPayloadMessagesItemHeldAction(fields.`id`, fields.`job`, additional) + } + override fun serialize(encoder: Encoder, value: GroupSnapshotEventPayloadMessagesItemHeldAction) { + val output = encoder as JsonEncoder + val fields = output.json.encodeToJsonElement(GroupSnapshotEventPayloadMessagesItemHeldActionFields(value.`id`, value.`job`)).jsonObject + val additional = value.additionalProperties.mapValues { output.json.encodeToJsonElement(it.value) } + output.encodeJsonElement(JsonObject(additional + fields)) + } +} + +@Serializable(with = GroupSnapshotEventPayloadMessagesItemJobQuestionCodec::class) +data class GroupSnapshotEventPayloadMessagesItemJobQuestion( + val `id`: String, + val `kind`: String, + val `job`: String, + val `options`: List? = null, + val `multiple`: Boolean? = null, + val additionalProperties: Map = emptyMap(), +) +@Serializable +private data class GroupSnapshotEventPayloadMessagesItemJobQuestionFields( + val `id`: String, + val `kind`: String, + val `job`: String, + val `options`: List? = null, + val `multiple`: Boolean? = null, +) +object GroupSnapshotEventPayloadMessagesItemJobQuestionCodec : KSerializer { + private val declared = setOf("id", "kind", "job", "options", "multiple") + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("GroupSnapshotEventPayloadMessagesItemJobQuestion") + override fun deserialize(decoder: Decoder): GroupSnapshotEventPayloadMessagesItemJobQuestion { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement().jsonObject + val fields = input.json.decodeFromJsonElement(JsonObject(element.filterKeys { it in declared })) + val additional = element.filterKeys { it !in declared }.mapValues { input.json.decodeFromJsonElement(it.value) } + return GroupSnapshotEventPayloadMessagesItemJobQuestion(fields.`id`, fields.`kind`, fields.`job`, fields.`options`, fields.`multiple`, additional) + } + override fun serialize(encoder: Encoder, value: GroupSnapshotEventPayloadMessagesItemJobQuestion) { + val output = encoder as JsonEncoder + val fields = output.json.encodeToJsonElement(GroupSnapshotEventPayloadMessagesItemJobQuestionFields(value.`id`, value.`kind`, value.`job`, value.`options`, value.`multiple`)).jsonObject + val additional = value.additionalProperties.mapValues { output.json.encodeToJsonElement(it.value) } + output.encodeJsonElement(JsonObject(additional + fields)) + } +} + +@Serializable(with = GroupSnapshotEventPayloadMessagesItemOriginCodec::class) +data class GroupSnapshotEventPayloadMessagesItemOrigin( + val `kind`: String, + val `name`: String? = null, + val `agentId`: String? = null, + val `via`: String? = null, + val `source`: String? = null, + val additionalProperties: Map = emptyMap(), +) +@Serializable +private data class GroupSnapshotEventPayloadMessagesItemOriginFields( + val `kind`: String, + val `name`: String? = null, + val `agentId`: String? = null, + val `via`: String? = null, + val `source`: String? = null, +) +object GroupSnapshotEventPayloadMessagesItemOriginCodec : KSerializer { + private val declared = setOf("kind", "name", "agentId", "via", "source") + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("GroupSnapshotEventPayloadMessagesItemOrigin") + override fun deserialize(decoder: Decoder): GroupSnapshotEventPayloadMessagesItemOrigin { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement().jsonObject + val fields = input.json.decodeFromJsonElement(JsonObject(element.filterKeys { it in declared })) + val additional = element.filterKeys { it !in declared }.mapValues { input.json.decodeFromJsonElement(it.value) } + return GroupSnapshotEventPayloadMessagesItemOrigin(fields.`kind`, fields.`name`, fields.`agentId`, fields.`via`, fields.`source`, additional) + } + override fun serialize(encoder: Encoder, value: GroupSnapshotEventPayloadMessagesItemOrigin) { + val output = encoder as JsonEncoder + val fields = output.json.encodeToJsonElement(GroupSnapshotEventPayloadMessagesItemOriginFields(value.`kind`, value.`name`, value.`agentId`, value.`via`, value.`source`)).jsonObject + val additional = value.additionalProperties.mapValues { output.json.encodeToJsonElement(it.value) } + output.encodeJsonElement(JsonObject(additional + fields)) + } +} + +@Serializable(with = GroupSnapshotEventPayloadMessagesItemReplyReferencesItemCodec::class) +data class GroupSnapshotEventPayloadMessagesItemReplyReferencesItem( + val `eventId`: String, + val `surface`: GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurface, + val additionalProperties: Map = emptyMap(), +) +@Serializable +private data class GroupSnapshotEventPayloadMessagesItemReplyReferencesItemFields( + val `eventId`: String, + val `surface`: GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurface, +) +object GroupSnapshotEventPayloadMessagesItemReplyReferencesItemCodec : KSerializer { + private val declared = setOf("eventId", "surface") + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("GroupSnapshotEventPayloadMessagesItemReplyReferencesItem") + override fun deserialize(decoder: Decoder): GroupSnapshotEventPayloadMessagesItemReplyReferencesItem { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement().jsonObject + val fields = input.json.decodeFromJsonElement(JsonObject(element.filterKeys { it in declared })) + val additional = element.filterKeys { it !in declared }.mapValues { input.json.decodeFromJsonElement(it.value) } + return GroupSnapshotEventPayloadMessagesItemReplyReferencesItem(fields.`eventId`, fields.`surface`, additional) + } + override fun serialize(encoder: Encoder, value: GroupSnapshotEventPayloadMessagesItemReplyReferencesItem) { + val output = encoder as JsonEncoder + val fields = output.json.encodeToJsonElement(GroupSnapshotEventPayloadMessagesItemReplyReferencesItemFields(value.`eventId`, value.`surface`)).jsonObject + val additional = value.additionalProperties.mapValues { output.json.encodeToJsonElement(it.value) } + output.encodeJsonElement(JsonObject(additional + fields)) + } +} + +@Serializable(with = GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceCodec::class) +sealed class GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurface { + data class Variant1(val value: GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant1) : GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurface() + data class Variant2(val value: GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant2) : GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurface() + data class Variant3(val value: GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant3) : GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurface() +} +object GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceCodec : KSerializer { + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurface") + override fun deserialize(decoder: Decoder): GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurface { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement() + val matches = listOf((element is JsonObject && element["kind"] != null && element["kind"] == Json.parseToJsonElement("\"text\"")), (element is JsonObject && element["kind"] != null && element["kind"] == Json.parseToJsonElement("\"tool-card\"") && element["toolCallId"] != null), (element is JsonObject && element["kind"] != null && element["kind"] == Json.parseToJsonElement("\"held-action\"") && element["actionId"] != null)) + require(matches.count { it } == 1) { "Expected exactly one GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurface variant" } + return when { + (element is JsonObject && element["kind"] != null && element["kind"] == Json.parseToJsonElement("\"text\"")) -> GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurface.Variant1(input.json.decodeFromJsonElement(element)) + (element is JsonObject && element["kind"] != null && element["kind"] == Json.parseToJsonElement("\"tool-card\"") && element["toolCallId"] != null) -> GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurface.Variant2(input.json.decodeFromJsonElement(element)) + (element is JsonObject && element["kind"] != null && element["kind"] == Json.parseToJsonElement("\"held-action\"") && element["actionId"] != null) -> GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurface.Variant3(input.json.decodeFromJsonElement(element)) + else -> throw SerializationException("Unknown GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurface variant") + } + } + override fun serialize(encoder: Encoder, value: GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurface) { + val output = encoder as JsonEncoder + output.encodeJsonElement(when (value) { + is GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurface.Variant1 -> output.json.encodeToJsonElement(value.value) + is GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurface.Variant2 -> output.json.encodeToJsonElement(value.value) + is GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurface.Variant3 -> output.json.encodeToJsonElement(value.value) + }) + } +} + +@Serializable(with = GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant1Codec::class) +data class GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant1( + val `kind`: String, + val additionalProperties: Map = emptyMap(), +) +@Serializable +private data class GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant1Fields( + val `kind`: String, +) +object GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant1Codec : KSerializer { + private val declared = setOf("kind") + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant1") + override fun deserialize(decoder: Decoder): GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant1 { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement().jsonObject + val fields = input.json.decodeFromJsonElement(JsonObject(element.filterKeys { it in declared })) + val additional = element.filterKeys { it !in declared }.mapValues { input.json.decodeFromJsonElement(it.value) } + return GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant1(fields.`kind`, additional) + } + override fun serialize(encoder: Encoder, value: GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant1) { + val output = encoder as JsonEncoder + val fields = output.json.encodeToJsonElement(GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant1Fields(value.`kind`)).jsonObject + val additional = value.additionalProperties.mapValues { output.json.encodeToJsonElement(it.value) } + output.encodeJsonElement(JsonObject(additional + fields)) + } +} + +@Serializable(with = GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant2Codec::class) +data class GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant2( + val `kind`: String, + val `toolCallId`: String, + val additionalProperties: Map = emptyMap(), +) +@Serializable +private data class GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant2Fields( + val `kind`: String, + val `toolCallId`: String, +) +object GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant2Codec : KSerializer { + private val declared = setOf("kind", "toolCallId") + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant2") + override fun deserialize(decoder: Decoder): GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant2 { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement().jsonObject + val fields = input.json.decodeFromJsonElement(JsonObject(element.filterKeys { it in declared })) + val additional = element.filterKeys { it !in declared }.mapValues { input.json.decodeFromJsonElement(it.value) } + return GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant2(fields.`kind`, fields.`toolCallId`, additional) + } + override fun serialize(encoder: Encoder, value: GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant2) { + val output = encoder as JsonEncoder + val fields = output.json.encodeToJsonElement(GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant2Fields(value.`kind`, value.`toolCallId`)).jsonObject + val additional = value.additionalProperties.mapValues { output.json.encodeToJsonElement(it.value) } + output.encodeJsonElement(JsonObject(additional + fields)) + } +} + +@Serializable(with = GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant3Codec::class) +data class GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant3( + val `kind`: String, + val `actionId`: String, + val additionalProperties: Map = emptyMap(), +) +@Serializable +private data class GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant3Fields( + val `kind`: String, + val `actionId`: String, +) +object GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant3Codec : KSerializer { + private val declared = setOf("kind", "actionId") + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant3") + override fun deserialize(decoder: Decoder): GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant3 { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement().jsonObject + val fields = input.json.decodeFromJsonElement(JsonObject(element.filterKeys { it in declared })) + val additional = element.filterKeys { it !in declared }.mapValues { input.json.decodeFromJsonElement(it.value) } + return GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant3(fields.`kind`, fields.`actionId`, additional) + } + override fun serialize(encoder: Encoder, value: GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant3) { + val output = encoder as JsonEncoder + val fields = output.json.encodeToJsonElement(GroupSnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant3Fields(value.`kind`, value.`actionId`)).jsonObject + val additional = value.additionalProperties.mapValues { output.json.encodeToJsonElement(it.value) } + output.encodeJsonElement(JsonObject(additional + fields)) + } +} + +@Serializable(with = GroupSnapshotEventPayloadMessagesItemSourcesItemCodec::class) +data class GroupSnapshotEventPayloadMessagesItemSourcesItem( + val `url`: String, + val `title`: String, + val additionalProperties: Map = emptyMap(), +) +@Serializable +private data class GroupSnapshotEventPayloadMessagesItemSourcesItemFields( + val `url`: String, + val `title`: String, +) +object GroupSnapshotEventPayloadMessagesItemSourcesItemCodec : KSerializer { + private val declared = setOf("url", "title") + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("GroupSnapshotEventPayloadMessagesItemSourcesItem") + override fun deserialize(decoder: Decoder): GroupSnapshotEventPayloadMessagesItemSourcesItem { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement().jsonObject + val fields = input.json.decodeFromJsonElement(JsonObject(element.filterKeys { it in declared })) + val additional = element.filterKeys { it !in declared }.mapValues { input.json.decodeFromJsonElement(it.value) } + return GroupSnapshotEventPayloadMessagesItemSourcesItem(fields.`url`, fields.`title`, additional) + } + override fun serialize(encoder: Encoder, value: GroupSnapshotEventPayloadMessagesItemSourcesItem) { + val output = encoder as JsonEncoder + val fields = output.json.encodeToJsonElement(GroupSnapshotEventPayloadMessagesItemSourcesItemFields(value.`url`, value.`title`)).jsonObject + val additional = value.additionalProperties.mapValues { output.json.encodeToJsonElement(it.value) } + output.encodeJsonElement(JsonObject(additional + fields)) + } +} + @Serializable data class Health( val `status`: String, @@ -1391,6 +2025,69 @@ data class IssueVoiceGatewayTokenResponse( val `issuedAt`: String, ) +@Serializable(with = JobHistoryItemCodec::class) +sealed class JobHistoryItem { + data class Variant1(val value: JobTaskItem) : JobHistoryItem() + data class Variant2(val value: JobReplyItem) : JobHistoryItem() + data class Variant3(val value: JobStepItem) : JobHistoryItem() +} +object JobHistoryItemCodec : KSerializer { + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("JobHistoryItem") + override fun deserialize(decoder: Decoder): JobHistoryItem { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement() + val matches = listOf((element is JsonObject && element["kind"] != null && (element["kind"] == Json.parseToJsonElement("\"task\"")) && element["id"] != null && element["text"] != null), (element is JsonObject && element["kind"] != null && (element["kind"] == Json.parseToJsonElement("\"reply\"")) && element["id"] != null && element["text"] != null), (element is JsonObject && element["kind"] != null && (element["kind"] == Json.parseToJsonElement("\"step\"")) && element["id"] != null && element["tool"] != null && element["label"] != null && element["icon"] != null && (element["icon"] == Json.parseToJsonElement("\"terminal\"") || element["icon"] == Json.parseToJsonElement("\"file\"") || element["icon"] == Json.parseToJsonElement("\"pencil\"") || element["icon"] == Json.parseToJsonElement("\"pointer\"") || element["icon"] == Json.parseToJsonElement("\"tool\"")))) + require(matches.count { it } == 1) { "Expected exactly one JobHistoryItem variant" } + return when { + (element is JsonObject && element["kind"] != null && (element["kind"] == Json.parseToJsonElement("\"task\"")) && element["id"] != null && element["text"] != null) -> JobHistoryItem.Variant1(input.json.decodeFromJsonElement(element)) + (element is JsonObject && element["kind"] != null && (element["kind"] == Json.parseToJsonElement("\"reply\"")) && element["id"] != null && element["text"] != null) -> JobHistoryItem.Variant2(input.json.decodeFromJsonElement(element)) + (element is JsonObject && element["kind"] != null && (element["kind"] == Json.parseToJsonElement("\"step\"")) && element["id"] != null && element["tool"] != null && element["label"] != null && element["icon"] != null && (element["icon"] == Json.parseToJsonElement("\"terminal\"") || element["icon"] == Json.parseToJsonElement("\"file\"") || element["icon"] == Json.parseToJsonElement("\"pencil\"") || element["icon"] == Json.parseToJsonElement("\"pointer\"") || element["icon"] == Json.parseToJsonElement("\"tool\""))) -> JobHistoryItem.Variant3(input.json.decodeFromJsonElement(element)) + else -> throw SerializationException("Unknown JobHistoryItem variant") + } + } + override fun serialize(encoder: Encoder, value: JobHistoryItem) { + val output = encoder as JsonEncoder + output.encodeJsonElement(when (value) { + is JobHistoryItem.Variant1 -> output.json.encodeToJsonElement(value.value) + is JobHistoryItem.Variant2 -> output.json.encodeToJsonElement(value.value) + is JobHistoryItem.Variant3 -> output.json.encodeToJsonElement(value.value) + }) + } +} + +@Serializable +data class JobHistoryPage( + val `messages`: List, + val `hasMore`: Boolean, + val `oldestEntryId`: String?, + val `items`: List, +) + +@Serializable +data class JobReplyItem( + val `kind`: String, + val `id`: String, + val `text`: String, +) + +@Serializable +data class JobStepItem( + val `kind`: String, + val `id`: String, + val `tool`: String, + val `label`: String, + val `icon`: String, + val `subject`: String? = null, + val `result`: TranscriptMessage? = null, +) + +@Serializable +data class JobTaskItem( + val `kind`: String, + val `id`: String, + val `text`: String, +) + @Serializable data class JudgeChoice( val `provider`: String, @@ -1501,6 +2198,15 @@ data class LearnedEventChangesItem( val `name`: String, ) +@Serializable +data class LibraryFile( + val `id`: String, + val `name`: String, + val `mimeType`: String, + val `size`: Long, + val `createdAt`: String, +) + @Serializable(with = ListChangesAgentIdCodec::class) sealed class ListChangesAgentId { data class Variant1(val value: String) : ListChangesAgentId() @@ -1786,6 +2492,12 @@ data class MessageOrigin( val `source`: String? = null, ) +@Serializable +data class MessagePresentation( + val `text`: String, + val `citations`: List, +) + @Serializable data class Model( val `provider`: String, @@ -1852,6 +2564,37 @@ data class PluginSettingsPluginsItem( val `settings`: List, ) +@Serializable +data class PostChatAttentionSeenRequest( + val `chat`: PostChatAttentionSeenRequestChat, + val `eventIds`: List, +) + +@Serializable +data class PostChatAttentionSeenRequestChat( + val `kind`: String, + val `id`: String, +) + +@Serializable +data class PreviewReasoningRequest( + val `provider`: String, + val `model`: String, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `thinkingLevel`: OptionalField = OptionalField.Absent, +) + +@Serializable +data class PreviewScheduleRequest( + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `cron`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `runAt`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `eventSourceId`: OptionalField = OptionalField.Absent, + val `timezone`: String, +) + @Serializable data class Provider( val `provider`: String, @@ -2007,6 +2750,17 @@ data class PushStatusTransports( val `fcm`: Boolean, ) +@Serializable +data class PutChatAttentionViewRequest( + val `chat`: PutChatAttentionViewRequestChat?, +) + +@Serializable +data class PutChatAttentionViewRequestChat( + val `kind`: String, + val `id`: String, +) + @Serializable data class PutDesktopControlRequest( val `holder`: String, @@ -2038,9 +2792,15 @@ data class PutPushDeviceRequest( ) @Serializable -data class PutPushPresenceRequest( - val `active`: Boolean, - val `agentId`: String?, +data class ReasoningOption( + val `value`: String, + val `label`: String, +) + +@Serializable +data class ReasoningPreview( + val `options`: List, + val `effectiveLevel`: String, ) @Serializable @@ -2229,10 +2989,21 @@ data class Schedule( val `eventSourceId`: String?, val `enabled`: Boolean, val `nextRunAt`: String?, + val `nextRunLabel`: String, + val `description`: String, + val `timing`: String, val `createdAt`: String, val `createdByAgentId`: String?, ) +@Serializable +data class SchedulePreview( + val `description`: String, + val `text`: String, + val `isProblem`: Boolean, + val `nextRunAt`: String?, +) + @Serializable data class ScheduleRun( val `admitted`: Boolean, @@ -2319,14 +3090,7 @@ data class SendGroupMessageRequest( @EncodeDefault(EncodeDefault.Mode.NEVER) val `replyTo`: OptionalField = OptionalField.Absent, @EncodeDefault(EncodeDefault.Mode.NEVER) - val `attachments`: OptionalField> = OptionalField.Absent, -) - -@Serializable -data class SendGroupMessageRequestAttachmentsItem( - val `name`: String, - val `mimeType`: String, - val `data`: String, + val `files`: OptionalField> = OptionalField.Absent, ) @Serializable @@ -2336,18 +3100,11 @@ data class SendMessageRequest( @EncodeDefault(EncodeDefault.Mode.NEVER) val `replyTo`: OptionalField = OptionalField.Absent, @EncodeDefault(EncodeDefault.Mode.NEVER) - val `attachments`: OptionalField> = OptionalField.Absent, + val `files`: OptionalField> = OptionalField.Absent, @EncodeDefault(EncodeDefault.Mode.NEVER) val `timezone`: OptionalField = OptionalField.Absent, ) -@Serializable -data class SendMessageRequestAttachmentsItem( - val `name`: String, - val `mimeType`: String, - val `data`: String, -) - @Serializable data class SendSpokenMessageRequest( val `callId`: String, @@ -2526,6 +3283,7 @@ data class SnapshotEventPayload( val `partial`: String, val `usage`: JsonElement? = null, val `status`: String, + val `working`: String, val `updatedAt`: Double, val `error`: String?, val additionalProperties: Map = emptyMap(), @@ -2542,22 +3300,23 @@ private data class SnapshotEventPayloadFields( val `partial`: String, val `usage`: JsonElement? = null, val `status`: String, + val `working`: String, val `updatedAt`: Double, val `error`: String?, ) object SnapshotEventPayloadCodec : KSerializer { - private val declared = setOf("messages", "hasMore", "oldestEntryId", "conversationId", "agentId", "conversation", "live", "partial", "usage", "status", "updatedAt", "error") + private val declared = setOf("messages", "hasMore", "oldestEntryId", "conversationId", "agentId", "conversation", "live", "partial", "usage", "status", "working", "updatedAt", "error") override val descriptor: SerialDescriptor = buildClassSerialDescriptor("SnapshotEventPayload") override fun deserialize(decoder: Decoder): SnapshotEventPayload { val input = decoder as JsonDecoder val element = input.decodeJsonElement().jsonObject val fields = input.json.decodeFromJsonElement(JsonObject(element.filterKeys { it in declared })) val additional = element.filterKeys { it !in declared }.mapValues { input.json.decodeFromJsonElement(it.value) } - return SnapshotEventPayload(fields.`messages`, fields.`hasMore`, fields.`oldestEntryId`, fields.`conversationId`, fields.`agentId`, fields.`conversation`, fields.`live`, fields.`partial`, fields.`usage`, fields.`status`, fields.`updatedAt`, fields.`error`, additional) + return SnapshotEventPayload(fields.`messages`, fields.`hasMore`, fields.`oldestEntryId`, fields.`conversationId`, fields.`agentId`, fields.`conversation`, fields.`live`, fields.`partial`, fields.`usage`, fields.`status`, fields.`working`, fields.`updatedAt`, fields.`error`, additional) } override fun serialize(encoder: Encoder, value: SnapshotEventPayload) { val output = encoder as JsonEncoder - val fields = output.json.encodeToJsonElement(SnapshotEventPayloadFields(value.`messages`, value.`hasMore`, value.`oldestEntryId`, value.`conversationId`, value.`agentId`, value.`conversation`, value.`live`, value.`partial`, value.`usage`, value.`status`, value.`updatedAt`, value.`error`)).jsonObject + val fields = output.json.encodeToJsonElement(SnapshotEventPayloadFields(value.`messages`, value.`hasMore`, value.`oldestEntryId`, value.`conversationId`, value.`agentId`, value.`conversation`, value.`live`, value.`partial`, value.`usage`, value.`status`, value.`working`, value.`updatedAt`, value.`error`)).jsonObject val additional = value.additionalProperties.mapValues { output.json.encodeToJsonElement(it.value) } output.encodeJsonElement(JsonObject(additional + fields)) } @@ -2607,22 +3366,24 @@ data class SnapshotEventPayloadMessagesItem( val `requestId`: String? = null, val `role`: String, val `content`: String, - val `blocks`: JsonElement? = null, + val `blocks`: List? = null, val `stopReason`: String? = null, val `timestamp`: Double? = null, val `kind`: String? = null, val `replyTo`: String? = null, val `replyPreview`: String? = null, + val `replyReferences`: List, val `origin`: SnapshotEventPayloadMessagesItemOrigin? = null, val `communication`: SnapshotEventPayloadMessagesItemCommunication? = null, val `jobQuestion`: SnapshotEventPayloadMessagesItemJobQuestion? = null, val `heldAction`: SnapshotEventPayloadMessagesItemHeldAction? = null, val `call`: SnapshotEventPayloadMessagesItemCall? = null, - val `attachments`: List? = null, + val `files`: List? = null, val `toolCallId`: String? = null, val `toolName`: String? = null, val `isError`: Boolean? = null, val `toolDetails`: JsonElement? = null, + val `presentation`: MessagePresentation? = null, val `sources`: List? = null, val additionalProperties: Map = emptyMap(), ) @@ -2633,70 +3394,39 @@ private data class SnapshotEventPayloadMessagesItemFields( val `requestId`: String? = null, val `role`: String, val `content`: String, - val `blocks`: JsonElement? = null, + val `blocks`: List? = null, val `stopReason`: String? = null, val `timestamp`: Double? = null, val `kind`: String? = null, val `replyTo`: String? = null, val `replyPreview`: String? = null, + val `replyReferences`: List, val `origin`: SnapshotEventPayloadMessagesItemOrigin? = null, val `communication`: SnapshotEventPayloadMessagesItemCommunication? = null, val `jobQuestion`: SnapshotEventPayloadMessagesItemJobQuestion? = null, val `heldAction`: SnapshotEventPayloadMessagesItemHeldAction? = null, val `call`: SnapshotEventPayloadMessagesItemCall? = null, - val `attachments`: List? = null, + val `files`: List? = null, val `toolCallId`: String? = null, val `toolName`: String? = null, val `isError`: Boolean? = null, val `toolDetails`: JsonElement? = null, + val `presentation`: MessagePresentation? = null, val `sources`: List? = null, ) object SnapshotEventPayloadMessagesItemCodec : KSerializer { - private val declared = setOf("id", "entryId", "requestId", "role", "content", "blocks", "stopReason", "timestamp", "kind", "replyTo", "replyPreview", "origin", "communication", "jobQuestion", "heldAction", "call", "attachments", "toolCallId", "toolName", "isError", "toolDetails", "sources") + private val declared = setOf("id", "entryId", "requestId", "role", "content", "blocks", "stopReason", "timestamp", "kind", "replyTo", "replyPreview", "replyReferences", "origin", "communication", "jobQuestion", "heldAction", "call", "files", "toolCallId", "toolName", "isError", "toolDetails", "presentation", "sources") override val descriptor: SerialDescriptor = buildClassSerialDescriptor("SnapshotEventPayloadMessagesItem") override fun deserialize(decoder: Decoder): SnapshotEventPayloadMessagesItem { val input = decoder as JsonDecoder val element = input.decodeJsonElement().jsonObject val fields = input.json.decodeFromJsonElement(JsonObject(element.filterKeys { it in declared })) val additional = element.filterKeys { it !in declared }.mapValues { input.json.decodeFromJsonElement(it.value) } - return SnapshotEventPayloadMessagesItem(fields.`id`, fields.`entryId`, fields.`requestId`, fields.`role`, fields.`content`, fields.`blocks`, fields.`stopReason`, fields.`timestamp`, fields.`kind`, fields.`replyTo`, fields.`replyPreview`, fields.`origin`, fields.`communication`, fields.`jobQuestion`, fields.`heldAction`, fields.`call`, fields.`attachments`, fields.`toolCallId`, fields.`toolName`, fields.`isError`, fields.`toolDetails`, fields.`sources`, additional) + return SnapshotEventPayloadMessagesItem(fields.`id`, fields.`entryId`, fields.`requestId`, fields.`role`, fields.`content`, fields.`blocks`, fields.`stopReason`, fields.`timestamp`, fields.`kind`, fields.`replyTo`, fields.`replyPreview`, fields.`replyReferences`, fields.`origin`, fields.`communication`, fields.`jobQuestion`, fields.`heldAction`, fields.`call`, fields.`files`, fields.`toolCallId`, fields.`toolName`, fields.`isError`, fields.`toolDetails`, fields.`presentation`, fields.`sources`, additional) } override fun serialize(encoder: Encoder, value: SnapshotEventPayloadMessagesItem) { val output = encoder as JsonEncoder - val fields = output.json.encodeToJsonElement(SnapshotEventPayloadMessagesItemFields(value.`id`, value.`entryId`, value.`requestId`, value.`role`, value.`content`, value.`blocks`, value.`stopReason`, value.`timestamp`, value.`kind`, value.`replyTo`, value.`replyPreview`, value.`origin`, value.`communication`, value.`jobQuestion`, value.`heldAction`, value.`call`, value.`attachments`, value.`toolCallId`, value.`toolName`, value.`isError`, value.`toolDetails`, value.`sources`)).jsonObject - val additional = value.additionalProperties.mapValues { output.json.encodeToJsonElement(it.value) } - output.encodeJsonElement(JsonObject(additional + fields)) - } -} - -@Serializable(with = SnapshotEventPayloadMessagesItemAttachmentsItemCodec::class) -data class SnapshotEventPayloadMessagesItemAttachmentsItem( - val `name`: String, - val `mimeType`: String, - val `size`: Double, - val `kind`: String, - val additionalProperties: Map = emptyMap(), -) -@Serializable -private data class SnapshotEventPayloadMessagesItemAttachmentsItemFields( - val `name`: String, - val `mimeType`: String, - val `size`: Double, - val `kind`: String, -) -object SnapshotEventPayloadMessagesItemAttachmentsItemCodec : KSerializer { - private val declared = setOf("name", "mimeType", "size", "kind") - override val descriptor: SerialDescriptor = buildClassSerialDescriptor("SnapshotEventPayloadMessagesItemAttachmentsItem") - override fun deserialize(decoder: Decoder): SnapshotEventPayloadMessagesItemAttachmentsItem { - val input = decoder as JsonDecoder - val element = input.decodeJsonElement().jsonObject - val fields = input.json.decodeFromJsonElement(JsonObject(element.filterKeys { it in declared })) - val additional = element.filterKeys { it !in declared }.mapValues { input.json.decodeFromJsonElement(it.value) } - return SnapshotEventPayloadMessagesItemAttachmentsItem(fields.`name`, fields.`mimeType`, fields.`size`, fields.`kind`, additional) - } - override fun serialize(encoder: Encoder, value: SnapshotEventPayloadMessagesItemAttachmentsItem) { - val output = encoder as JsonEncoder - val fields = output.json.encodeToJsonElement(SnapshotEventPayloadMessagesItemAttachmentsItemFields(value.`name`, value.`mimeType`, value.`size`, value.`kind`)).jsonObject + val fields = output.json.encodeToJsonElement(SnapshotEventPayloadMessagesItemFields(value.`id`, value.`entryId`, value.`requestId`, value.`role`, value.`content`, value.`blocks`, value.`stopReason`, value.`timestamp`, value.`kind`, value.`replyTo`, value.`replyPreview`, value.`replyReferences`, value.`origin`, value.`communication`, value.`jobQuestion`, value.`heldAction`, value.`call`, value.`files`, value.`toolCallId`, value.`toolName`, value.`isError`, value.`toolDetails`, value.`presentation`, value.`sources`)).jsonObject val additional = value.additionalProperties.mapValues { output.json.encodeToJsonElement(it.value) } output.encodeJsonElement(JsonObject(additional + fields)) } @@ -2770,6 +3500,93 @@ object SnapshotEventPayloadMessagesItemCommunicationCodec : KSerializer { + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("SnapshotEventPayloadMessagesItemFilesItem") + override fun deserialize(decoder: Decoder): SnapshotEventPayloadMessagesItemFilesItem { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement() + return when { + (element is JsonObject && element["id"] != null && element["name"] != null && element["mimeType"] != null && element["size"] != null) -> SnapshotEventPayloadMessagesItemFilesItem.Variant1(input.json.decodeFromJsonElement(element)) + (element is JsonObject && element["id"] != null && element["deleted"] != null && element["deleted"] == Json.parseToJsonElement("true")) -> SnapshotEventPayloadMessagesItemFilesItem.Variant2(input.json.decodeFromJsonElement(element)) + else -> throw SerializationException("Unknown SnapshotEventPayloadMessagesItemFilesItem variant") + } + } + override fun serialize(encoder: Encoder, value: SnapshotEventPayloadMessagesItemFilesItem) { + val output = encoder as JsonEncoder + output.encodeJsonElement(when (value) { + is SnapshotEventPayloadMessagesItemFilesItem.Variant1 -> output.json.encodeToJsonElement(value.value) + is SnapshotEventPayloadMessagesItemFilesItem.Variant2 -> output.json.encodeToJsonElement(value.value) + }) + } +} + +@Serializable(with = SnapshotEventPayloadMessagesItemFilesItemVariant1Codec::class) +data class SnapshotEventPayloadMessagesItemFilesItemVariant1( + val `id`: String, + val `name`: String, + val `mimeType`: String, + val `size`: Double, + val additionalProperties: Map = emptyMap(), +) +@Serializable +private data class SnapshotEventPayloadMessagesItemFilesItemVariant1Fields( + val `id`: String, + val `name`: String, + val `mimeType`: String, + val `size`: Double, +) +object SnapshotEventPayloadMessagesItemFilesItemVariant1Codec : KSerializer { + private val declared = setOf("id", "name", "mimeType", "size") + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("SnapshotEventPayloadMessagesItemFilesItemVariant1") + override fun deserialize(decoder: Decoder): SnapshotEventPayloadMessagesItemFilesItemVariant1 { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement().jsonObject + val fields = input.json.decodeFromJsonElement(JsonObject(element.filterKeys { it in declared })) + val additional = element.filterKeys { it !in declared }.mapValues { input.json.decodeFromJsonElement(it.value) } + return SnapshotEventPayloadMessagesItemFilesItemVariant1(fields.`id`, fields.`name`, fields.`mimeType`, fields.`size`, additional) + } + override fun serialize(encoder: Encoder, value: SnapshotEventPayloadMessagesItemFilesItemVariant1) { + val output = encoder as JsonEncoder + val fields = output.json.encodeToJsonElement(SnapshotEventPayloadMessagesItemFilesItemVariant1Fields(value.`id`, value.`name`, value.`mimeType`, value.`size`)).jsonObject + val additional = value.additionalProperties.mapValues { output.json.encodeToJsonElement(it.value) } + output.encodeJsonElement(JsonObject(additional + fields)) + } +} + +@Serializable(with = SnapshotEventPayloadMessagesItemFilesItemVariant2Codec::class) +data class SnapshotEventPayloadMessagesItemFilesItemVariant2( + val `id`: String, + val `deleted`: Boolean, + val additionalProperties: Map = emptyMap(), +) +@Serializable +private data class SnapshotEventPayloadMessagesItemFilesItemVariant2Fields( + val `id`: String, + val `deleted`: Boolean, +) +object SnapshotEventPayloadMessagesItemFilesItemVariant2Codec : KSerializer { + private val declared = setOf("id", "deleted") + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("SnapshotEventPayloadMessagesItemFilesItemVariant2") + override fun deserialize(decoder: Decoder): SnapshotEventPayloadMessagesItemFilesItemVariant2 { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement().jsonObject + val fields = input.json.decodeFromJsonElement(JsonObject(element.filterKeys { it in declared })) + val additional = element.filterKeys { it !in declared }.mapValues { input.json.decodeFromJsonElement(it.value) } + return SnapshotEventPayloadMessagesItemFilesItemVariant2(fields.`id`, fields.`deleted`, additional) + } + override fun serialize(encoder: Encoder, value: SnapshotEventPayloadMessagesItemFilesItemVariant2) { + val output = encoder as JsonEncoder + val fields = output.json.encodeToJsonElement(SnapshotEventPayloadMessagesItemFilesItemVariant2Fields(value.`id`, value.`deleted`)).jsonObject + val additional = value.additionalProperties.mapValues { output.json.encodeToJsonElement(it.value) } + output.encodeJsonElement(JsonObject(additional + fields)) + } +} + @Serializable(with = SnapshotEventPayloadMessagesItemHeldActionCodec::class) data class SnapshotEventPayloadMessagesItemHeldAction( val `id`: String, @@ -2869,6 +3686,150 @@ object SnapshotEventPayloadMessagesItemOriginCodec : KSerializer = emptyMap(), +) +@Serializable +private data class SnapshotEventPayloadMessagesItemReplyReferencesItemFields( + val `eventId`: String, + val `surface`: SnapshotEventPayloadMessagesItemReplyReferencesItemSurface, +) +object SnapshotEventPayloadMessagesItemReplyReferencesItemCodec : KSerializer { + private val declared = setOf("eventId", "surface") + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("SnapshotEventPayloadMessagesItemReplyReferencesItem") + override fun deserialize(decoder: Decoder): SnapshotEventPayloadMessagesItemReplyReferencesItem { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement().jsonObject + val fields = input.json.decodeFromJsonElement(JsonObject(element.filterKeys { it in declared })) + val additional = element.filterKeys { it !in declared }.mapValues { input.json.decodeFromJsonElement(it.value) } + return SnapshotEventPayloadMessagesItemReplyReferencesItem(fields.`eventId`, fields.`surface`, additional) + } + override fun serialize(encoder: Encoder, value: SnapshotEventPayloadMessagesItemReplyReferencesItem) { + val output = encoder as JsonEncoder + val fields = output.json.encodeToJsonElement(SnapshotEventPayloadMessagesItemReplyReferencesItemFields(value.`eventId`, value.`surface`)).jsonObject + val additional = value.additionalProperties.mapValues { output.json.encodeToJsonElement(it.value) } + output.encodeJsonElement(JsonObject(additional + fields)) + } +} + +@Serializable(with = SnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceCodec::class) +sealed class SnapshotEventPayloadMessagesItemReplyReferencesItemSurface { + data class Variant1(val value: SnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant1) : SnapshotEventPayloadMessagesItemReplyReferencesItemSurface() + data class Variant2(val value: SnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant2) : SnapshotEventPayloadMessagesItemReplyReferencesItemSurface() + data class Variant3(val value: SnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant3) : SnapshotEventPayloadMessagesItemReplyReferencesItemSurface() +} +object SnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceCodec : KSerializer { + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("SnapshotEventPayloadMessagesItemReplyReferencesItemSurface") + override fun deserialize(decoder: Decoder): SnapshotEventPayloadMessagesItemReplyReferencesItemSurface { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement() + val matches = listOf((element is JsonObject && element["kind"] != null && element["kind"] == Json.parseToJsonElement("\"text\"")), (element is JsonObject && element["kind"] != null && element["kind"] == Json.parseToJsonElement("\"tool-card\"") && element["toolCallId"] != null), (element is JsonObject && element["kind"] != null && element["kind"] == Json.parseToJsonElement("\"held-action\"") && element["actionId"] != null)) + require(matches.count { it } == 1) { "Expected exactly one SnapshotEventPayloadMessagesItemReplyReferencesItemSurface variant" } + return when { + (element is JsonObject && element["kind"] != null && element["kind"] == Json.parseToJsonElement("\"text\"")) -> SnapshotEventPayloadMessagesItemReplyReferencesItemSurface.Variant1(input.json.decodeFromJsonElement(element)) + (element is JsonObject && element["kind"] != null && element["kind"] == Json.parseToJsonElement("\"tool-card\"") && element["toolCallId"] != null) -> SnapshotEventPayloadMessagesItemReplyReferencesItemSurface.Variant2(input.json.decodeFromJsonElement(element)) + (element is JsonObject && element["kind"] != null && element["kind"] == Json.parseToJsonElement("\"held-action\"") && element["actionId"] != null) -> SnapshotEventPayloadMessagesItemReplyReferencesItemSurface.Variant3(input.json.decodeFromJsonElement(element)) + else -> throw SerializationException("Unknown SnapshotEventPayloadMessagesItemReplyReferencesItemSurface variant") + } + } + override fun serialize(encoder: Encoder, value: SnapshotEventPayloadMessagesItemReplyReferencesItemSurface) { + val output = encoder as JsonEncoder + output.encodeJsonElement(when (value) { + is SnapshotEventPayloadMessagesItemReplyReferencesItemSurface.Variant1 -> output.json.encodeToJsonElement(value.value) + is SnapshotEventPayloadMessagesItemReplyReferencesItemSurface.Variant2 -> output.json.encodeToJsonElement(value.value) + is SnapshotEventPayloadMessagesItemReplyReferencesItemSurface.Variant3 -> output.json.encodeToJsonElement(value.value) + }) + } +} + +@Serializable(with = SnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant1Codec::class) +data class SnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant1( + val `kind`: String, + val additionalProperties: Map = emptyMap(), +) +@Serializable +private data class SnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant1Fields( + val `kind`: String, +) +object SnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant1Codec : KSerializer { + private val declared = setOf("kind") + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("SnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant1") + override fun deserialize(decoder: Decoder): SnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant1 { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement().jsonObject + val fields = input.json.decodeFromJsonElement(JsonObject(element.filterKeys { it in declared })) + val additional = element.filterKeys { it !in declared }.mapValues { input.json.decodeFromJsonElement(it.value) } + return SnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant1(fields.`kind`, additional) + } + override fun serialize(encoder: Encoder, value: SnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant1) { + val output = encoder as JsonEncoder + val fields = output.json.encodeToJsonElement(SnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant1Fields(value.`kind`)).jsonObject + val additional = value.additionalProperties.mapValues { output.json.encodeToJsonElement(it.value) } + output.encodeJsonElement(JsonObject(additional + fields)) + } +} + +@Serializable(with = SnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant2Codec::class) +data class SnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant2( + val `kind`: String, + val `toolCallId`: String, + val additionalProperties: Map = emptyMap(), +) +@Serializable +private data class SnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant2Fields( + val `kind`: String, + val `toolCallId`: String, +) +object SnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant2Codec : KSerializer { + private val declared = setOf("kind", "toolCallId") + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("SnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant2") + override fun deserialize(decoder: Decoder): SnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant2 { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement().jsonObject + val fields = input.json.decodeFromJsonElement(JsonObject(element.filterKeys { it in declared })) + val additional = element.filterKeys { it !in declared }.mapValues { input.json.decodeFromJsonElement(it.value) } + return SnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant2(fields.`kind`, fields.`toolCallId`, additional) + } + override fun serialize(encoder: Encoder, value: SnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant2) { + val output = encoder as JsonEncoder + val fields = output.json.encodeToJsonElement(SnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant2Fields(value.`kind`, value.`toolCallId`)).jsonObject + val additional = value.additionalProperties.mapValues { output.json.encodeToJsonElement(it.value) } + output.encodeJsonElement(JsonObject(additional + fields)) + } +} + +@Serializable(with = SnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant3Codec::class) +data class SnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant3( + val `kind`: String, + val `actionId`: String, + val additionalProperties: Map = emptyMap(), +) +@Serializable +private data class SnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant3Fields( + val `kind`: String, + val `actionId`: String, +) +object SnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant3Codec : KSerializer { + private val declared = setOf("kind", "actionId") + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("SnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant3") + override fun deserialize(decoder: Decoder): SnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant3 { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement().jsonObject + val fields = input.json.decodeFromJsonElement(JsonObject(element.filterKeys { it in declared })) + val additional = element.filterKeys { it !in declared }.mapValues { input.json.decodeFromJsonElement(it.value) } + return SnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant3(fields.`kind`, fields.`actionId`, additional) + } + override fun serialize(encoder: Encoder, value: SnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant3) { + val output = encoder as JsonEncoder + val fields = output.json.encodeToJsonElement(SnapshotEventPayloadMessagesItemReplyReferencesItemSurfaceVariant3Fields(value.`kind`, value.`actionId`)).jsonObject + val additional = value.additionalProperties.mapValues { output.json.encodeToJsonElement(it.value) } + output.encodeJsonElement(JsonObject(additional + fields)) + } +} + @Serializable(with = SnapshotEventPayloadMessagesItemSourcesItemCodec::class) data class SnapshotEventPayloadMessagesItemSourcesItem( val `url`: String, @@ -2918,6 +3879,45 @@ data class StartProviderLoginRequest( @Serializable class StartVoiceCallRequest +@Serializable(with = TranscriptBlockCodec::class) +sealed class TranscriptBlock { + data class Variant1(val value: TranscriptTextBlock) : TranscriptBlock() + data class Variant2(val value: TranscriptThinkingBlock) : TranscriptBlock() + data class Variant3(val value: TranscriptImageBlock) : TranscriptBlock() + data class Variant4(val value: TranscriptToolCallBlock) : TranscriptBlock() +} +object TranscriptBlockCodec : KSerializer { + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("TranscriptBlock") + override fun deserialize(decoder: Decoder): TranscriptBlock { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement() + val matches = listOf((element is JsonObject && element["type"] != null && (element["type"] == Json.parseToJsonElement("\"text\"")) && element["text"] != null), (element is JsonObject && element["type"] != null && (element["type"] == Json.parseToJsonElement("\"thinking\"")) && element["thinking"] != null), (element is JsonObject && element["type"] != null && (element["type"] == Json.parseToJsonElement("\"image\"")) && element["mimeType"] != null), (element is JsonObject && element["type"] != null && (element["type"] == Json.parseToJsonElement("\"toolCall\"")) && element["id"] != null && element["name"] != null && element["arguments"] != null)) + require(matches.count { it } == 1) { "Expected exactly one TranscriptBlock variant" } + return when { + (element is JsonObject && element["type"] != null && (element["type"] == Json.parseToJsonElement("\"text\"")) && element["text"] != null) -> TranscriptBlock.Variant1(input.json.decodeFromJsonElement(element)) + (element is JsonObject && element["type"] != null && (element["type"] == Json.parseToJsonElement("\"thinking\"")) && element["thinking"] != null) -> TranscriptBlock.Variant2(input.json.decodeFromJsonElement(element)) + (element is JsonObject && element["type"] != null && (element["type"] == Json.parseToJsonElement("\"image\"")) && element["mimeType"] != null) -> TranscriptBlock.Variant3(input.json.decodeFromJsonElement(element)) + (element is JsonObject && element["type"] != null && (element["type"] == Json.parseToJsonElement("\"toolCall\"")) && element["id"] != null && element["name"] != null && element["arguments"] != null) -> TranscriptBlock.Variant4(input.json.decodeFromJsonElement(element)) + else -> throw SerializationException("Unknown TranscriptBlock variant") + } + } + override fun serialize(encoder: Encoder, value: TranscriptBlock) { + val output = encoder as JsonEncoder + output.encodeJsonElement(when (value) { + is TranscriptBlock.Variant1 -> output.json.encodeToJsonElement(value.value) + is TranscriptBlock.Variant2 -> output.json.encodeToJsonElement(value.value) + is TranscriptBlock.Variant3 -> output.json.encodeToJsonElement(value.value) + is TranscriptBlock.Variant4 -> output.json.encodeToJsonElement(value.value) + }) + } +} + +@Serializable +data class TranscriptImageBlock( + val `type`: String, + val `mimeType`: String, +) + @Serializable data class TranscriptMessage( val `id`: String, @@ -2925,22 +3925,24 @@ data class TranscriptMessage( val `requestId`: String? = null, val `role`: String, val `content`: String, - val `blocks`: JsonElement? = null, + val `blocks`: List? = null, val `stopReason`: String? = null, val `timestamp`: Double? = null, val `kind`: String? = null, val `replyTo`: String? = null, val `replyPreview`: String? = null, + val `replyReferences`: List, val `origin`: MessageOrigin? = null, val `communication`: BotCommunication? = null, val `jobQuestion`: TranscriptMessageJobQuestion? = null, val `heldAction`: TranscriptMessageHeldAction? = null, val `call`: TranscriptMessageCall? = null, - val `attachments`: List? = null, + val `files`: List? = null, val `toolCallId`: String? = null, val `toolName`: String? = null, val `isError`: Boolean? = null, val `toolDetails`: JsonElement? = null, + val `presentation`: MessagePresentation? = null, val `sources`: List? = null, ) @@ -2951,6 +3953,45 @@ data class TranscriptMessageCall( val `callee`: String? = null, ) +@Serializable(with = TranscriptMessageFilesItemCodec::class) +sealed class TranscriptMessageFilesItem { + data class Variant1(val value: TranscriptMessageFilesItemVariant1) : TranscriptMessageFilesItem() + data class Variant2(val value: TranscriptMessageFilesItemVariant2) : TranscriptMessageFilesItem() +} +object TranscriptMessageFilesItemCodec : KSerializer { + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("TranscriptMessageFilesItem") + override fun deserialize(decoder: Decoder): TranscriptMessageFilesItem { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement() + return when { + (element is JsonObject && element["id"] != null && element["name"] != null && element["mimeType"] != null && element["size"] != null) -> TranscriptMessageFilesItem.Variant1(input.json.decodeFromJsonElement(element)) + (element is JsonObject && element["id"] != null && element["deleted"] != null && (element["deleted"] == Json.parseToJsonElement("true"))) -> TranscriptMessageFilesItem.Variant2(input.json.decodeFromJsonElement(element)) + else -> throw SerializationException("Unknown TranscriptMessageFilesItem variant") + } + } + override fun serialize(encoder: Encoder, value: TranscriptMessageFilesItem) { + val output = encoder as JsonEncoder + output.encodeJsonElement(when (value) { + is TranscriptMessageFilesItem.Variant1 -> output.json.encodeToJsonElement(value.value) + is TranscriptMessageFilesItem.Variant2 -> output.json.encodeToJsonElement(value.value) + }) + } +} + +@Serializable +data class TranscriptMessageFilesItemVariant1( + val `id`: String, + val `name`: String, + val `mimeType`: String, + val `size`: Double, +) + +@Serializable +data class TranscriptMessageFilesItemVariant2( + val `id`: String, + val `deleted`: Boolean, +) + @Serializable data class TranscriptMessageHeldAction( val `id`: String, @@ -2966,6 +4007,59 @@ data class TranscriptMessageJobQuestion( val `multiple`: Boolean? = null, ) +@Serializable +data class TranscriptMessageReplyReferencesItem( + val `eventId`: String, + val `surface`: TranscriptMessageReplyReferencesItemSurface, +) + +@Serializable(with = TranscriptMessageReplyReferencesItemSurfaceCodec::class) +sealed class TranscriptMessageReplyReferencesItemSurface { + data class Variant1(val value: TranscriptMessageReplyReferencesItemSurfaceVariant1) : TranscriptMessageReplyReferencesItemSurface() + data class Variant2(val value: TranscriptMessageReplyReferencesItemSurfaceVariant2) : TranscriptMessageReplyReferencesItemSurface() + data class Variant3(val value: TranscriptMessageReplyReferencesItemSurfaceVariant3) : TranscriptMessageReplyReferencesItemSurface() +} +object TranscriptMessageReplyReferencesItemSurfaceCodec : KSerializer { + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("TranscriptMessageReplyReferencesItemSurface") + override fun deserialize(decoder: Decoder): TranscriptMessageReplyReferencesItemSurface { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement() + val matches = listOf((element is JsonObject && element["kind"] != null && (element["kind"] == Json.parseToJsonElement("\"text\""))), (element is JsonObject && element["kind"] != null && (element["kind"] == Json.parseToJsonElement("\"tool-card\"")) && element["toolCallId"] != null), (element is JsonObject && element["kind"] != null && (element["kind"] == Json.parseToJsonElement("\"held-action\"")) && element["actionId"] != null)) + require(matches.count { it } == 1) { "Expected exactly one TranscriptMessageReplyReferencesItemSurface variant" } + return when { + (element is JsonObject && element["kind"] != null && (element["kind"] == Json.parseToJsonElement("\"text\""))) -> TranscriptMessageReplyReferencesItemSurface.Variant1(input.json.decodeFromJsonElement(element)) + (element is JsonObject && element["kind"] != null && (element["kind"] == Json.parseToJsonElement("\"tool-card\"")) && element["toolCallId"] != null) -> TranscriptMessageReplyReferencesItemSurface.Variant2(input.json.decodeFromJsonElement(element)) + (element is JsonObject && element["kind"] != null && (element["kind"] == Json.parseToJsonElement("\"held-action\"")) && element["actionId"] != null) -> TranscriptMessageReplyReferencesItemSurface.Variant3(input.json.decodeFromJsonElement(element)) + else -> throw SerializationException("Unknown TranscriptMessageReplyReferencesItemSurface variant") + } + } + override fun serialize(encoder: Encoder, value: TranscriptMessageReplyReferencesItemSurface) { + val output = encoder as JsonEncoder + output.encodeJsonElement(when (value) { + is TranscriptMessageReplyReferencesItemSurface.Variant1 -> output.json.encodeToJsonElement(value.value) + is TranscriptMessageReplyReferencesItemSurface.Variant2 -> output.json.encodeToJsonElement(value.value) + is TranscriptMessageReplyReferencesItemSurface.Variant3 -> output.json.encodeToJsonElement(value.value) + }) + } +} + +@Serializable +data class TranscriptMessageReplyReferencesItemSurfaceVariant1( + val `kind`: String, +) + +@Serializable +data class TranscriptMessageReplyReferencesItemSurfaceVariant2( + val `kind`: String, + val `toolCallId`: String, +) + +@Serializable +data class TranscriptMessageReplyReferencesItemSurfaceVariant3( + val `kind`: String, + val `actionId`: String, +) + @Serializable data class TranscriptMessageSourcesItem( val `url`: String, @@ -2979,6 +4073,27 @@ data class TranscriptPage( val `oldestEntryId`: String?, ) +@Serializable +data class TranscriptTextBlock( + val `type`: String, + val `text`: String, +) + +@Serializable +data class TranscriptThinkingBlock( + val `type`: String, + val `thinking`: String, + val `redacted`: Boolean? = null, +) + +@Serializable +data class TranscriptToolCallBlock( + val `type`: String, + val `id`: String, + val `name`: String, + val `arguments`: Map, +) + @Serializable data class UpdateAgentMemoryRequest( val `content`: String, @@ -3383,6 +4498,12 @@ data class UpdateWebSearchResponse( val `exaKeyConfigured`: Boolean, ) +@Serializable +data class UploadFile( + val `file`: LibraryFile, + val `existed`: Boolean, +) + @Serializable data class VisionChoice( val `provider`: String, diff --git a/app/src/main/java/dev/crumble/android/generated/ContractOperations.kt b/app/src/main/java/dev/crumble/android/generated/ContractOperations.kt index c099c5d..a1a1dad 100644 --- a/app/src/main/java/dev/crumble/android/generated/ContractOperations.kt +++ b/app/src/main/java/dev/crumble/android/generated/ContractOperations.kt @@ -1,4 +1,4 @@ -// Generated by scripts/generate-contract.py 1.2.0. Do not edit. +// Generated by scripts/generate-contract.py 1.3.0. Do not edit. package dev.crumble.android.generated import kotlinx.serialization.* @@ -51,12 +51,18 @@ class ContractOperations(private val boundary: ContractBoundary) { boundary.send("DELETE", path, null, timeoutMs) } - suspend fun putPushPresence(body: PutPushPresenceRequest, `installationId`: String, timeoutMs: Int = 20_000): Unit { + suspend fun putChatAttentionView(body: PutChatAttentionViewRequest, `viewId`: String, timeoutMs: Int = 20_000): Unit { val query = mutableListOf() - val path = "/v1/push/devices/${boundary.escape(`installationId`)}/presence" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val path = "/v1/chat-attention/views/${boundary.escape(`viewId`)}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") boundary.send("PUT", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) } + suspend fun postChatAttentionSeen(body: PostChatAttentionSeenRequest, timeoutMs: Int = 20_000): Unit { + val query = mutableListOf() + val path = "/v1/chat-attention/seen" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + boundary.send("POST", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + } + suspend fun listUsers(timeoutMs: Int = 20_000): ListUsersResponse { val query = mutableListOf() val path = "/v1/admin/users" + if (query.isEmpty()) "" else "?" + query.joinToString("&") @@ -457,13 +463,13 @@ class ContractOperations(private val boundary: ContractBoundary) { boundary.send("POST", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) } - suspend fun getCodingJobHistory(`id`: String, `name`: String, `limit`: Long? = null, `before`: String? = null, timeoutMs: Int = 20_000): TranscriptPage { + suspend fun getCodingJobHistory(`id`: String, `name`: String, `limit`: Long? = null, `before`: String? = null, timeoutMs: Int = 20_000): JobHistoryPage { val query = mutableListOf() `limit`?.let { query.add("limit=" + boundary.escape(it.toString())) } `before`?.let { query.add("before=" + boundary.escape(it)) } val path = "/v1/agents/${boundary.escape(`id`)}/coding-jobs/${boundary.escape(`name`)}/history" + if (query.isEmpty()) "" else "?" + query.joinToString("&") val bytes = boundary.send("GET", path, null, timeoutMs) - return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) } suspend fun listDesktopJobs(`id`: String, timeoutMs: Int = 20_000): DesktopJobs { @@ -508,13 +514,13 @@ class ContractOperations(private val boundary: ContractBoundary) { return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) } - suspend fun getDesktopJobHistory(`id`: String, `name`: String, `limit`: Long? = null, `before`: String? = null, timeoutMs: Int = 20_000): TranscriptPage { + suspend fun getDesktopJobHistory(`id`: String, `name`: String, `limit`: Long? = null, `before`: String? = null, timeoutMs: Int = 20_000): JobHistoryPage { val query = mutableListOf() `limit`?.let { query.add("limit=" + boundary.escape(it.toString())) } `before`?.let { query.add("before=" + boundary.escape(it)) } val path = "/v1/agents/${boundary.escape(`id`)}/desktop-jobs/${boundary.escape(`name`)}/history" + if (query.isEmpty()) "" else "?" + query.joinToString("&") val bytes = boundary.send("GET", path, null, timeoutMs) - return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) } suspend fun sendMessage(body: SendMessageRequest, `id`: String, timeoutMs: Int = 20_000): Execution { @@ -524,6 +530,68 @@ class ContractOperations(private val boundary: ContractBoundary) { return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) } + suspend fun uploadFile(body: ByteArray, `id`: String, `x-file-name`: String, `content-type`: String, timeoutMs: Int = 20_000): UploadFile { + val query = mutableListOf() + val path = "/v1/agents/${boundary.escape(`id`)}/files" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val headers = mutableMapOf() + `x-file-name`.let { headers["x-file-name"] = it } + `content-type`.let { headers["content-type"] = it } + val bytes = boundary.send("POST", path, body, timeoutMs, headers) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun listFiles(`id`: String, `before`: String? = null, `limit`: Long? = null, timeoutMs: Int = 20_000): List { + val query = mutableListOf() + `before`?.let { query.add("before=" + boundary.escape(it)) } + `limit`?.let { query.add("limit=" + boundary.escape(it.toString())) } + val path = "/v1/agents/${boundary.escape(`id`)}/files" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString>(bytes.toString(Charsets.UTF_8)) + } + + suspend fun getFile(`id`: String, `fileId`: String, timeoutMs: Int = 20_000): ByteArray { + val query = mutableListOf() + val path = "/v1/agents/${boundary.escape(`id`)}/files/${boundary.escape(`fileId`)}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + return boundary.send("GET", path, null, timeoutMs) + } + + suspend fun deleteFile(`id`: String, `fileId`: String, timeoutMs: Int = 20_000): Unit { + val query = mutableListOf() + val path = "/v1/agents/${boundary.escape(`id`)}/files/${boundary.escape(`fileId`)}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + boundary.send("DELETE", path, null, timeoutMs) + } + + suspend fun uploadGroupFile(body: ByteArray, `id`: String, `x-file-name`: String, `content-type`: String, timeoutMs: Int = 20_000): UploadFile { + val query = mutableListOf() + val path = "/v1/group-chats/${boundary.escape(`id`)}/files" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val headers = mutableMapOf() + `x-file-name`.let { headers["x-file-name"] = it } + `content-type`.let { headers["content-type"] = it } + val bytes = boundary.send("POST", path, body, timeoutMs, headers) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun listGroupFiles(`id`: String, `before`: String? = null, `limit`: Long? = null, timeoutMs: Int = 20_000): List { + val query = mutableListOf() + `before`?.let { query.add("before=" + boundary.escape(it)) } + `limit`?.let { query.add("limit=" + boundary.escape(it.toString())) } + val path = "/v1/group-chats/${boundary.escape(`id`)}/files" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString>(bytes.toString(Charsets.UTF_8)) + } + + suspend fun getGroupFile(`id`: String, `fileId`: String, timeoutMs: Int = 20_000): ByteArray { + val query = mutableListOf() + val path = "/v1/group-chats/${boundary.escape(`id`)}/files/${boundary.escape(`fileId`)}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + return boundary.send("GET", path, null, timeoutMs) + } + + suspend fun deleteGroupFile(`id`: String, `fileId`: String, timeoutMs: Int = 20_000): Unit { + val query = mutableListOf() + val path = "/v1/group-chats/${boundary.escape(`id`)}/files/${boundary.escape(`fileId`)}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + boundary.send("DELETE", path, null, timeoutMs) + } + suspend fun getAttachment(`id`: String, `entryId`: String, `index`: Long?, timeoutMs: Int = 20_000): ByteArray { val query = mutableListOf() val path = "/v1/agents/${boundary.escape(`id`)}/attachments/${boundary.escape(`entryId`)}/${boundary.escape(`index`.toString())}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") @@ -615,12 +683,6 @@ class ContractOperations(private val boundary: ContractBoundary) { return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) } - suspend fun getGroupAttachment(`id`: String, `entryId`: String, `index`: Long?, timeoutMs: Int = 20_000): ByteArray { - val query = mutableListOf() - val path = "/v1/group-chats/${boundary.escape(`id`)}/attachments/${boundary.escape(`entryId`)}/${boundary.escape(`index`.toString())}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") - return boundary.send("GET", path, null, timeoutMs) - } - suspend fun stopGroupChat(`id`: String, timeoutMs: Int = 20_000): Unit { val query = mutableListOf() val path = "/v1/group-chats/${boundary.escape(`id`)}/stop" + if (query.isEmpty()) "" else "?" + query.joinToString("&") @@ -973,6 +1035,13 @@ class ContractOperations(private val boundary: ContractBoundary) { return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) } + suspend fun previewSchedule(body: PreviewScheduleRequest, timeoutMs: Int = 20_000): SchedulePreview { + val query = mutableListOf() + val path = "/v1/schedules/preview" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("POST", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + suspend fun updateSchedule(body: UpdateScheduleRequest, `id`: String, timeoutMs: Int = 20_000): Schedule? { val query = mutableListOf() val path = "/v1/schedules/${boundary.escape(`id`)}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") @@ -1028,6 +1097,13 @@ class ContractOperations(private val boundary: ContractBoundary) { return boundary.json.decodeFromString>(bytes.toString(Charsets.UTF_8)) } + suspend fun previewReasoning(body: PreviewReasoningRequest, timeoutMs: Int = 20_000): ReasoningPreview { + val query = mutableListOf() + val path = "/v1/reasoning/preview" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("POST", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + suspend fun listModels(`provider`: String? = null, timeoutMs: Int = 20_000): List { val query = mutableListOf() `provider`?.let { query.add("provider=" + boundary.escape(it)) } diff --git a/app/src/main/java/dev/crumble/android/generated/event-projection.json b/app/src/main/java/dev/crumble/android/generated/event-projection.json index 20592b3..2622c4b 100644 --- a/app/src/main/java/dev/crumble/android/generated/event-projection.json +++ b/app/src/main/java/dev/crumble/android/generated/event-projection.json @@ -6,6 +6,152 @@ }, "components": { "schemas": { + "Citation": { + "type": "object", + "properties": { + "href": { + "type": "string" + }, + "title": { + "type": "string" + }, + "site": { + "type": "string" + } + }, + "required": [ + "href", + "title", + "site" + ] + }, + "MessagePresentation": { + "type": "object", + "properties": { + "text": { + "type": "string" + }, + "citations": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Citation" + } + } + }, + "required": [ + "text", + "citations" + ] + }, + "TranscriptBlock": { + "oneOf": [ + { + "$ref": "#/components/schemas/TranscriptTextBlock" + }, + { + "$ref": "#/components/schemas/TranscriptThinkingBlock" + }, + { + "$ref": "#/components/schemas/TranscriptImageBlock" + }, + { + "$ref": "#/components/schemas/TranscriptToolCallBlock" + } + ], + "discriminator": { + "propertyName": "type", + "mapping": { + "text": "#/components/schemas/TranscriptTextBlock", + "thinking": "#/components/schemas/TranscriptThinkingBlock", + "image": "#/components/schemas/TranscriptImageBlock", + "toolCall": "#/components/schemas/TranscriptToolCallBlock" + } + } + }, + "TranscriptImageBlock": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "image" + ] + }, + "mimeType": { + "type": "string" + } + }, + "required": [ + "type", + "mimeType" + ] + }, + "TranscriptTextBlock": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "text" + ] + }, + "text": { + "type": "string" + } + }, + "required": [ + "type", + "text" + ] + }, + "TranscriptThinkingBlock": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "thinking" + ] + }, + "thinking": { + "type": "string" + }, + "redacted": { + "type": "boolean" + } + }, + "required": [ + "type", + "thinking" + ] + }, + "TranscriptToolCallBlock": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "toolCall" + ] + }, + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "arguments": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "type", + "id", + "name", + "arguments" + ] + }, "SnapshotEventPayload": { "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", @@ -30,7 +176,12 @@ "content": { "type": "string" }, - "blocks": {}, + "blocks": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TranscriptBlock" + } + }, "stopReason": { "type": "string" }, @@ -46,6 +197,76 @@ "replyPreview": { "type": "string" }, + "replyReferences": { + "type": "array", + "items": { + "type": "object", + "properties": { + "eventId": { + "type": "string", + "minLength": 1 + }, + "surface": { + "oneOf": [ + { + "type": "object", + "properties": { + "kind": { + "type": "string", + "const": "text" + } + }, + "required": [ + "kind" + ], + "additionalProperties": true + }, + { + "type": "object", + "properties": { + "kind": { + "type": "string", + "const": "tool-card" + }, + "toolCallId": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "kind", + "toolCallId" + ], + "additionalProperties": true + }, + { + "type": "object", + "properties": { + "kind": { + "type": "string", + "const": "held-action" + }, + "actionId": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "kind", + "actionId" + ], + "additionalProperties": true + } + ] + } + }, + "required": [ + "eventId", + "surface" + ], + "additionalProperties": true + } + }, "origin": { "type": "object", "properties": { @@ -176,35 +397,52 @@ ], "additionalProperties": true }, - "attachments": { + "files": { "type": "array", "items": { - "type": "object", - "properties": { - "name": { - "type": "string" + "anyOf": [ + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "mimeType": { + "type": "string" + }, + "size": { + "type": "number" + } + }, + "required": [ + "id", + "name", + "mimeType", + "size" + ], + "additionalProperties": true }, - "mimeType": { - "type": "string" - }, - "size": { - "type": "number" - }, - "kind": { - "type": "string", - "enum": [ - "image", - "text" - ] + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "deleted": { + "type": "boolean", + "const": true + } + }, + "required": [ + "id", + "deleted" + ], + "additionalProperties": true } - }, - "required": [ - "name", - "mimeType", - "size", - "kind" - ], - "additionalProperties": true + ] } }, "toolCallId": { @@ -217,6 +455,9 @@ "type": "boolean" }, "toolDetails": {}, + "presentation": { + "$ref": "#/components/schemas/MessagePresentation" + }, "sources": { "type": "array", "items": { @@ -241,7 +482,8 @@ "id", "entryId", "role", - "content" + "content", + "replyReferences" ], "additionalProperties": true } @@ -305,6 +547,19 @@ "failed" ] }, + "working": { + "type": "string", + "enum": [ + "idle", + "thinking", + "writing", + "searching", + "remembering", + "tinkering", + "struggling", + "failed" + ] + }, "updatedAt": { "type": "number" }, @@ -324,11 +579,451 @@ "conversation", "partial", "status", + "working", "updatedAt", "error" ], "additionalProperties": true }, + "GroupSnapshotEventPayload": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "messages": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "entryId": { + "type": "string" + }, + "requestId": { + "type": "string" + }, + "role": { + "type": "string" + }, + "content": { + "type": "string" + }, + "blocks": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TranscriptBlock" + } + }, + "stopReason": { + "type": "string" + }, + "timestamp": { + "type": "number" + }, + "kind": { + "type": "string" + }, + "replyTo": { + "type": "string" + }, + "replyPreview": { + "type": "string" + }, + "replyReferences": { + "type": "array", + "items": { + "type": "object", + "properties": { + "eventId": { + "type": "string", + "minLength": 1 + }, + "surface": { + "oneOf": [ + { + "type": "object", + "properties": { + "kind": { + "type": "string", + "const": "text" + } + }, + "required": [ + "kind" + ], + "additionalProperties": true + }, + { + "type": "object", + "properties": { + "kind": { + "type": "string", + "const": "tool-card" + }, + "toolCallId": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "kind", + "toolCallId" + ], + "additionalProperties": true + }, + { + "type": "object", + "properties": { + "kind": { + "type": "string", + "const": "held-action" + }, + "actionId": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "kind", + "actionId" + ], + "additionalProperties": true + } + ] + } + }, + "required": [ + "eventId", + "surface" + ], + "additionalProperties": true + } + }, + "origin": { + "type": "object", + "properties": { + "kind": { + "type": "string" + }, + "name": { + "type": "string" + }, + "agentId": { + "type": "string" + }, + "via": { + "type": "string" + }, + "source": { + "type": "string" + } + }, + "required": [ + "kind" + ], + "additionalProperties": true + }, + "communication": { + "type": "object", + "properties": { + "executionId": { + "type": "string" + }, + "fromAgentId": { + "type": "string" + }, + "fromName": { + "type": "string" + }, + "toAgentId": { + "type": "string" + }, + "toName": { + "type": "string" + }, + "status": { + "type": "string", + "enum": [ + "sent", + "done", + "failed", + "cancelled" + ] + } + }, + "required": [ + "executionId", + "fromAgentId", + "fromName", + "toAgentId", + "toName", + "status" + ], + "additionalProperties": true + }, + "jobQuestion": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "kind": { + "type": "string" + }, + "job": { + "type": "string" + }, + "options": { + "type": "array", + "items": { + "type": "string" + } + }, + "multiple": { + "type": "boolean" + } + }, + "required": [ + "id", + "kind", + "job" + ], + "additionalProperties": true + }, + "heldAction": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "job": { + "type": "string" + } + }, + "required": [ + "id", + "job" + ], + "additionalProperties": true + }, + "call": { + "type": "object", + "properties": { + "callId": { + "type": "string" + }, + "direction": { + "type": "string", + "enum": [ + "inbound", + "outbound" + ] + }, + "callee": { + "type": "string" + } + }, + "required": [ + "callId", + "direction" + ], + "additionalProperties": true + }, + "files": { + "type": "array", + "items": { + "anyOf": [ + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "mimeType": { + "type": "string" + }, + "size": { + "type": "number" + } + }, + "required": [ + "id", + "name", + "mimeType", + "size" + ], + "additionalProperties": true + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "deleted": { + "type": "boolean", + "const": true + } + }, + "required": [ + "id", + "deleted" + ], + "additionalProperties": true + } + ] + } + }, + "toolCallId": { + "type": "string" + }, + "toolName": { + "type": "string" + }, + "isError": { + "type": "boolean" + }, + "toolDetails": {}, + "presentation": { + "$ref": "#/components/schemas/MessagePresentation" + }, + "sources": { + "type": "array", + "items": { + "type": "object", + "properties": { + "url": { + "type": "string" + }, + "title": { + "type": "string" + } + }, + "required": [ + "url", + "title" + ], + "additionalProperties": true + } + } + }, + "required": [ + "id", + "entryId", + "role", + "content", + "replyReferences" + ], + "additionalProperties": true + } + }, + "hasMore": { + "type": "boolean" + }, + "oldestEntryId": { + "type": [ + "string", + "null" + ] + }, + "groupChat": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "memberIds": { + "type": "array", + "items": { + "type": "string" + } + }, + "createdAt": { + "type": "string" + }, + "updatedAt": { + "type": "string" + } + }, + "required": [ + "id", + "name", + "memberIds", + "createdAt", + "updatedAt" + ], + "additionalProperties": true + }, + "activity": { + "type": "object", + "properties": { + "paused": { + "type": "boolean" + }, + "botTurns": { + "type": "number" + }, + "members": { + "type": "array", + "items": { + "type": "object", + "properties": { + "agentId": { + "type": "string" + }, + "status": { + "type": "string", + "enum": [ + "idle", + "queued", + "running", + "disabled" + ] + }, + "error": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "agentId", + "status", + "error" + ], + "additionalProperties": true + } + } + }, + "required": [ + "paused", + "botTurns", + "members" + ], + "additionalProperties": true + }, + "updatedAt": { + "type": "number" + } + }, + "required": [ + "messages", + "hasMore", + "oldestEntryId", + "groupChat", + "activity", + "updatedAt" + ], + "additionalProperties": true + }, "ActivityEventPayload": { "$schema": "https://json-schema.org/draft/2020-12/schema", "oneOf": [ diff --git a/app/src/main/java/dev/crumble/android/model/AppModel.kt b/app/src/main/java/dev/crumble/android/model/AppModel.kt index f82e5cd..e9f8fb8 100644 --- a/app/src/main/java/dev/crumble/android/model/AppModel.kt +++ b/app/src/main/java/dev/crumble/android/model/AppModel.kt @@ -1,6 +1,7 @@ package dev.crumble.android.model import kotlinx.serialization.builtins.ListSerializer +import dev.crumble.android.generated.JobHistoryItem import kotlinx.serialization.json.JsonObject import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue @@ -30,6 +31,8 @@ import dev.crumble.android.network.UrlConnectionTransport import dev.crumble.android.network.domain import dev.crumble.android.network.edited import dev.crumble.android.network.friendlyError +import dev.crumble.android.push.ChatAttention +import dev.crumble.android.push.ChatAttentionChat import dev.crumble.android.storage.CredentialStore import dev.crumble.android.storage.InMemoryCredentialStore import dev.crumble.android.ui.BotState @@ -39,6 +42,10 @@ import java.time.Instant import java.time.ZoneId import java.time.temporal.ChronoUnit import java.util.UUID +import dev.crumble.android.generated.ReasoningPreview +import dev.crumble.android.generated.SchedulePreview +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers @@ -243,6 +250,24 @@ class AppModel( private val onSessionReset: () -> Unit = {}, private val onNotificationsChanged: () -> Unit = {}, ) { + val chatAttention = ChatAttention(scope) + var attentionWindowID: String = "" + private set + + fun newAttentionView(): String { + attentionWindowID = newRequestID() + chatAttention.newView() + return attentionWindowID + } + + private var botSnapshotRevision = 0 + private var groupSnapshotRevision = 0 + private var attentionRefresh: Job? = null + + fun updateChatAttention() { + chatAttention.update(client, appActive, route.attentionChat()) + } + var serverURL by mutableStateOf("http://127.0.0.1:7337") var token by mutableStateOf("") var email by mutableStateOf("") @@ -408,6 +433,7 @@ class AppModel( val content: String, val replyTo: String, val attachments: List, + val uploadedFiles: MutableMap = mutableMapOf(), ) private data class PendingPreview( @@ -435,9 +461,10 @@ class AppModel( private var groupStream: Job? = null private var groupVersion = 0 - /** Sent image bytes, keyed by "entryId/index"; they never change once sent. */ + /** File bytes are scoped to the connection and chat; screenshots retain their entry/index key. */ var attachmentBytes by mutableStateOf>(emptyMap()) private set + private val deletedFileKeys = mutableSetOf() private var activeRequests = 0 var pendingMutations by mutableStateOf>(emptySet()) @@ -515,7 +542,13 @@ class AppModel( var agentDraft by mutableStateOf(null) var memoryDraft by mutableStateOf(null) - var taskDraft by mutableStateOf(null) + private var taskDraftState by mutableStateOf(null) + var taskDraft: TaskDraft? + get() = taskDraftState + set(value) { + if (taskDraftState?.let(::scheduleKey) != value?.let(::scheduleKey)) schedulePreviewState = null + taskDraftState = value + } var eventSourceDraft by mutableStateOf(null) var skillDraft by mutableStateOf(null) var showingPalette by mutableStateOf(false) @@ -574,7 +607,7 @@ class AppModel( var confirmingDelete by mutableStateOf(false) - var appActive: Boolean = true + var appActive by mutableStateOf(true) init { if (loadCredentials) { @@ -861,6 +894,7 @@ class AppModel( /** Keeps older pages the owner already loaded; snapshots only carry the newest page. */ fun applySnapshot(incoming: ChatSnapshot) { + botSnapshotRevision += 1 val incomingMessages = incoming.messages ?: emptyList() val acknowledged = incomingMessages.mapNotNull { it.requestId }.toSet() if (acknowledged.isNotEmpty()) { @@ -890,7 +924,7 @@ class AppModel( incomingMessages, ) } - messages = confirmed + local + messages = reconcileDeletedFiles("bot/$selectedAgentID", confirmed + local) snapshot = incoming.copy(messages = null) cacheRecentChat() followDecisions() @@ -1151,10 +1185,23 @@ class AppModel( private suspend fun loadJobHistory(api: APIClient, agentID: String, job: JobRef, version: Int) { try { + val pending = jobPanel?.takeIf { jobPanelVersion == version }?.items + ?.filterIsInstance()?.filter { it.value.result == null }?.map { it.value.id }?.toMutableSet() ?: return val page = api.jobHistory(agentID, job, before = null, limit = JOB_PAGE_SIZE) + val refreshed = page.items.associateByTo(mutableMapOf()) { it.id } + pending.removeAll(refreshed.keys) + var next = page.oldestEntryId.takeIf { page.hasMore } + val visited = mutableSetOf() + while (pending.isNotEmpty() && next != null && visited.add(next)) { + val older = api.jobHistory(agentID, job, before = next, limit = JOB_PAGE_SIZE) + older.items.filter { it.id in pending }.forEach { refreshed[it.id] = it } + pending.removeAll(refreshed.keys) + next = older.oldestEntryId.takeIf { older.hasMore } + } val panel = jobPanel?.takeIf { jobPanelVersion == version } ?: return jobPanel = panel.copy( - messages = mergeJobPages(panel.messages, page.messages.orEmpty()), + messages = mergeJobPages(panel.messages, page.messages), + items = mergeJobItems(panel.items.map { refreshed[it.id] ?: it }, page.items), hasMore = if (panel.loaded) panel.hasMore else page.hasMore == true, oldestEntryID = if (panel.loaded) panel.oldestEntryID else page.oldestEntryId, loaded = true, @@ -1240,8 +1287,10 @@ class AppModel( val page = api.jobHistory(agentID, panel.job, before, JOB_PAGE_SIZE) val current = jobPanel?.takeIf { jobPanelVersion == version } ?: return@launch val known = current.messages.map { it.id }.toSet() + val knownItems = current.items.map { it.id }.toSet() jobPanel = current.copy( - messages = page.messages.orEmpty().filterNot { it.id in known } + current.messages, + messages = page.messages.filterNot { it.id in known } + current.messages, + items = page.items.filterNot { it.id in knownItems } + current.items, hasMore = page.hasMore == true, oldestEntryID = page.oldestEntryId, loadingEarlier = false, @@ -1526,10 +1575,35 @@ class AppModel( agents = updated } } + if (event.type == "reply") refreshAttentionReferences(event) val context = NotificationContext(appActive = appActive, route = route) notifier.handle(event, context) } + private fun refreshAttentionReferences(event: ActivityEvent) { + val api = client ?: return + if (!appActive) return + val chat = if (!event.groupId.isNullOrEmpty()) ChatAttentionChat("group", event.groupId) else ChatAttentionChat("bot", event.agentId) + if (route.attentionChat() != chat) return + val version = if (chat.kind == "group") groupVersion else selectionVersion + val revision = if (chat.kind == "group") groupSnapshotRevision else botSnapshotRevision + attentionRefresh?.cancel() + attentionRefresh = scope.launch { + try { + if (chat.kind == "group") { + val incoming = api.groupSnapshot(chat.id) + if (client === api && route.attentionChat() == chat && groupVersion == version && groupSnapshotRevision == revision) applyGroupSnapshot(incoming) + } else { + val incoming = api.chat(chat.id, limit = 5) + if (client === api && route.attentionChat() == chat && selectionVersion == version && botSnapshotRevision == revision) applySnapshot(incoming) + } + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + } + } + } + fun loadOlder() { if (awaitingInitialSnapshot || loadingOlder || !hasMore || oldestEntryID.isEmpty()) return val id = selectedAgentID @@ -1542,7 +1616,7 @@ class AppModel( return@request { if (selectionVersion == version) { loadingOlder = false - messages = mergeMessages(messages, page.messages ?: emptyList()) + messages = reconcileDeletedFiles("bot/$id", mergeMessages(messages, page.messages ?: emptyList())) hasMore = page.hasMore ?: false oldestEntryID = page.oldestEntryId ?: "" } @@ -1644,18 +1718,22 @@ class AppModel( val gen = generation scope.launch { try { + val files = uploadFiles(record, { generation == gen && pendingSends[id]?.get(requestID) === record }) { + api.uploadFile(id, it) + } api.sendChatMessage( agentID = id, content = record.content, requestID = requestID, replyTo = record.replyTo, - attachments = record.attachments.map { it.outgoing }, + files = files, ) if (generation != gen) return@launch } catch (e: CancellationException) { throw e } catch (e: Throwable) { if (generation != gen || !markMessage(id, requestID, MessageDeliveryState.failed)) return@launch + discardRejectedFiles(record, e) if (selectedAgentID == id) errorText = "Message was not confirmed: ${friendlyError(e)}" if (restoreDraft) restoreComposer(id, record) } @@ -1663,6 +1741,36 @@ class AppModel( } } + private suspend fun uploadFiles( + record: PendingSend, + isCurrent: () -> Boolean, + upload: suspend (PendingAttachment) -> String, + ): List { + fun checkCurrent() { + if (!isCurrent()) throw CancellationException("Send no longer belongs to this connection or chat") + } + checkCurrent() + val files = record.attachments.map { attachment -> + currentCoroutineContext().ensureActive() + checkCurrent() + record.uploadedFiles[attachment.id] ?: upload(attachment).also { id -> + currentCoroutineContext().ensureActive() + checkCurrent() + record.uploadedFiles[attachment.id] = id + } + } + checkCurrent() + return files + } + + private fun discardRejectedFiles(record: PendingSend, error: Throwable) { + if (error !is APIError || error.statusCode != 400) return + val message = friendlyError(error) + if (message == "File not found in this library" || message.endsWith(" was deleted from the library")) { + record.uploadedFiles.clear() + } + } + /** Text the owner wrote since sending is never overwritten; the failed row still holds the message. */ private fun restoreComposer(id: String, record: PendingSend) { if (selectedAgentID == id) { @@ -1691,10 +1799,30 @@ class AppModel( attachments = attachments.filterNot { it.id == id } } + private fun reconcileDeletedFiles(chat: String, transcript: List): List { + for (message in transcript) { + for (file in message.attachments.orEmpty()) { + if (file.deleted && file.id.isNotEmpty()) deletedFileKeys.add("$generation/$chat/${file.id}") + } + } + if (deletedFileKeys.isEmpty()) return transcript + attachmentBytes = attachmentBytes.filterKeys { it !in deletedFileKeys } + return transcript.map { message -> + val files = message.attachments ?: return@map message + if (files.none { !it.deleted && "$generation/$chat/${it.id}" in deletedFileKeys }) return@map message + message.copy(attachments = files.map { file -> + if ("$generation/$chat/${file.id}" in deletedFileKeys) AttachmentInfo(id = file.id, deleted = true) else file + }) + } + } + fun attachmentImageBytes(message: Message, index: Int): ByteArray? { val entryID = message.entryId if (!entryID.isNullOrEmpty()) { - return attachmentBytes["$entryID/$index"] + val file = message.attachments?.getOrNull(index) + if (file?.deleted == true) return null + val key = file?.id?.nilIfEmpty?.let { "$generation/bot/$selectedAgentID/$it" } ?: "$entryID/$index" + return attachmentBytes[key] } val requestID = message.requestId ?: return null val files = pendingSends[selectedAgentID]?.get(requestID)?.attachments ?: return null @@ -1703,18 +1831,28 @@ class AppModel( } suspend fun loadAttachmentImage(entryID: String, index: Int) { - val key = "$entryID/$index" - if (attachmentBytes.containsKey(key)) return val currentClient = client ?: return if (entryID.startsWith("local:")) return val agent = selectedAgentID val gen = generation + val message = messages.firstOrNull { it.entryId == entryID } + val file = message?.attachments?.getOrNull(index) + if (file?.deleted == true) return + val fileID = file?.id?.nilIfEmpty + val key = fileID?.let { "$gen/bot/$agent/$it" } ?: "$entryID/$index" + if (attachmentBytes.containsKey(key)) return try { - val bytes = currentClient.attachment(agent, entryID = entryID, index = index) - if (bytes.isNotEmpty() && generation == gen) { + val bytes = if (fileID != null) currentClient.file(agent, fileID) + else currentClient.attachment(agent, entryID = entryID, index = index) + val latest = messages.firstOrNull { it.entryId == entryID }?.attachments?.getOrNull(index) + val stillVisible = selectedAgentID == agent && + (fileID == null || latest?.let { it.id == fileID && !it.deleted } == true) + if (bytes.isNotEmpty() && generation == gen && stillVisible) { attachmentBytes = attachmentBytes + (key to bytes) } - } catch (_: Throwable) { + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { } } @@ -1828,6 +1966,7 @@ class AppModel( } private fun applyGroupSnapshot(incoming: GroupSnapshot) { + groupSnapshotRevision += 1 val id = incoming.groupChat.id val acknowledged = incoming.messages.mapNotNull { it.requestId }.toSet() val waiting = groupOutgoing[id].orEmpty() @@ -1837,7 +1976,9 @@ class AppModel( } val editing = "group:$id" in pendingMutations updateConversation(id) { current -> - val merged = current.merging(incoming) + val merged = current.merging(incoming).let { + it.copy(messages = reconcileDeletedFiles("group/$id", it.messages)) + } if (editing) merged.copy(group = current.group) else merged } if (!editing) writeGroup(incoming.groupChat, adding = true) @@ -1950,12 +2091,16 @@ class AppModel( updateConversation(id) { it.copy(sendError = null) } scope.launch { try { - api.sendGroupMessage(id, record.content, requestID, record.replyTo, record.attachments.map { it.outgoing }) + val files = uploadFiles(record, { generation == gen && groupSends[requestID] === record }) { + api.uploadGroupFile(id, it) + } + api.sendGroupMessage(id, record.content, requestID, record.replyTo, files) } catch (e: CancellationException) { throw e } catch (e: Throwable) { // A snapshot may already show the message, or the group may be gone. if (generation != gen || groupOutgoing[id].orEmpty().none { it.requestId == requestID }) return@launch + discardRejectedFiles(record, e) markGroupMessage(id, requestID, MessageDeliveryState.failed) updateConversation(id) { it.copy(sendError = "Message was not confirmed: ${friendlyError(e)}") } } @@ -1988,7 +2133,9 @@ class AppModel( scope.launch { try { val page = api.groupHistory(id, before, GROUP_PAGE_SIZE) - if (groupVersion == version) updateConversation(id) { it.adding(page) } + if (groupVersion == version) updateConversation(id) { current -> + current.adding(page).let { it.copy(messages = reconcileDeletedFiles("group/$id", it.messages)) } + } } catch (e: CancellationException) { throw e } catch (e: Exception) { @@ -2001,21 +2148,32 @@ class AppModel( fun groupAttachmentImageBytes(message: Message, index: Int): ByteArray? { val entryID = message.entryId - if (!entryID.isNullOrEmpty()) return attachmentBytes["$entryID/$index"] + if (!entryID.isNullOrEmpty()) { + val file = message.attachments?.getOrNull(index) ?: return null + if (file.deleted || file.id.isEmpty()) return null + val id = groupConversation?.groupID ?: return null + return attachmentBytes["$generation/group/$id/${file.id}"] + } val file = groupSends[message.requestId]?.attachments?.getOrNull(index) return file?.takeIf { it.isImage }?.data } - // Group entry IDs embed the group's ID, so they cannot collide with a bot's in `attachmentBytes`. suspend fun loadGroupAttachmentImage(entryID: String, index: Int) { - val key = "$entryID/$index" val api = client ?: return - val id = groupConversation?.groupID ?: return - if (attachmentBytes.containsKey(key)) return + val conversation = groupConversation ?: return + val id = conversation.groupID + val file = conversation.messages.firstOrNull { it.entryId == entryID }?.attachments?.getOrNull(index) ?: return + if (file.deleted || file.id.isEmpty()) return val gen = generation + val key = "$gen/group/$id/${file.id}" + if (attachmentBytes.containsKey(key)) return try { - val bytes = api.groupAttachment(id, entryID, index) - if (bytes.isNotEmpty() && generation == gen) attachmentBytes = attachmentBytes + (key to bytes) + val bytes = api.groupFile(id, file.id) + val latest = groupConversation?.takeIf { it.groupID == id }?.messages + ?.firstOrNull { it.entryId == entryID }?.attachments?.getOrNull(index) + if (bytes.isNotEmpty() && generation == gen && latest?.let { it.id == file.id && !it.deleted } == true) { + attachmentBytes = attachmentBytes + (key to bytes) + } } catch (e: CancellationException) { throw e } catch (_: Exception) { @@ -2249,12 +2407,22 @@ class AppModel( if (provider.isNotEmpty()) loadDesktopModels(provider) } - /** The levels the editor's model takes. The picked level stays in the draft, so changing back restores it. */ - val editorLevels: List - get() = levelsOf(models.firstOrNull { it.id == agentDraft?.model?.trim() }) + private var reasoningPreviewState by mutableStateOf, ReasoningPreview>>?>(null) + + private fun reasoningKey(draft: AgentDraft) = listOf(draft.id.toString(), draft.botRequestID.orEmpty(), draft.provider, draft.model.trim(), draft.thinking) + + val editorReasoning: ReasoningPreview? + get() = agentDraft?.let { draft -> reasoningPreviewState?.takeIf { it.first === client && it.second.first == reasoningKey(draft) }?.second?.second } val editorLevel: String - get() = clampLevel(agentDraft?.thinking?.ifEmpty { "off" } ?: "off", editorLevels) + get() = editorReasoning?.effectiveLevel ?: agentDraft?.thinking.orEmpty() + + suspend fun refreshEditorReasoning(api: APIClient, draft: AgentDraft) { + val key = reasoningKey(draft) + val result = api.previewReasoning(draft.provider, draft.model.trim(), draft.thinking) + currentCoroutineContext().ensureActive() + if (client === api && agentDraft?.let(::reasoningKey) == key) reasoningPreviewState = api to (key to result) + } val modelHint: String get() { @@ -2557,15 +2725,41 @@ class AppModel( if (settledSince(revision, SCHEDULE_RECORD)) { loadSchedules() } else { - schedules = withLocalChanges(items, schedules, SCHEDULE_RECORD, Schedule::id) - schedulesLoaded = true - schedulesError = "" - if (taskTab == TaskTab.Runs) loadTaskRuns() + applySchedules(items) } } } } + private fun applySchedules(items: List) { + schedules = withLocalChanges(items, schedules, SCHEDULE_RECORD, Schedule::id) + schedulesLoaded = true + schedulesError = "" + if (taskTab == TaskTab.Runs) loadTaskRuns() + } + + suspend fun followTaskSchedules(api: APIClient) { + val gen = generation + while (currentCoroutineContext().isActive) { + delay(60_000) + if (!appActive) continue + if (client !== api || generation != gen || route != Route.Tasks || taskTab != TaskTab.Tasks) return + val revision = mutationRevision + try { + val items = api.schedules() + currentCoroutineContext().ensureActive() + if (client !== api || generation != gen || route != Route.Tasks || taskTab != TaskTab.Tasks) return + if (!settledSince(revision, SCHEDULE_RECORD)) applySchedules(items) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + currentCoroutineContext().ensureActive() + if (client !== api || generation != gen || route != Route.Tasks || taskTab != TaskTab.Tasks) return + schedulesError = friendlyError(e) + } + } + } + fun filterActivity(kind: String? = activityFeed.kind, botID: String? = activityFeed.botID) { if (kind == activityFeed.kind && botID == activityFeed.botID) return activityFeed = ActivityFeedState(kind = kind, botID = botID) @@ -2846,6 +3040,32 @@ class AppModel( taskDraft = form } + private var schedulePreviewState by mutableStateOf, SchedulePreview>>?>(null) + + private fun scheduleKey(draft: TaskDraft) = listOf( + draft.id.toString(), draft.agentID, draft.onEvent.toString(), draft.eventSourceID, + draft.repeats.toString(), draft.cron.trim(), draft.runDate.toString(), draft.timezone.trim(), + ) + + val taskPreview: SchedulePreview? + get() = taskDraft?.let { draft -> schedulePreviewState?.takeIf { it.first === client && it.second.first == scheduleKey(draft) }?.second?.second } + + internal fun acceptSchedulePreview(api: APIClient, draft: TaskDraft, preview: SchedulePreview) { + val key = scheduleKey(draft) + if (client === api && taskDraft?.let(::scheduleKey) == key) schedulePreviewState = api to (key to preview) + } + + suspend fun refreshTaskPreview(api: APIClient, draft: TaskDraft) { + val preview = api.previewSchedule( + cron = draft.cron.trim().takeIf { !draft.onEvent && draft.repeats }, + runAt = draft.runDate.toIso8601SecondString().takeIf { !draft.onEvent && !draft.repeats }, + eventSourceID = draft.eventSourceID.takeIf { draft.onEvent }, + timezone = draft.timezone.trim(), + ) + currentCoroutineContext().ensureActive() + acceptSchedulePreview(api, draft, preview) + } + fun saveTask() { val form = taskDraft ?: return val name = form.name.trim() @@ -2862,19 +3082,19 @@ class AppModel( val validationError = validateTask( name = name, prompt = prompt, - cron = cron, - runAt = runAt, - timezone = timezone, kind = form.kind, command = form.command, timeoutSeconds = form.timeoutSeconds, - onEvent = form.onEvent, - eventSourceID = sourceID, ) if (validationError != null) { errorText = validationError return } + val preview = taskPreview ?: return + if (preview.isProblem) { + errorText = preview.text + return + } val timeoutSeconds = if (isScript) form.timeoutSeconds.trim().toLong() else 600L val payload = LinkedHashMap().apply { put("agentId", JsonPrimitive(form.agentID)) @@ -2905,6 +3125,9 @@ class AppModel( timeoutSeconds = timeoutSeconds, notify = form.notify, eventSourceId = sourceID.ifEmpty { null }, + nextRunLabel = "Saving…", + description = "Saving…", + timing = "Saving…", // Without a next run a one-off reads as finished and leaves the list before it is saved. nextRunAt = runAt.ifEmpty { old?.nextRunAt.takeIf { cron.isNotEmpty() } }, ) @@ -2960,7 +3183,7 @@ class AppModel( val enabled = !old.enabled optimisticMutation( key = "schedule:$id", - update = { replace(old.copy(enabled = enabled)) }, + update = { replace(old.copy(enabled = enabled, timing = if (enabled) old.description else "Paused · ${old.description}", nextRunLabel = if (enabled) "Saving…" else "—")) }, rollback = { replace(old) }, work = { api -> val saved = api.updateSchedule(id, patch = mapOf("enabled" to JsonPrimitive(enabled))) @@ -3802,9 +4025,12 @@ class AppModel( } val candidate = APIClient(rawURL, session, transport) candidate.agents() - val replaced = client?.takeIf { it.token.isNotEmpty() && it.token != session } + val replaced = client?.takeIf { it.token.isNotEmpty() && (it.token != session || it.baseURL != candidate.baseURL) } // The server keeps one device row per installation, so this must land before the new session registers. - replaced?.let { old -> quietly { onSignOut(old) } } + replaced?.let { old -> + chatAttention.disconnect(old) + quietly { onSignOut(old) } + } credentials.write("server-token", session) credentials.write("account-email", trimmedEmail) credentials.write("server-url", rawURL) @@ -3844,6 +4070,8 @@ class AppModel( /** Drops everything that belonged to the old session, so nothing carries over to the next one. */ private fun resetConnectionState() { + chatAttention.update(null, false, null) + attentionRefresh?.cancel() cancelStream() generation += 1 pendingMutations = emptySet() @@ -3856,6 +4084,7 @@ class AppModel( resetAccountForm() recentChats.clear() attachmentBytes = emptyMap() + deletedFileKeys.clear() credentials.deletePrefixed(RECENT_CHAT_PREFIX) forgetDrafts() awaitingInitialSnapshot = false @@ -3928,6 +4157,7 @@ class AppModel( scope.launch { try { val revoked = try { + chatAttention.disconnect(api) onSignOut(api) api.signOut() true diff --git a/app/src/main/java/dev/crumble/android/model/Attachments.kt b/app/src/main/java/dev/crumble/android/model/Attachments.kt index 644f3fd..a8cbdab 100644 --- a/app/src/main/java/dev/crumble/android/model/Attachments.kt +++ b/app/src/main/java/dev/crumble/android/model/Attachments.kt @@ -13,7 +13,6 @@ import java.nio.ByteBuffer import java.nio.charset.CharacterCodingException import java.nio.charset.CodingErrorAction import java.nio.charset.StandardCharsets -import java.util.Base64 import java.util.UUID import kotlin.math.max import kotlin.math.min @@ -29,13 +28,6 @@ data class PendingAttachment( val isImage: Boolean get() = mimeType.startsWith("image/") - val outgoing: OutgoingAttachment - get() = OutgoingAttachment( - name = name, - mimeType = mimeType, - data = Base64.getEncoder().encodeToString(data), - ) - override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is PendingAttachment) return false diff --git a/app/src/main/java/dev/crumble/android/model/Automations.kt b/app/src/main/java/dev/crumble/android/model/Automations.kt index 5bc9971..51c710e 100644 --- a/app/src/main/java/dev/crumble/android/model/Automations.kt +++ b/app/src/main/java/dev/crumble/android/model/Automations.kt @@ -60,27 +60,6 @@ fun listedSchedules(schedules: List): List = schedules fun automationsOf(agentID: String, schedules: List): List = schedules.filter { it.agentId == agentID && !it.finished } -fun automationTiming(schedule: Schedule, sources: List, now: Instant = Instant.now()): String = - (if (schedule.enabled) "" else "Paused · ") + describeTiming(schedule, sources, now) - -fun describeTiming( - schedule: Schedule, - sources: List, - now: Instant = Instant.now(), - localZone: String = ZoneId.systemDefault().id, -): String { - val sourceID = schedule.eventSourceId - if (sourceID != null) { - val source = sources.firstOrNull { it.id == sourceID } - return if (source != null) "On event · ${source.name}" else "On event" - } - if (!schedule.cron.isNullOrEmpty()) return describeCron(schedule.cron, schedule.timezone ?: localZone, localZone) - val runAt = schedule.runAt?.let(::taskRunDate) ?: return "Once" - val zone = runCatching { ZoneId.of(schedule.timezone) }.getOrDefault(ZoneId.systemDefault()) - val text = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.SHORT).withZone(zone).format(runAt) - return if (runAt.isBefore(now) && schedule.nextRunAt == null) "Ran $text" else "Once, $text" -} - fun canRunScripts(capabilities: Capabilities?, agent: Agent?): Boolean = capabilities?.coding == true && agent?.tools?.contains("coding") == true diff --git a/app/src/main/java/dev/crumble/android/model/Cron.kt b/app/src/main/java/dev/crumble/android/model/Cron.kt index 64efacb..5b1668a 100644 --- a/app/src/main/java/dev/crumble/android/model/Cron.kt +++ b/app/src/main/java/dev/crumble/android/model/Cron.kt @@ -1,452 +1,3 @@ package dev.crumble.android.model -import java.time.Instant -import java.time.LocalDate -import java.time.LocalDateTime -import java.time.LocalTime -import java.time.ZoneId -import java.time.ZonedDateTime -import java.time.temporal.TemporalAdjusters - const val MAX_CRON_CHARS = 100 - -// Reaches the next Feb 29 from any date; anything later never fires. -private const val MAX_SCAN_DAYS = 3_000 - -private val CRON_ALIASES = mapOf( - "@yearly" to "0 0 0 1 1 *", - "@annually" to "0 0 0 1 1 *", - "@monthly" to "0 0 0 1 * *", - "@weekly" to "0 0 0 * * 0", - "@daily" to "0 0 0 * * *", - "@hourly" to "0 0 * * * *", - "@minutely" to "0 * * * * *", - "@secondly" to "* * * * * *", - "@weekdays" to "0 0 0 * * 1-5", - "@weekends" to "0 0 0 * * 0,6", -) - -private val CRON_NAMES = listOf("sun", "mon", "tue", "wed", "thu", "fri", "sat").withIndex().associate { (index, name) -> name to index } + - listOf("jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec").withIndex().associate { (index, name) -> name to index + 1 } -private val CRON_NAME = Regex("[a-z]{3}", RegexOption.IGNORE_CASE) -private val CRON_FIELD = Regex("[?,*\\dL#/-]+") -private val LAST_WEEKDAY = Regex("\\dL") -private val WHITESPACE = Regex("\\s+") - -private val FIELD_DEFAULTS = listOf("0", "*", "*", "*", "*", "*") - -private class CronField(val values: Set, val wildcard: Boolean, val last: Boolean = false) - -private class CronRule( - val seconds: List, - val minutes: List, - val hours: List, - val months: Set, - val daysOfMonth: CronField, - val weekdays: CronField, - val lastWeekdays: Set, - val nthWeekday: Int?, -) { - fun matches(date: LocalDate): Boolean { - if (date.monthValue !in months) return false - val lastDay = date == date.with(TemporalAdjusters.lastDayOfMonth()) - val onDay = date.dayOfMonth in daysOfMonth.values || (daysOfMonth.last && lastDay) - val weekday = date.dayOfWeek.value % 7 - val finalWeek = date.plusDays(7).month != date.month - val onWeekday = (weekday in weekdays.values && (nthWeekday == null || (date.dayOfMonth - 1) / 7 + 1 == nthWeekday)) || - (weekday in lastWeekdays && finalWeek) - return when { - daysOfMonth.wildcard && weekdays.wildcard -> true - daysOfMonth.wildcard -> onWeekday - weekdays.wildcard -> onDay - else -> onDay || onWeekday - } - } -} - -private fun cronAtom(atom: String, min: Int, max: Int, weekday: Boolean): Set? { - val slash = atom.split("/") - if (slash.size > 2) return null - val stepped = slash.size == 2 - val range = if (stepped && '-' !in slash[0]) "${slash[0]}-$max" else slash[0] - val step = if (stepped) slash[1].toIntOrNull() ?: return null else 1 - val bounds = range.split("-") - if (bounds.size == 1) { - val value = range.toIntOrNull()?.takeIf { it in min..max } ?: return null - return setOf(if (weekday) value % 7 else value) - } - val low = bounds[0].toIntOrNull() ?: return null - val high = bounds[1].toIntOrNull() ?: return null - if (low < min || high > max || low > high || step <= 0) return null - return (low..high step step).mapTo(HashSet()) { if (weekday) it % 7 else it } -} - -private fun cronField(raw: String, min: Int, max: Int, weekday: Boolean = false, lastDay: Boolean = false, lastWeekdays: MutableSet? = null): CronField? { - var unknownName = false - val named = CRON_NAME.replace(raw) { match -> - CRON_NAMES[match.value.lowercase()]?.toString() ?: match.value.also { unknownName = true } - } - if (unknownName || !CRON_FIELD.matches(named)) return null - val values = HashSet() - var last = false - for (atom in named.replace(Regex("[*?]"), "$min-$max").split(",")) { - when { - lastDay && atom == "L" -> last = true - lastWeekdays != null && LAST_WEEKDAY.matches(atom) -> lastWeekdays.add(atom[0].digitToInt() % 7) - else -> values.addAll(cronAtom(atom, min, max, weekday) ?: return null) - } - } - return CronField(values, wildcard = raw == "*" || raw == "?", last = last) -} - -private fun cronRule(cron: String): CronRule? { - val text = cron.trim() - if (text.isEmpty() || text.length > MAX_CRON_CHARS) return null - val written = (CRON_ALIASES[text] ?: text).split(WHITESPACE) - if (written.size > 6) return null - // cron-parser fills missing leading fields, so "1 2 3" is a valid, if odd, schedule. - val fields = FIELD_DEFAULTS.take(6 - written.size) + written - val (second, minute, hour, dayOfMonth, month) = fields - val dayOfWeek = fields[5] - - val nth = dayOfWeek.split("#") - if (nth.size > 2 || (nth.size == 2 && dayOfWeek.any { it in ",-/" })) return null - val nthWeekday = if (nth.size == 2) nth[1].toIntOrNull()?.takeIf { it in 1..5 } ?: return null else null - - val lastWeekdays = HashSet() - return CronRule( - seconds = cronField(second, 0, 59)?.values?.sorted() ?: return null, - minutes = cronField(minute, 0, 59)?.values?.sorted() ?: return null, - hours = cronField(hour, 0, 23)?.values?.sorted() ?: return null, - months = cronField(month, 1, 12)?.values ?: return null, - daysOfMonth = cronField(dayOfMonth, 1, 31, lastDay = true) ?: return null, - weekdays = cronField(nth[0], 0, 7, weekday = true, lastWeekdays = lastWeekdays) ?: return null, - lastWeekdays = lastWeekdays, - nthWeekday = nthWeekday, - ) -} - -private fun instantsOf(local: LocalDateTime, zone: ZoneId, everyHour: Boolean): List { - val offsets = zone.rules.getValidOffsets(local) - return if (everyHour && offsets.size == 2) offsets.map(local::toInstant) else listOf(ZonedDateTime.of(local, zone).toInstant()) -} - -/** - * The server's next run for `cron`, or null if it never fires. Like cron-parser, a skipped time runs - * just after the gap, and only every-hour rules run again in a repeated hour. - */ -fun nextOccurrence(cron: String, zone: ZoneId, from: Instant): Instant? { - val rule = cronRule(cron) ?: return null - var date = from.atZone(zone).toLocalDate() - repeat(MAX_SCAN_DAYS) { - var soonest: Instant? = null - if (rule.matches(date)) { - for (hour in rule.hours) for (minute in rule.minutes) for (second in rule.seconds) { - val readings = instantsOf(LocalDateTime.of(date, LocalTime.of(hour, minute, second)), zone, rule.hours.size == 24) - for (at in readings) if (at.isAfter(from) && (soonest == null || at.isBefore(soonest))) soonest = at - if (soonest != null && readings.size == 1) return soonest - } - } - if (soonest != null) return soonest - date = date.plusDays(1) - } - return null -} - -/** `H` fields are randomized by the server, so the app cannot predict their next run. */ -fun hasHashedField(cron: String): Boolean = Regex("(? "*" - items.all { it.toIntOrNull() != null } -> items.sortedBy { it.toInt() }.joinToString(",") - else -> items.joinToString(",") - } -} - -private fun replaceNames(field: String, names: List, first: Int): String { - var text = field - names.forEachIndexed { index, name -> text = text.replace(name, (index + first).toString(), ignoreCase = true) } - return text -} - -private fun inBounds(field: String, min: Int, max: Int): Boolean = field.split(",").all { part -> - val step = part.substringAfter('/', "") - val first = Regex("^\\d+").find(part)?.value?.toIntOrNull() - val second = Regex("^\\d+-(\\d+)").find(part)?.groupValues?.get(1)?.toIntOrNull() - !step.matches(Regex("0+")) && (first == null || first in min..max) && (second == null || second in min..max) -} - -private fun zeroStep(field: String, start: String) = if (field.startsWith("$start/")) "*/" + field.removePrefix("$start/") else field - -private fun boundedStep(field: String, through: Int): String { - if ('/' !in field || Regex("^\\*|-|,").containsMatchIn(field)) return field - val (start, step) = field.split("/", limit = 2) - return "$start-$through/$step" -} - -/** The five fields cronstrue words after normalizing, or null when the expression needs the raw text. */ -private fun wordableFields(cron: String): CronWords? { - var text = cron.trim() - if (text.startsWith("@")) text = SPECIAL_CRONS[text] ?: return null - val parts = text.split(Regex(" +")).map(::sortedList).toMutableList() - if (parts.size == 6) { - if (Regex("\\d{4}$").containsMatchIn(parts[5]) || parts[4] == "?" || parts[2] == "?" || parts[0] != "0") return null - parts.removeAt(0) - } - if (parts.size != 5) return null - - var minute = zeroStep(parts[0], "0") - var hour = zeroStep(parts[1].replaceFirst("?", "*"), "0") - var day = zeroStep(parts[2].replaceFirst("?", "*"), "1") - var month = zeroStep(parts[3], "1") - var weekday = Regex("(^\\d+)|([^#/\\s\\d]\\d+)").replace(parts[4].replaceFirst("?", "*")) { match -> - if (match.value.replaceFirst(Regex("\\D"), "") == "7") match.value.replace("7", "0") else match.value - } - weekday = replaceNames(weekday, WEEKDAY_NUMBERS, 0) - month = replaceNames(month, MONTH_NUMBERS, 1) - if (listOf(minute, hour, day, month, weekday).any { !PLAIN_FIELD.matches(it) || it.isEmpty() }) return null - if (!Regex("[*\\-,/]").containsMatchIn(hour) && Regex("[*/]").containsMatchIn(minute)) hour = "$hour-$hour" - - fun oneStep(field: String) = if (field == "*/1") "*" else field - minute = oneStep(minute) - hour = oneStep(hour) - day = oneStep(day) - month = boundedStep(oneStep(month), 12) - weekday = boundedStep(oneStep(weekday), 6) - val valid = inBounds(minute, 0, 59) && inBounds(hour, 0, 23) && inBounds(day, 1, 31) && inBounds(month, 1, 12) && inBounds(weekday, 0, 6) - return if (valid) CronWords(minute, hour, day, month, weekday) else null -} - -private class Segment( - val all: String, - val single: (String) -> String, - val increment: (String) -> String, - val range: (String) -> String, - val format: (String) -> String, -) - -/** The English cronstrue wording, or null when only the raw expression says it right. */ -fun wordedCron(cron: String): String? = wordableFields(cron)?.sentence() - -private class CronWords(val minute: String, val hour: String, val day: String, val month: String, val weekday: String) { - fun sentence(): String = (timeOfDay() + dayOfMonth() + dayOfWeek() + monthOfYear()) - .replace(", every minute", "") - .replace(", every hour", "") - .replace(", every day", "") - .replace(Regex(", ?$"), "") - .replaceFirstChar { it.uppercase() } - - private fun time(hour: String, minute: String) = "${hour.padStart(2, '0')}:${minute.padStart(2, '0')}" - - private fun timeOfDay(): String = when { - !minute.special() && !hour.special() -> "At " + time(hour, minute) - '-' in minute && ',' !in minute && '/' !in minute && !hour.special() -> { - val bounds = minute.split("-") - "Every minute between ${time(hour, bounds[0])} and ${time(hour, bounds[1])}" - } - ',' in hour && '-' !in hour && '/' !in hour && !minute.special() -> { - val hours = hour.split(",") - buildString { - append("At") - hours.forEachIndexed { index, each -> - append(" ").append(time(each, minute)) - if (index < hours.size - 2) append(",") - if (index == hours.size - 2) append(" and") - } - } - } - else -> { - val minutes = minutesText() - val hours = hoursText() - if (minutes == hours) minutes else listOf(minutes, hours).filter { it.isNotEmpty() }.joinToString(", ") - } - } - - private fun minutesText() = described( - minute, - Segment( - all = "every minute", - single = { it }, - increment = { plural(it, "every %s minute", "every %s minutes") }, - range = { "minutes %s through %s past the hour" }, - format = { value -> - when { - value == "0" && '/' !in hour -> "every hour" - value == "0" -> "on the hour" - else -> plural(value, "at %s minute past the hour", "at %s minutes past the hour") - } - }, - ), - ) - - private fun hoursText(): String { - val rangeEnds = ArrayList>() - var index = 0 - for (range in hour.substringBefore('/').split(",")) { - val parts = range.split("-") - if (parts.size == 2) rangeEnds.add(parts[1] to index + 1) - index += parts.size - } - var evaluated = 0 - return described( - hour, - Segment( - all = "every hour", - single = { value -> - val endsRange = rangeEnds.any { it.first == value && it.second == evaluated } - evaluated += 1 - time(value, if (endsRange && minute != "0") "59" else "0") - }, - increment = { plural(it, "every %s hour", "every %s hours") }, - range = { "between %s and %s" }, - format = { "at %s" }, - ), - ) - } - - private fun dayOfWeek(): String { - if (weekday == "*") return "" - return described( - weekday, - Segment( - all = ", every day", - single = { WEEKDAY_NAMES[it.toInt()] }, - increment = { if (it.toIntOrNull() == 1) "" else ", every %s days of the week" }, - range = { ", %s through %s" }, - format = { if (day != "*") ", and on %s" else ", only on %s" }, - ), - ) - } - - private fun monthOfYear() = described( - month, - Segment( - all = "", - single = { MONTH_NAMES[it.toInt() - 1] }, - increment = { if (it.toIntOrNull() == 1) "" else ", every %s months" }, - range = { ", %s through %s" }, - format = { ", only in %s" }, - ), - ) - - private fun dayOfMonth(): String { - if (day == "*" && weekday != "*") return "" - return described( - day, - Segment( - all = ", every day", - single = { it }, - increment = { if (it == "1") ", every day" else ", every %s days in a month" }, - range = { ", between day %s and %s of the month" }, - format = { ", on day %s of the month" }, - ), - ) - } - - private fun described(field: String, segment: Segment): String = when { - field.isEmpty() -> "" - field == "*" -> segment.all - ',' in field -> listed(field, segment) - '/' in field -> stepped(field, segment) - '-' in field -> ranged(field, segment.range, segment.single) - else -> fill(segment.format(field), segment.single(field)) - } - - private fun listed(field: String, segment: Segment): String { - val stepped = '/' in field - val items = field.split(",") - val text = buildString { - items.forEachIndexed { index, item -> - if (index > 0 && items.size > 2) { - append(",") - if (index < items.size - 1) append(" ") - } - if (index > 0 && (index == items.size - 1 || items.size == 2)) append(" and ") - when { - '/' in item || '-' in item -> { - val plainRange = '-' in item && '/' !in item - val inner = Segment(segment.all, segment.single, segment.increment, if (plainRange) ({ ", %s through %s" }) else segment.range, segment.format) - val part = described(item, inner) - append( - when { - plainRange -> part.replaceFirst(", ", "") - index > 0 -> part.removePrefix(", ") - else -> part - }, - ) - } - !stepped -> append(segment.single(item)) - else -> { - val part = described(item, segment) - append(if (index > 0) part.removePrefix(", ") else part) - } - } - } - } - return if (stepped) text else fill(segment.format(field), text) - } - - private fun stepped(field: String, segment: Segment): String { - val (start, step) = field.split("/", limit = 2) - var text = fill(segment.increment(step), step) - if ('-' in start) { - val range = ranged(start, segment.range, segment.single) - if (!range.startsWith(", ")) text += ", " - text += range - } else if ('*' !in start) { - text += ", starting " + fill(segment.format(start), segment.single(start)).replaceFirst(", ", "") - } - return text - } - - private fun ranged(field: String, range: (String) -> String, single: (String) -> String): String { - val bounds = field.split("-") - val first = single(bounds[0]) - val second = single(bounds[1]) - return fill(range(field), first, second) - } -} diff --git a/app/src/main/java/dev/crumble/android/model/GroupChats.kt b/app/src/main/java/dev/crumble/android/model/GroupChats.kt index dea586d..9b3a2cf 100644 --- a/app/src/main/java/dev/crumble/android/model/GroupChats.kt +++ b/app/src/main/java/dev/crumble/android/model/GroupChats.kt @@ -130,11 +130,7 @@ fun groupReactions(messages: List) = reactionsOf(messages) { message, _ /** A bot reacts to the owner's last message. */ fun botReactions(messages: List) = reactionsOf(messages) { _, lastOwner -> lastOwner } -/** A group message's sources, which the server stores with the message. */ -fun groupSourcesOf(message: Message): Sources? { - val sources = message.sources.orEmpty().mapNotNull { source -> sourceKey(source.url)?.let { it to source.title } } - return sources.toMap().takeIf { it.isNotEmpty() } -} + fun groupReplyLabel(message: Message): String = if (message.role == "user") "You" else message.origin?.name ?: "a bot" diff --git a/app/src/main/java/dev/crumble/android/model/Jobs.kt b/app/src/main/java/dev/crumble/android/model/Jobs.kt index 864ae8b..2afb4a5 100644 --- a/app/src/main/java/dev/crumble/android/model/Jobs.kt +++ b/app/src/main/java/dev/crumble/android/model/Jobs.kt @@ -1,6 +1,8 @@ package dev.crumble.android.model import dev.crumble.android.generated.CodingJobQuestion +import dev.crumble.android.generated.JobHistoryItem +import dev.crumble.android.generated.TranscriptBlock import java.util.Locale import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.json.Json @@ -40,6 +42,7 @@ data class JobSummary( data class JobPanel( val job: JobRef, val messages: List = emptyList(), + val items: List = emptyList(), val hasMore: Boolean = false, val oldestEntryID: String? = null, val loaded: Boolean = false, @@ -49,17 +52,18 @@ data class JobPanel( val downloadFailed: Boolean = false, ) -sealed class JobItem { - abstract val id: String - - data class Task(override val id: String, val text: String) : JobItem() - data class Reply(override val id: String, val text: String) : JobItem() - data class Step( - override val id: String, - val tool: String, - val subject: String?, - val result: Message? = null, - ) : JobItem() +val JobHistoryItem.id: String + get() = when (this) { + is JobHistoryItem.Variant1 -> value.id + is JobHistoryItem.Variant2 -> value.id + is JobHistoryItem.Variant3 -> value.id + } + +data class JobHistoryPage(val messages: List, val items: List, val hasMore: Boolean, val oldestEntryId: String?) + +fun mergeJobItems(existing: List, newest: List): List { + val first = newest.firstOrNull()?.id ?: return existing + return existing.takeWhile { it.id != first } + newest } fun jobWorking(status: String?): Boolean = status == "working" || status == "running" @@ -89,54 +93,6 @@ fun costLine(usage: JsonElement?): String? { private fun JsonObject.string(key: String): String? = (this[key] as? JsonPrimitive)?.takeIf { it.isString }?.contentOrNull -private fun blocksOf(message: Message): List = - (message.blocks as? JsonArray).orEmpty().filterIsInstance() - -private fun stepOf(message: Message, block: JsonObject, index: Int): JobItem.Step { - val arguments = block["arguments"] as? JsonObject - return JobItem.Step( - id = block.string("id") ?: "${message.id}:$index", - tool = block.string("name").orEmpty(), - subject = arguments?.string("command") ?: arguments?.string("path"), - ) -} - -/** The job's task, replies, and tool steps; a tool result attaches to the step that called it. */ -fun jobItems(messages: List): List { - val items = mutableListOf() - val steps = mutableMapOf() - for (message in messages) { - when (message.role) { - "user" -> if (message.text.isNotBlank()) items.add(JobItem.Task(message.id, message.text)) - "assistant" -> blocksOf(message).forEachIndexed { index, block -> - val text = block.string("text").orEmpty() - if (block.string("type") == "text" && text.isNotBlank()) { - items.add(JobItem.Reply("${message.id}:$index", text)) - } - if (block.string("type") == "toolCall" && !block.string("name").isNullOrEmpty()) { - val step = stepOf(message, block, index) - steps[step.id] = items.size - items.add(step) - } - } - "toolResult" -> steps[message.toolCallId]?.let { at -> - items[at] = (items[at] as JobItem.Step).copy(result = message) - } - } - } - return items -} - -private val STEP_VERBS = mapOf( - "bash" to "Ran", - "read" to "Read", - "write" to "Wrote", - "edit" to "Edited", - "computer_use" to "Used the bot desktop", -) - -fun jobStepVerb(tool: String): String = STEP_VERBS[tool] ?: tool.replaceFirstChar { it.uppercase() } - /** Keeps pages loaded earlier and rows the newest page has scrolled past; entries never change. */ fun mergeJobPages(existing: List, newest: List): List { val first = newest.firstOrNull()?.id ?: return existing @@ -159,14 +115,13 @@ private val PrettyJson = Json { private fun messageMarkdown(message: Message): List = when (message.role) { "user" -> listOf("## Task\n\n${message.text}") "toolResult" -> listOf((if (message.isError == true) "Failed:\n\n" else "") + fenced(message.text)) - "assistant" -> blocksOf(message).mapNotNull { block -> - val text = block.string("text").orEmpty() - val name = block.string("name").orEmpty() - when { - block.string("type") == "text" && text.isNotBlank() -> text - block.string("type") == "toolCall" && name.isNotEmpty() -> { - val arguments = PrettyJson.encodeToString(JsonElement.serializer(), block["arguments"] ?: JsonObject(emptyMap())) - "### $name\n\n${fenced(arguments, "json")}" + "assistant" -> message.blocks.orEmpty().mapNotNull { block -> + when (block) { + is TranscriptBlock.Variant1 -> block.value.text.takeIf { it.isNotBlank() } + is TranscriptBlock.Variant4 -> { + val call = block.value + val arguments = PrettyJson.encodeToString(JsonElement.serializer(), JsonObject(call.arguments)) + "### ${call.name}\n\n${fenced(arguments, "json")}" } else -> null } diff --git a/app/src/main/java/dev/crumble/android/model/Models.kt b/app/src/main/java/dev/crumble/android/model/Models.kt index a993281..26e7b9d 100644 --- a/app/src/main/java/dev/crumble/android/model/Models.kt +++ b/app/src/main/java/dev/crumble/android/model/Models.kt @@ -7,6 +7,8 @@ import java.time.format.DateTimeFormatter import java.time.temporal.ChronoUnit import java.util.Locale import java.util.UUID +import dev.crumble.android.generated.TranscriptBlock +import dev.crumble.android.generated.MessagePresentation import kotlinx.serialization.Serializable import kotlinx.serialization.Transient import kotlinx.serialization.json.Json @@ -123,10 +125,6 @@ data class BotRequestRef(val id: String = "", val name: String = "") @Serializable data class CallRequestRef(val id: String = "", val callee: String = "") -/** A page a group message's bot searched or read, stored with the message. */ -@Serializable -data class MessageSource(val url: String = "", val title: String = "") - /** Client-side delivery state for an optimistic owner message. */ @Serializable enum class MessageDeliveryState { @@ -141,7 +139,7 @@ data class Message( val entryId: String? = null, val role: String = "", val content: JsonElement? = null, - val blocks: JsonElement? = null, + val blocks: List? = null, val kind: String? = null, val replyTo: String? = null, val replyPreview: String? = null, @@ -164,7 +162,8 @@ data class Message( val toolCallId: String? = null, val isError: Boolean? = null, val toolDetails: JsonElement? = null, - val sources: List? = null, + val presentation: MessagePresentation? = null, + val replyReferences: List = emptyList(), ) { val text: String get() = contentText(content) @@ -177,17 +176,18 @@ data class AttachmentInfo( val mimeType: String = "", val size: Int = 0, val kind: String = "", + val id: String = "", + val deleted: Boolean = false, ) { val isImage: Boolean - get() = kind == "image" + get() = !deleted && (mimeType.startsWith("image/") || kind == "image") } -typealias OutgoingAttachment = dev.crumble.android.generated.SendMessageRequestAttachmentsItem - @Serializable data class ChatSnapshot( val messages: List? = null, val status: String? = null, + val working: String? = null, val partial: String? = null, val error: String? = null, val agentId: String? = null, @@ -195,7 +195,7 @@ data class ChatSnapshot( val oldestEntryId: String? = null, ) { val isRunning: Boolean - get() = status == "running" + get() = working != null && working != "idle" && working != "failed" } @Serializable @@ -249,6 +249,9 @@ data class Schedule( val notify: Boolean = true, val eventSourceId: String? = null, val nextRunAt: String? = null, + val nextRunLabel: String = "", + val description: String = "", + val timing: String = "", ) @Serializable @@ -438,17 +441,7 @@ sealed class ChatRow { "toolResult" -> message.botRequest != null || message.callRequest != null || message.credentialRequest != null || message.loginRequest != null || jobOf(message) != null || displayOf(message) != null || isDesktopScreenshot(message) "assistant" -> { - val blocks = message.blocks - if (blocks is JsonArray) { - blocks.any { block -> - val obj = block as? JsonObject ?: return@any false - val type = (obj["type"] as? JsonPrimitive)?.takeIf { it.isString }?.contentOrNull - val text = (obj["text"] as? JsonPrimitive)?.takeIf { it.isString }?.contentOrNull ?: "" - type == "text" && text.trim().isNotEmpty() - } - } else { - contentText(blocks).isNotEmpty() - } + message.blocks.orEmpty().any { it is TranscriptBlock.Variant1 && it.value.text.isNotBlank() } } else -> false } @@ -494,14 +487,9 @@ fun taskRunDate(value: String): Instant? { fun validateTask( name: String, prompt: String, - cron: String, - runAt: String, - timezone: String = ZoneId.systemDefault().id, kind: String = "prompt", command: String = "", timeoutSeconds: String = "600", - onEvent: Boolean = false, - eventSourceID: String = "", ): String? { if (kind == "script") { if (name.trim().isEmpty() || command.isBlank()) { @@ -513,24 +501,6 @@ fun validateTask( } else if (name.trim().isEmpty() || prompt.trim().isEmpty()) { return "Task name and prompt are required." } - if (onEvent) { - return if (eventSourceID.isEmpty()) "Choose an event source." else null - } - if (cron.isEmpty() == runAt.isEmpty()) { - return "Choose either a recurring cron or a one-time run time." - } - val validZone = try { - ZoneId.of(timezone) - true - } catch (_: Exception) { - false - } - if (!validZone) { - return "Choose a valid time zone." - } - if (runAt.isNotEmpty() && taskRunDate(runAt) == null) { - return "Choose a valid date and time." - } return null } diff --git a/app/src/main/java/dev/crumble/android/model/Reasoning.kt b/app/src/main/java/dev/crumble/android/model/Reasoning.kt deleted file mode 100644 index 93b1a22..0000000 --- a/app/src/main/java/dev/crumble/android/model/Reasoning.kt +++ /dev/null @@ -1,28 +0,0 @@ -package dev.crumble.android.model - -data class ThinkingLevel(val value: String, val label: String) - -val THINKING_LEVELS = listOf( - ThinkingLevel("off", "Off"), - ThinkingLevel("minimal", "Minimal"), - ThinkingLevel("low", "Low"), - ThinkingLevel("medium", "Medium"), - ThinkingLevel("high", "High"), - ThinkingLevel("xhigh", "Extra high"), - ThinkingLevel("max", "Maximum"), -) - -private val ORDER = THINKING_LEVELS.map { it.value } - -/** The levels `model` takes; a model ID outside the catalog may take any. */ -fun levelsOf(model: ModelSummary?): List = model?.thinkingLevels ?: ORDER - -/** The level a turn runs at, the nearest supported one preferring higher, as Pi AI's `clampThinkingLevel`. */ -fun clampLevel(level: String, levels: List): String { - if (level in levels) return level - val index = ORDER.indexOf(level) - return ORDER.drop(index + 1).firstOrNull { it in levels } - ?: ORDER.take(maxOf(index, 0)).lastOrNull { it in levels } - ?: levels.firstOrNull() - ?: "off" -} diff --git a/app/src/main/java/dev/crumble/android/model/Recurrence.kt b/app/src/main/java/dev/crumble/android/model/Recurrence.kt index bd6d212..d262e54 100644 --- a/app/src/main/java/dev/crumble/android/model/Recurrence.kt +++ b/app/src/main/java/dev/crumble/android/model/Recurrence.kt @@ -1,14 +1,9 @@ package dev.crumble.android.model import java.time.DayOfWeek -import java.time.Instant import java.time.LocalDateTime import java.time.ZoneId -import java.time.ZonedDateTime -import java.time.format.DateTimeFormatter -import java.time.format.FormatStyle import java.time.format.TextStyle -import java.time.temporal.ChronoUnit import java.util.Locale enum class TaskWhen(val label: String) { @@ -116,36 +111,3 @@ fun timezoneChoices(query: String, current: String, available: Set = Zon val regions = available.filter { it == "UTC" || ('/' in it && !it.startsWith("Etc/") && !it.startsWith("SystemV/")) } return (regions + current).distinct().filter { it.isNotEmpty() && it.lowercase().contains(needle) }.sorted() } - -sealed interface NextRun { - data object Never : NextRun - data object Passed : NextRun - data object Unknown : NextRun - data class At(val label: String, val time: String, val zone: String) : NextRun -} - -private fun validZone(id: String) = runCatching { ZoneId.of(id) }.isSuccess - -fun nextRunOf(draft: TaskDraft, now: Instant = Instant.now(), locale: Locale = Locale.getDefault()): NextRun { - val zoneID = draft.timezone.trim() - if (!validZone(zoneID)) return NextRun.Never - if (draft.repeats && hasHashedField(draft.cron)) return NextRun.Unknown - val zone = ZoneId.of(zoneID) - val run = if (draft.repeats) nextOccurrence(draft.cron, zone, now) ?: return NextRun.Never else draft.runDate - if (run.isBefore(now)) return NextRun.Passed - return NextRun.At(if (draft.repeats) "Next run" else "Runs", humanRun(run, zone, now, locale), zoneID) -} - -/** "today at 09:00", "tomorrow at 09:00", a weekday this week, or a short date further out. */ -fun humanRun(run: Instant, zone: ZoneId, now: Instant, locale: Locale = Locale.getDefault()): String { - val date: ZonedDateTime = run.atZone(zone) - val days = ChronoUnit.DAYS.between(now.atZone(zone).toLocalDate(), date.toLocalDate()) - val time = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).withLocale(locale).format(date) - val day = when (days) { - 0L -> "today" - 1L -> "tomorrow" - in 2L..6L -> date.format(DateTimeFormatter.ofPattern("EEEE", locale)) - else -> date.format(DateTimeFormatter.ofPattern("EEE, MMM d", locale)) - } - return "$day at $time" -} diff --git a/app/src/main/java/dev/crumble/android/model/ReplyAttention.kt b/app/src/main/java/dev/crumble/android/model/ReplyAttention.kt new file mode 100644 index 0000000..60101db --- /dev/null +++ b/app/src/main/java/dev/crumble/android/model/ReplyAttention.kt @@ -0,0 +1,51 @@ +package dev.crumble.android.model + +import dev.crumble.android.generated.TranscriptMessageReplyReferencesItemSurface +import dev.crumble.android.push.ChatAttentionChat + +sealed interface DisplayedReplySurface { + data object Text : DisplayedReplySurface + data class ToolCard(val toolCallId: String) : DisplayedReplySurface + data class HeldAction(val actionId: String) : DisplayedReplySurface +} + +fun Route?.attentionChat(): ChatAttentionChat? = when (this) { + is Route.AgentChat -> ChatAttentionChat("bot", id) + is Route.GroupChat -> ChatAttentionChat("group", id) + else -> null +} + +fun Message.attentionEventIDs(surface: DisplayedReplySurface): List = replyReferences.filter { reference -> + when (val expected = reference.surface) { + is TranscriptMessageReplyReferencesItemSurface.Variant1 -> surface == DisplayedReplySurface.Text + is TranscriptMessageReplyReferencesItemSurface.Variant2 -> surface is DisplayedReplySurface.ToolCard && surface.toolCallId == expected.value.toolCallId + is TranscriptMessageReplyReferencesItemSurface.Variant3 -> surface is DisplayedReplySurface.HeldAction && surface.actionId == expected.value.actionId + } +}.map { it.eventId }.distinct() + +fun AppModel.replyCardReady(message: Message): Boolean = when { + message.heldAction != null -> heldActions.any { it.id == message.heldAction.id } + message.botRequest != null -> botRequests.any { it.id == message.botRequest.id } + message.callRequest != null -> callRequests.any { it.id == message.callRequest.id } + message.credentialRequest != null -> { + val ref = message.credentialRequest + val list = botCredentials[selectedAgentID] + secretRequestState( + list?.requests?.firstOrNull { ref.answers(it.name, it.requestedAt) }, list != null, + list?.credentials?.any { it.name == ref.name } == true, + credentialReadKey(ref) in freshSecretRequests, decisionsFailed, + ).isReady() + } + message.loginRequest != null -> { + val ref = message.loginRequest + val list = botLogins[selectedAgentID] + secretRequestState( + list?.requests?.firstOrNull { ref.answers(it.name, it.requestedAt) }, list != null, + list?.logins?.any { it.name == ref.name } == true, + loginReadKey(ref) in freshSecretRequests, decisionsFailed, + ).isReady() + } + else -> false +} + +private fun SecretRequestState<*>.isReady() = this is SecretRequestState.Waiting || this == SecretRequestState.Saved || this == SecretRequestState.Declined diff --git a/app/src/main/java/dev/crumble/android/model/Sources.kt b/app/src/main/java/dev/crumble/android/model/Sources.kt deleted file mode 100644 index 42c63ac..0000000 --- a/app/src/main/java/dev/crumble/android/model/Sources.kt +++ /dev/null @@ -1,116 +0,0 @@ -package dev.crumble.android.model - -import kotlinx.serialization.json.JsonArray -import kotlinx.serialization.json.JsonObject -import kotlinx.serialization.json.JsonPrimitive -import kotlinx.serialization.json.contentOrNull - -/** Pages a reply may cite, keyed by `sourceKey` of their URL, with their titles. */ -typealias Sources = Map - -data class SourceChip(val href: String, val title: String) - -data class SplitReply(val text: String, val chips: List) - -// Parsed by hand: java.net.URI rejects characters real page URLs carry, such as `|` in a query. -private val WEB_URL = Regex("^https?://(?:[^/?#@]*@)?([^/?#]+)([^?#]*)(\\?[^#]*)?", RegexOption.IGNORE_CASE) - -private val DEFAULT_PORT = Regex("^(https://.*:443|http://.*:80)$", RegexOption.IGNORE_CASE) - -private val WEB_TOOLS = setOf("web_search", "web_extract") - -/** Ignores the fragment, a trailing slash, and the host's case, so a cited link matches the page that was read. */ -fun sourceKey(href: String): String? { - val match = WEB_URL.find(href) ?: return null - val (authority, path, query) = match.destructured - val origin = href.substring(0, href.indexOf("://") + 3) + authority - val host = if (DEFAULT_PORT.matches(origin)) authority.substringBeforeLast(':') else authority - return host.lowercase() + path.trimEnd('/') + query.takeIf { it.length > 1 }.orEmpty() -} - -/** The host a source chip names, without its port or `www.`. */ -fun siteOf(href: String): String { - val authority = WEB_URL.find(href)?.groupValues?.get(1) ?: return href - return authority.lowercase().replace(Regex(":\\d+$"), "").removePrefix("www.") -} - -private fun pagesOf(message: Message): List { - if (message.role != "toolResult" || message.isError == true || message.toolName !in WEB_TOOLS) return emptyList() - val pages = message.toolDetails as? JsonArray ?: return emptyList() - return pages.filterIsInstance().filterNot { "error" in it } -} - -/** For each bot reply, the pages its turn searched or read; a turn starts at each message to the bot. */ -fun sourcesOf(messages: List): Map { - val replies = mutableMapOf() - var turn = mutableMapOf() - for (message in messages) { - if (message.role == "user") turn = mutableMapOf() - for (page in pagesOf(message)) { - val url = (page["url"] as? JsonPrimitive)?.contentOrNull ?: continue - val key = sourceKey(url) ?: continue - turn[key] = (page["title"] as? JsonPrimitive)?.contentOrNull.orEmpty() - } - if (message.role == "assistant" && turn.isNotEmpty()) replies[message.id] = turn.toMap() - } - return replies -} - -// A citation: a Markdown link labeled "source", whose URL may hold one pair of parentheses. -private val CITATION = Regex("\\[sources?\\]\\((https?://[^\\s()]*(?:\\([^\\s()]*\\)[^\\s()]*)*)\\)", RegexOption.IGNORE_CASE) - -// A private-use character marks where a chip was; bot text never contains it. -private const val SLOT = "" - -private val SEPARATOR = Regex("$SLOT[ \\t]*(?:,|;|&|and)[ \\t]*(?=$SLOT)") - -private val LEFTOVER = Regex("[ \\t]*$SLOT") - -private val EMPTY_PARENS = Regex("[ \\t]*\\((?:\\s*sources?:?)?\\s*\\)", RegexOption.IGNORE_CASE) - -private val FENCE = Regex("^\\s*(?:```|~~~)") - -private val CODE_SPAN = Regex("`[^`]*`") - -private fun takeSources(prose: String, sources: Sources, chips: MutableMap): String { - val marked = CITATION.replace(prose) { citation -> - val href = citation.groupValues[1] - val key = sourceKey(href) - val title = key?.let { sources[it] } - if (key == null || title == null) { - citation.value - } else { - chips.getOrPut(key) { SourceChip(href, title) } - SLOT - } - } - return EMPTY_PARENS.replace(LEFTOVER.replace(SEPARATOR.replace(marked, SLOT), ""), "") -} - -private fun takeOutsideCode(line: String, sources: Sources, chips: MutableMap): String { - fun prose(part: String) = if (part.startsWith("`")) part else takeSources(part, sources, chips) - val kept = StringBuilder() - var end = 0 - for (span in CODE_SPAN.findAll(line)) { - kept.append(prose(line.substring(end, span.range.first))).append(span.value) - end = span.range.last + 1 - } - return kept.append(prose(line.substring(end))).toString() -} - -/** Takes the reply's citations of pages its turn read out of its text, outside code, so they show once as chips after it. */ -fun splitSources(markdown: String, sources: Sources): SplitReply { - val chips = linkedMapOf() - var fenced = false - val text = markdown.split("\n").joinToString("\n") { line -> - when { - FENCE.containsMatchIn(line) -> { - fenced = !fenced - line - } - fenced -> line - else -> takeOutsideCode(line, sources, chips) - } - } - return SplitReply(text, chips.values.toList()) -} diff --git a/app/src/main/java/dev/crumble/android/network/APIClient.kt b/app/src/main/java/dev/crumble/android/network/APIClient.kt index 9a9f66e..66519fc 100644 --- a/app/src/main/java/dev/crumble/android/network/APIClient.kt +++ b/app/src/main/java/dev/crumble/android/network/APIClient.kt @@ -12,7 +12,6 @@ import dev.crumble.android.generated.DesktopViewer import dev.crumble.android.generated.GroupChat import dev.crumble.android.generated.InstallSkillsRequest import dev.crumble.android.generated.LearnedChange -import dev.crumble.android.generated.OptionalField import dev.crumble.android.generated.PendingSkillUpdate import dev.crumble.android.generated.PutDesktopControlRequest import dev.crumble.android.generated.ScriptRun @@ -33,13 +32,20 @@ import dev.crumble.android.model.JobSummary import dev.crumble.android.model.MCPServer import dev.crumble.android.model.Memory import dev.crumble.android.model.ModelSummary -import dev.crumble.android.model.OutgoingAttachment +import dev.crumble.android.model.PendingAttachment +import dev.crumble.android.generated.OptionalField +import dev.crumble.android.generated.PreviewReasoningRequest +import dev.crumble.android.generated.PreviewScheduleRequest import dev.crumble.android.model.EventSource import dev.crumble.android.model.Schedule import dev.crumble.android.model.SharedSkill import dev.crumble.android.model.nilIfEmpty import dev.crumble.android.push.PushInfo -import dev.crumble.android.push.PushPresence +import dev.crumble.android.push.ChatAttentionChat +import dev.crumble.android.generated.PutChatAttentionViewRequest +import dev.crumble.android.generated.PutChatAttentionViewRequestChat +import dev.crumble.android.generated.PostChatAttentionSeenRequest +import dev.crumble.android.generated.PostChatAttentionSeenRequestChat import dev.crumble.android.push.PushRegistration import dev.crumble.android.push.PushRegistrationResult import java.io.ByteArrayInputStream @@ -57,7 +63,6 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive import kotlinx.coroutines.withContext -import kotlinx.serialization.builtins.ListSerializer import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive @@ -203,7 +208,7 @@ class APIClient( if (token.isNotEmpty()) { headers["Authorization"] = "Bearer $token" } - if (body != null) { + if (body != null && headers.keys.none { it.equals("Content-Type", ignoreCase = true) }) { headers["Content-Type"] = "application/json" } return HttpRequestData( @@ -243,8 +248,8 @@ class APIClient( private val operations = dev.crumble.android.generated.ContractOperations(object : dev.crumble.android.generated.ContractBoundary { override val json = CrumblePatchJson override fun escape(value: String) = APIClient.escape(value) - override fun request(method: String, path: String, body: ByteArray?, timeoutMs: Int) = makeRequest(method, path, body, timeoutMs) - override suspend fun send(method: String, path: String, body: ByteArray?, timeoutMs: Int) = this@APIClient.send(method, path, body, timeoutMs) + override fun request(method: String, path: String, body: ByteArray?, timeoutMs: Int, headers: Map) = makeRequest(method, path, body, timeoutMs, headers) + override suspend fun send(method: String, path: String, body: ByteArray?, timeoutMs: Int, headers: Map) = this@APIClient.send(method, path, body, timeoutMs, headers) }) private inline fun request(fields: Map): T = @@ -318,6 +323,16 @@ class APIClient( suspend fun declineHeldAction(agentID: String, id: String, reason: String) { operations.declineAgentHeldAction(request(if (reason.isEmpty()) emptyMap() else strings("reason" to reason)), agentID, id) } + suspend fun previewReasoning(provider: String, model: String, thinkingLevel: String) = operations.previewReasoning( + PreviewReasoningRequest(provider, model, OptionalField.Present(thinkingLevel)), + ) + suspend fun previewSchedule(cron: String?, runAt: String?, eventSourceID: String?, timezone: String) = operations.previewSchedule( + PreviewScheduleRequest( + OptionalField.Present(cron), + OptionalField.Present(runAt), + OptionalField.Present(eventSourceID), timezone, + ), + ) suspend fun codingJobs(agentID: String) = operations.listCodingJobs(agentID).jobs suspend fun answerCodingJob(agentID: String, job: String, questionID: String, text: String) { operations.answerCodingJob(request(strings("questionId" to questionID, "text" to text)), agentID, job) @@ -327,7 +342,7 @@ class APIClient( JobKind.coding -> operations.listCodingJobs(agentID).jobs.map { it.domain() } JobKind.desktop -> operations.listDesktopJobs(agentID).jobs.map { it.domain() } } - suspend fun jobHistory(agentID: String, job: JobRef, before: String?, limit: Int): ChatHistoryResponse = when (job.kind) { + suspend fun jobHistory(agentID: String, job: JobRef, before: String?, limit: Int): dev.crumble.android.model.JobHistoryPage = when (job.kind) { JobKind.coding -> operations.getCodingJobHistory(agentID, job.name, limit.toLong(), before) JobKind.desktop -> operations.getDesktopJobHistory(agentID, job.name, limit.toLong(), before) }.domain() @@ -354,18 +369,23 @@ class APIClient( suspend fun chatHistory(agentID: String, before: String, limit: Int): ChatHistoryResponse = operations.getChatHistory(agentID, before = before.nilIfEmpty, limit = limit.takeIf { it > 0 }?.toLong()).domain() - private fun messageFields(content: String, requestID: String, replyTo: String, attachments: List): Map { + private fun messageFields(content: String, requestID: String, replyTo: String, files: List): Map { val fields = strings("content" to content, "requestId" to requestID).toMutableMap() replyTo.nilIfEmpty?.let { fields["replyTo"] = JsonPrimitive(it) } - if (attachments.isNotEmpty()) fields["attachments"] = CrumbleJson.encodeToJsonElement(ListSerializer(OutgoingAttachment.serializer()), attachments) + if (files.isNotEmpty()) fields["files"] = kotlinx.serialization.json.JsonArray(files.map(::JsonPrimitive)) return fields } - suspend fun sendChatMessage(agentID: String, content: String, requestID: String, replyTo: String, attachments: List = emptyList()) { - val fields = messageFields(content, requestID, replyTo, attachments) + ("timezone" to JsonPrimitive(ZoneId.systemDefault().id)) - operations.sendMessage(request(fields), agentID, timeoutMs = if (attachments.isEmpty()) 20_000 else 120_000) + suspend fun uploadFile(agentID: String, file: PendingAttachment): String = + operations.uploadFile(file.data, agentID, escape(file.name), file.mimeType, timeoutMs = 120_000).file.id + + suspend fun sendChatMessage(agentID: String, content: String, requestID: String, replyTo: String, files: List = emptyList()) { + val fields = messageFields(content, requestID, replyTo, files) + ("timezone" to JsonPrimitive(ZoneId.systemDefault().id)) + operations.sendMessage(request(fields), agentID, timeoutMs = if (files.isEmpty()) 20_000 else 120_000) } + suspend fun file(agentID: String, fileID: String): ByteArray = operations.getFile(agentID, fileID) + suspend fun attachment(agentID: String, entryID: String, index: Int): ByteArray = operations.getAttachment(agentID, entryID, index.toLong()) suspend fun abortChat(agentID: String) = operations.abortChat(agentID) @@ -384,10 +404,13 @@ class APIClient( suspend fun groupSnapshot(id: String): GroupSnapshot = operations.getGroupChatSnapshot(id).domain() suspend fun groupHistory(id: String, before: String, limit: Int): ChatHistoryResponse = operations.getGroupChatHistory(id, limit.toLong(), before).domain() - suspend fun sendGroupMessage(id: String, content: String, requestID: String, replyTo: String, attachments: List = emptyList()) { - operations.sendGroupMessage(request(messageFields(content, requestID, replyTo, attachments)), id, timeoutMs = if (attachments.isEmpty()) 20_000 else 120_000) + suspend fun uploadGroupFile(id: String, file: PendingAttachment): String = + operations.uploadGroupFile(file.data, id, escape(file.name), file.mimeType, timeoutMs = 120_000).file.id + + suspend fun sendGroupMessage(id: String, content: String, requestID: String, replyTo: String, files: List = emptyList()) { + operations.sendGroupMessage(request(messageFields(content, requestID, replyTo, files)), id, timeoutMs = if (files.isEmpty()) 20_000 else 120_000) } - suspend fun groupAttachment(id: String, entryID: String, index: Int): ByteArray = operations.getGroupAttachment(id, entryID, index.toLong()) + suspend fun groupFile(id: String, fileID: String): ByteArray = operations.getGroupFile(id, fileID) suspend fun stopGroupChat(id: String) = operations.stopGroupChat(id) suspend fun groupChatEvents(id: String, onEvent: suspend (GroupSnapshot) -> Unit): Nothing = @@ -546,8 +569,11 @@ class APIClient( suspend fun registerPushDevice(installationId: String, registration: PushRegistration): PushRegistrationResult = operations.putPushDevice(registration.wire(), pushInstallationPath(installationId)).domain() suspend fun unregisterPushDevice(installationId: String) = operations.deletePushDevice(pushInstallationPath(installationId)) - suspend fun updatePushPresence(installationId: String, presence: PushPresence) { - operations.putPushPresence(dev.crumble.android.generated.PutPushPresenceRequest(presence.active, presence.agentId), pushInstallationPath(installationId)) + suspend fun putChatAttentionView(viewID: String, chat: ChatAttentionChat?) { + operations.putChatAttentionView(PutChatAttentionViewRequest(chat?.let { PutChatAttentionViewRequestChat(it.kind, it.id) }), viewID) + } + suspend fun postChatAttentionSeen(chat: ChatAttentionChat, eventIDs: List) { + operations.postChatAttentionSeen(PostChatAttentionSeenRequest(PostChatAttentionSeenRequestChat(chat.kind, chat.id), eventIDs)) } private fun pushInstallationPath(installationId: String): String { require(installationId.isNotBlank()) { "installationId must not be blank" } diff --git a/app/src/main/java/dev/crumble/android/network/ContractAdapters.kt b/app/src/main/java/dev/crumble/android/network/ContractAdapters.kt index f3cda46..e56f7de 100644 --- a/app/src/main/java/dev/crumble/android/network/ContractAdapters.kt +++ b/app/src/main/java/dev/crumble/android/network/ContractAdapters.kt @@ -95,12 +95,22 @@ private fun secretRequestRef(tool: String, toolName: String?, isError: Boolean?, return SecretRequestRef(name, hosts, (request["requestedAt"] as? JsonPrimitive)?.contentOrNull?.nilIfEmpty) } +private fun TranscriptMessageFilesItem.domain(): dev.crumble.android.model.AttachmentInfo = when (this) { + is TranscriptMessageFilesItem.Variant1 -> dev.crumble.android.model.AttachmentInfo(value.name, value.mimeType, value.size.toInt(), id = value.id) + is TranscriptMessageFilesItem.Variant2 -> dev.crumble.android.model.AttachmentInfo(id = value.id, deleted = value.deleted) +} + +private fun SnapshotEventPayloadMessagesItemFilesItem.domain(): dev.crumble.android.model.AttachmentInfo = when (this) { + is SnapshotEventPayloadMessagesItemFilesItem.Variant1 -> dev.crumble.android.model.AttachmentInfo(value.name, value.mimeType, value.size.toInt(), id = value.id) + is SnapshotEventPayloadMessagesItemFilesItem.Variant2 -> dev.crumble.android.model.AttachmentInfo(id = value.id, deleted = value.deleted) +} + internal fun TranscriptMessage.domain() = Message( id = id, entryId = entryId, role = role, content = JsonPrimitive(content), blocks = blocks, kind = kind, replyTo = replyTo, replyPreview = replyPreview, origin = origin?.let { dev.crumble.android.model.MessageOrigin(it.kind, it.name, it.agentId, it.source, it.via) }, communication = communication?.let { dev.crumble.android.model.BotCommunication(it.executionId, it.fromAgentId, it.fromName, it.toAgentId, it.toName, it.status) }, - timestamp = timestamp?.toLong(), attachments = attachments?.map { dev.crumble.android.model.AttachmentInfo(it.name, it.mimeType, it.size.toInt(), it.kind) }, + timestamp = timestamp?.toLong(), attachments = files?.map { it.domain() }, requestId = requestId, heldAction = heldAction?.let { HeldActionRef(it.id, it.job) }, jobQuestion = jobQuestion?.let { JobQuestionRef(it.id, it.job) }, @@ -110,7 +120,7 @@ internal fun TranscriptMessage.domain() = Message( credentialRequest = secretRequestRef("request_credential", toolName, isError, toolDetails), loginRequest = secretRequestRef("request_login", toolName, isError, toolDetails), toolName = toolName, toolCallId = toolCallId, isError = isError, toolDetails = toolDetails, - sources = sources?.map { MessageSource(it.url, it.title) }, + presentation = presentation, replyReferences = replyReferences, ) internal fun SnapshotEventPayloadMessagesItem.domain() = Message( @@ -118,7 +128,7 @@ internal fun SnapshotEventPayloadMessagesItem.domain() = Message( kind = kind, replyTo = replyTo, replyPreview = replyPreview, origin = origin?.let { dev.crumble.android.model.MessageOrigin(it.kind, it.name, it.agentId, it.source, it.via) }, communication = communication?.let { dev.crumble.android.model.BotCommunication(it.executionId, it.fromAgentId, it.fromName, it.toAgentId, it.toName, it.status) }, - timestamp = timestamp?.toLong(), attachments = attachments?.map { dev.crumble.android.model.AttachmentInfo(it.name, it.mimeType, it.size.toInt(), it.kind) }, + timestamp = timestamp?.toLong(), attachments = files?.map { it.domain() }, requestId = requestId, heldAction = heldAction?.let { HeldActionRef(it.id, it.job) }, jobQuestion = jobQuestion?.let { JobQuestionRef(it.id, it.job) }, @@ -128,22 +138,26 @@ internal fun SnapshotEventPayloadMessagesItem.domain() = Message( credentialRequest = secretRequestRef("request_credential", toolName, isError, toolDetails), loginRequest = secretRequestRef("request_login", toolName, isError, toolDetails), toolName = toolName, toolCallId = toolCallId, isError = isError, toolDetails = toolDetails, - sources = sources?.map { MessageSource(it.url, it.title) }, + presentation = presentation, + replyReferences = replyReferences.map { CrumblePatchJson.decodeFromJsonElement(CrumblePatchJson.encodeToJsonElement(it)) }, ) internal fun dev.crumble.android.generated.ChatSnapshot.domain() = dev.crumble.android.model.ChatSnapshot( - messages = messages.map { it.domain() }, status = status, partial = partial, error = error, + messages = messages.map { it.domain() }, status = status, working = working, partial = partial, error = error, agentId = agentId, hasMore = hasMore, oldestEntryId = oldestEntryId, ) internal fun SnapshotEventPayload.domain() = dev.crumble.android.model.ChatSnapshot( - messages = messages.map { it.domain() }, status = status, partial = partial, error = error, + messages = messages.map { it.domain() }, status = status, working = working, partial = partial, error = error, agentId = agentId, hasMore = hasMore, oldestEntryId = oldestEntryId, ) internal fun GroupChatSnapshot.domain() = GroupSnapshot(messages.map { it.domain() }, hasMore, oldestEntryId, groupChat, activity) internal fun TranscriptPage.domain() = ChatHistoryResponse(messages.map { it.domain() }, hasMore, oldestEntryId) +internal fun dev.crumble.android.generated.JobHistoryPage.domain() = dev.crumble.android.model.JobHistoryPage( + messages.map { it.domain() }, items, hasMore, oldestEntryId, +) internal fun dev.crumble.android.generated.Memory.domain() = dev.crumble.android.model.Memory(id, content, createdAt, agentId, source, updatedAt) internal fun dev.crumble.android.generated.Skill.domain() = SharedSkill(id, name, instructions) internal fun ListedSkill.domain(): SharedSkill = when (this) { @@ -152,7 +166,7 @@ internal fun ListedSkill.domain(): SharedSkill = when (this) { } internal fun dev.crumble.android.generated.Schedule.domain() = dev.crumble.android.model.Schedule( id, agentId, name, cron, prompt, timezone, runAt, enabled, createdByAgentId, - kind, command, timeoutSeconds, notify, eventSourceId, nextRunAt, + kind, command, timeoutSeconds, notify, eventSourceId, nextRunAt, nextRunLabel, description, timing, ) internal fun dev.crumble.android.generated.Execution.domain() = dev.crumble.android.model.Execution( id, agentId, conversationId, status, prompt, error, createdAt, updatedAt, scheduleId, diff --git a/app/src/main/java/dev/crumble/android/push/ChatAttention.kt b/app/src/main/java/dev/crumble/android/push/ChatAttention.kt new file mode 100644 index 0000000..d918c32 --- /dev/null +++ b/app/src/main/java/dev/crumble/android/push/ChatAttention.kt @@ -0,0 +1,212 @@ +package dev.crumble.android.push + +import dev.crumble.android.network.APIClient +import dev.crumble.android.network.APIError +import java.lang.ref.WeakReference +import java.util.UUID +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeoutOrNull + +data class ChatAttentionChat(val kind: String, val id: String) + +class ChatAttention(private val scope: CoroutineScope) { + var viewId: String = UUID.randomUUID().toString() + private set + private var connection: Connection? = null + private var disconnectedAPI: WeakReference? = null + private var view: View? = null + private var active = false + private var route: ChatAttentionChat? = null + private var mounted: ChatAttentionChat? = null + + private val effective: ChatAttentionChat? + get() = route?.takeIf { active && it == mounted } + + fun update(api: APIClient?, active: Boolean, chat: ChatAttentionChat?) { + val signedIn = api?.takeIf { it.token.isNotBlank() && it !== disconnectedAPI?.get() } + if (connection?.api !== signedIn) { + retire() + connection?.stop() + viewId = UUID.randomUUID().toString() + mounted = null + if (signedIn != null) disconnectedAPI = null + connection = signedIn?.let(::Connection) + view = connection?.let { View(it, viewId) } + } + this.active = active + route = chat + refresh() + } + + fun setDisplayedChat(chat: ChatAttentionChat?) { + mounted = chat + refresh() + } + + fun newView() { + retire() + viewId = UUID.randomUUID().toString() + mounted = null + view = connection?.let { View(it, viewId) } + refresh() + } + + fun displayed(api: APIClient, viewId: String, chat: ChatAttentionChat, eventIDs: List) { + val current = connection ?: return + if (current.api !== api || this.viewId != viewId || effective != chat || current.unauthorized) return + val known = current.known.getOrPut(chat) { mutableSetOf() } + val earned = eventIDs.filter { it.isNotBlank() && known.add(it) } + if (earned.isEmpty()) return + current.pending.getOrPut(chat) { linkedSetOf() }.addAll(earned) + current.wake.trySend(Unit) + } + + suspend fun disconnect(api: APIClient) { + val oldConnection = connection?.takeIf { it.api === api } ?: return + disconnectedAPI = WeakReference(api) + oldConnection.stop() + connection = null + retire() + viewId = UUID.randomUUID().toString() + mounted = null + active = false + route = null + try { + withTimeoutOrNull(2_000) { oldConnection.views.toList().forEach { it.job.join() } } + } finally { + oldConnection.views.toList().forEach { it.job.cancel() } + } + } + + private fun retire(): View? { + val old = view + view = null + old?.retired = true + old?.set(null, force = true) + if (old != null && !old.job.isCompleted) { + old.retirement = scope.launch { + delay(2_000) + old.job.cancel() + } + } + return old + } + + private fun refresh() { + view?.set(effective) + } + + private inner class View(val owner: Connection, val id: String) { + val api = owner.api + var retirement: Job? = null + val wake = Channel(Channel.CONFLATED) + var desired: ChatAttentionChat? = null + var revision = 0L + var retired = false + val job = scope.launch { + val heartbeat = launch { + while (true) { + delay(30_000) + if (!retired && desired != null) set(desired, force = true) + } + } + try { + for (signal in wake) { + var backoff = 1_000L + while (true) { + wake.tryReceive() + val version = revision + val chat = desired + try { + api.putChatAttentionView(id, chat) + if (version != revision) continue + if (retired) return@launch + break + } catch (error: CancellationException) { + throw error + } catch (error: Exception) { + if (error is APIError && error.statusCode == 401) return@launch + if (version != revision) continue + withTimeoutOrNull(backoff) { wake.receive() } + backoff = (backoff * 2).coerceAtMost(30_000) + } + } + } + } finally { + heartbeat.cancel() + wake.close() + } + } + + init { + owner.views.add(this) + job.invokeOnCompletion { + retirement?.cancel() + owner.views.remove(this) + } + } + + fun set(chat: ChatAttentionChat?, force: Boolean = false) { + if (!force && desired == chat) return + desired = chat + revision++ + wake.trySend(Unit) + } + } + + private inner class Connection(val api: APIClient) { + val views = mutableSetOf() + val known = mutableMapOf>() + val pending = linkedMapOf>() + val wake = Channel(Channel.CONFLATED) + var unauthorized = false + val job: Job = scope.launch { + for (signal in wake) { + delay(100) + while (pending.isNotEmpty() && !unauthorized) { + val chat = pending.keys.first() + val ids = pending.getValue(chat).take(100) + pending.getValue(chat).removeAll(ids.toSet()) + if (pending.getValue(chat).isEmpty()) pending.remove(chat) + submit(chat, ids) + } + } + } + + suspend fun submit(chat: ChatAttentionChat, ids: List) { + var backoff = 1_000L + while (!unauthorized) { + try { + api.postChatAttentionSeen(chat, ids) + return + } catch (error: CancellationException) { + throw error + } catch (error: Exception) { + if (error is APIError) { + when (error.statusCode) { + 401 -> { unauthorized = true; return } + 400, 404 -> { + if (ids.size > 1) ids.forEach { submit(chat, listOf(it)) } + return + } + } + } + delay(backoff) + backoff = (backoff * 2).coerceAtMost(30_000) + } + } + } + + fun stop() { + job.cancel() + wake.close() + pending.clear() + known.clear() + } + } +} diff --git a/app/src/main/java/dev/crumble/android/push/PushContract.kt b/app/src/main/java/dev/crumble/android/push/PushContract.kt index 83104a8..8c16d42 100644 --- a/app/src/main/java/dev/crumble/android/push/PushContract.kt +++ b/app/src/main/java/dev/crumble/android/push/PushContract.kt @@ -30,12 +30,6 @@ data class PushRegistrationResult( val remoteDelivery: Boolean = false, ) -/** Presence used to suppress a notification for the chat currently on screen. */ -data class PushPresence( - val active: Boolean, - val agentId: String? = null, -) - /** The common reply payload sent by FCM data messages and APNs adapters. */ @Serializable data class PushReply( diff --git a/app/src/main/java/dev/crumble/android/push/PushRuntime.kt b/app/src/main/java/dev/crumble/android/push/PushRuntime.kt index f4e83ac..822dd56 100644 --- a/app/src/main/java/dev/crumble/android/push/PushRuntime.kt +++ b/app/src/main/java/dev/crumble/android/push/PushRuntime.kt @@ -24,12 +24,7 @@ import java.io.File import java.util.UUID import java.util.concurrent.TimeUnit import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.launch -import kotlinx.coroutines.sync.Mutex -import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext /** Process-wide receiver state; registration and duplicate tracking survive process death. */ @@ -42,8 +37,6 @@ class PushRuntime private constructor(private val context: Context) : ReplyNotif sound = { settings.sound }, ) private val delivery = PushDelivery(store) - private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) - private val presenceMutex = Mutex() @Volatile private var visible = NotificationContext(false, null) // This ID must not be restored onto a second device from Android Auto Backup. @@ -107,27 +100,8 @@ class PushRuntime private constructor(private val context: Context) : ReplyNotif ) } - fun updatePresence(active: Boolean, route: Route?) { + fun updateVisibility(active: Boolean, route: Route?) { visible = NotificationContext(active, route) - refreshPresence() - } - - fun refreshPresence() { - scope.launch { sendPresence() } - } - - suspend fun sendPresence() = presenceMutex.withLock { - val connection = store.read().current ?: return@withLock - if (connection.serverId == null || !connection.enabled) return@withLock - val state = visible - val agentId = (state.route as? Route.AgentChat)?.id - // Read the latest presence after acquiring the lock so a queued old resume cannot - // overwrite a more recent pause. The server expires this lease after 120 seconds. - runCatching { - APIClient(connection.url, connection.bearer).updatePushPresence( - installationId, PushPresence(state.appActive, if (state.appActive) agentId else null), - ) - } } override fun handle(event: ActivityEvent, context: NotificationContext) { diff --git a/app/src/main/java/dev/crumble/android/push/PushSyncWorker.kt b/app/src/main/java/dev/crumble/android/push/PushSyncWorker.kt index 337a3d7..7800025 100644 --- a/app/src/main/java/dev/crumble/android/push/PushSyncWorker.kt +++ b/app/src/main/java/dev/crumble/android/push/PushSyncWorker.kt @@ -20,7 +20,6 @@ class PushSyncWorker(context: Context, params: WorkerParameters) : CoroutineWork installationId = runtime.installationId, firebaseConfigured = FirebaseApp.getApps(applicationContext).isNotEmpty(), fetchToken = { fetchToken() }, - onRegistered = { runtime.sendPresence() }, ).run() when (outcome) { PushSyncResult.SUCCESS -> Result.success() diff --git a/app/src/main/java/dev/crumble/android/ui/AgentEditorSheet.kt b/app/src/main/java/dev/crumble/android/ui/AgentEditorSheet.kt index 501bc9a..f832f97 100644 --- a/app/src/main/java/dev/crumble/android/ui/AgentEditorSheet.kt +++ b/app/src/main/java/dev/crumble/android/ui/AgentEditorSheet.kt @@ -48,6 +48,16 @@ import androidx.compose.material3.TextButton import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.setValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.delay import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Shape @@ -60,7 +70,6 @@ import dev.crumble.android.model.Agent import dev.crumble.android.model.AgentDraft import dev.crumble.android.model.AppModel import dev.crumble.android.model.ChoiceOption -import dev.crumble.android.model.THINKING_LEVELS import dev.crumble.android.model.WEB_SEARCH_ACCOUNT_DEFAULT import dev.crumble.android.model.WEB_SEARCH_OPTIONS import dev.crumble.android.model.botProviderOptions @@ -76,8 +85,24 @@ fun AgentEditorDialog( draft: AgentDraft, ) { val context = LocalContext.current + val client = model.client + var retry by remember(draft.id) { mutableIntStateOf(0) } + var previewFailed by remember(client, draft.id, draft.provider, draft.model, draft.thinking, retry) { mutableStateOf(false) } + LaunchedEffect(client, draft.id, draft.botRequestID, draft.provider, draft.model, draft.thinking, retry) { + if (client != null && draft.provider.isNotEmpty() && draft.model.isNotBlank()) { + delay(250) + try { + model.refreshEditorReasoning(client, draft) + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + currentCoroutineContext().ensureActive() + previewFailed = true + } + } + } val requestID = draft.botRequestID - val complete = draft.name.isNotBlank() && draft.provider.isNotEmpty() && draft.model.isNotBlank() + val complete = draft.name.isNotBlank() && draft.provider.isNotEmpty() && draft.model.isNotBlank() && model.editorReasoning != null Dialog( onDismissRequest = { @@ -243,10 +268,17 @@ fun AgentEditorDialog( } } } - if (model.editorLevels.size > 1) { + if (draft.provider.isNotEmpty() && draft.model.isNotBlank() && model.editorReasoning == null) { + if (previewFailed) { + TextButton(onClick = { retry++ }) { Text("Couldn't load reasoning options. Retry") } + } else { + Text("Checking reasoning…", style = MaterialTheme.typography.bodySmall) + } + } + if ((model.editorReasoning?.options?.size ?: 0) > 1) { ChoiceField( label = "Reasoning", - options = THINKING_LEVELS.filter { it.value in model.editorLevels }.map { ChoiceOption(it.value, it.label) }, + options = model.editorReasoning!!.options.map { ChoiceOption(it.value, it.label) }, value = model.editorLevel, onChoose = { model.agentDraft = draft.copy(thinking = it) }, ) diff --git a/app/src/main/java/dev/crumble/android/ui/BotDetailsDialog.kt b/app/src/main/java/dev/crumble/android/ui/BotDetailsDialog.kt index eb4fab2..fec9304 100644 --- a/app/src/main/java/dev/crumble/android/ui/BotDetailsDialog.kt +++ b/app/src/main/java/dev/crumble/android/ui/BotDetailsDialog.kt @@ -29,7 +29,6 @@ import dev.crumble.android.model.Agent import dev.crumble.android.model.AppModel import dev.crumble.android.model.Route import dev.crumble.android.model.Schedule -import dev.crumble.android.model.automationTiming import dev.crumble.android.model.automationsOf import dev.crumble.android.model.nilIfEmpty @@ -111,6 +110,6 @@ private fun AutomationRow(model: AppModel, schedule: Schedule, shape: Shape) { }, ) { RowTitle(schedule.name, maxLines = 1) - RowSubtitle(automationTiming(schedule, model.eventSources)) + RowSubtitle(schedule.timing) } } diff --git a/app/src/main/java/dev/crumble/android/ui/ChatScreen.kt b/app/src/main/java/dev/crumble/android/ui/ChatScreen.kt index a6db8bf..ca05ca3 100644 --- a/app/src/main/java/dev/crumble/android/ui/ChatScreen.kt +++ b/app/src/main/java/dev/crumble/android/ui/ChatScreen.kt @@ -105,14 +105,15 @@ import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import dev.crumble.android.model.Agent import dev.crumble.android.model.AppModel +import dev.crumble.android.model.DisplayedReplySurface +import dev.crumble.android.model.replyCardReady +import dev.crumble.android.push.ChatAttentionChat import dev.crumble.android.model.ChatRow import dev.crumble.android.model.MentionCompletion import dev.crumble.android.model.CallMarker import dev.crumble.android.model.Message import dev.crumble.android.model.MessageDeliveryState import dev.crumble.android.model.PendingAttachment -import dev.crumble.android.model.Sources -import dev.crumble.android.model.SplitReply import dev.crumble.android.model.botReactions import dev.crumble.android.model.displayOf import dev.crumble.android.model.callMarkerOf @@ -127,10 +128,8 @@ import dev.crumble.android.model.mentionableBots import dev.crumble.android.model.messageLabel import dev.crumble.android.model.nilIfEmpty import dev.crumble.android.model.noticeTitle +import dev.crumble.android.generated.MessagePresentation import dev.crumble.android.model.preview -import dev.crumble.android.model.siteOf -import dev.crumble.android.model.sourcesOf -import dev.crumble.android.model.splitSources import java.util.UUID import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers @@ -148,7 +147,6 @@ fun ChatView( val rows = remember(model.messages, model.snapshot, model.hasMore) { ChatRow.rows(messages = model.messages, snapshot = model.snapshot, hasMore = model.hasMore) } - val sources = remember(model.messages) { sourcesOf(model.messages) } val reactions = remember(model.messages) { botReactions(model.messages) } // Keep each agent's scroll position isolated. Reverse layout means the // newest row is index 0 and is naturally anchored at the bottom. @@ -175,34 +173,37 @@ fun ChatView( } } - Column(modifier = modifier.fillMaxSize()) { - Box( - modifier = Modifier - .weight(1f) - .fillMaxWidth(), - ) { - if (rows.isEmpty()) { - EmptyChatView( - model = model, - agent = agent, - modifier = Modifier.align(Alignment.Center), - ) - } else { - LazyColumn( - state = listState, - modifier = Modifier.fillMaxSize(), - reverseLayout = true, - contentPadding = PaddingValues(horizontal = 16.dp, vertical = 12.dp), - verticalArrangement = Arrangement.spacedBy(10.dp, Alignment.Bottom), - ) { - items(rows.asReversed(), key = { it.id }) { row -> - ChatRowView(model = model, agent = agent, row = row, sources = sources, reactions = reactions) + AttentionChat(model, ChatAttentionChat("bot", agent.id), ready = model.snapshot != null) { + Column(modifier = modifier.fillMaxSize()) { + Box( + modifier = Modifier + .weight(1f) + .fillMaxWidth() + .then(attentionViewport()), + ) { + if (rows.isEmpty()) { + EmptyChatView( + model = model, + agent = agent, + modifier = Modifier.align(Alignment.Center), + ) + } else { + LazyColumn( + state = listState, + modifier = Modifier.fillMaxSize(), + reverseLayout = true, + contentPadding = PaddingValues(horizontal = 16.dp, vertical = 12.dp), + verticalArrangement = Arrangement.spacedBy(10.dp, Alignment.Bottom), + ) { + items(rows.asReversed(), key = { it.id }) { row -> + ChatRowView(model = model, agent = agent, row = row, reactions = reactions) + } } } } - } - if (model.snapshot != null) { - Composer(model = model, agent = agent) + if (model.snapshot != null) { + Composer(model = model, agent = agent) + } } } } @@ -251,7 +252,6 @@ fun ChatRowView( model: AppModel, agent: Agent, row: ChatRow, - sources: Map = emptyMap(), reactions: Map> = emptyMap(), ) { when (row) { @@ -262,7 +262,6 @@ fun ChatRowView( model = model, message = row.message, botName = agent.name, - sources = sources[row.message.id], reactions = reactions[row.message.entryId].orEmpty(), ) } @@ -359,7 +358,6 @@ fun MessageView( model: AppModel, message: Message, botName: String, - sources: Sources? = null, reactions: List = emptyList(), ) { val replyable = !message.entryId.isNullOrEmpty() && (message.role == "user" || message.role == "assistant") @@ -383,7 +381,9 @@ fun MessageView( when (message.role) { "event" -> { when { - message.heldAction != null -> HeldActionCard(model, message.heldAction, message.text) + message.heldAction != null -> ReplyAttention(model, message, DisplayedReplySurface.HeldAction(message.heldAction.id), model.replyCardReady(message)) { + HeldActionCard(model, message.heldAction, message.text) + } message.jobQuestion != null -> JobQuestionCard(model, message.jobQuestion, message.text) message.kind == "bot-message" -> BotMessageView(message = message) else -> EventView(model = model, message = message) @@ -395,10 +395,18 @@ fun MessageView( when { display != null -> DisplayCardView(display) isDesktopScreenshot(message) -> DesktopScreenshotCard(model, message) - message.botRequest != null -> BotRequestCard(model, message.botRequest) - message.callRequest != null -> CallRequestCard(model, message.callRequest) - message.credentialRequest != null -> CredentialRequestCard(model, message.credentialRequest) - message.loginRequest != null -> LoginRequestCard(model, message.loginRequest) + message.botRequest != null -> ReplyAttention(model, message, DisplayedReplySurface.ToolCard(message.toolCallId.orEmpty()), model.replyCardReady(message)) { + BotRequestCard(model, message.botRequest) + } + message.callRequest != null -> ReplyAttention(model, message, DisplayedReplySurface.ToolCard(message.toolCallId.orEmpty()), model.replyCardReady(message)) { + CallRequestCard(model, message.callRequest) + } + message.credentialRequest != null -> ReplyAttention(model, message, DisplayedReplySurface.ToolCard(message.toolCallId.orEmpty()), model.replyCardReady(message)) { + CredentialRequestCard(model, message.credentialRequest) + } + message.loginRequest != null -> ReplyAttention(model, message, DisplayedReplySurface.ToolCard(message.toolCallId.orEmpty()), model.replyCardReady(message)) { + LoginRequestCard(model, message.loginRequest) + } job != null -> JobCard(model, job) } } @@ -484,7 +492,10 @@ fun MessageView( onLongClick = { menuExpanded = true }, ), ) { - ReplyContent(message.text, sources) + ReplyContent( + message.text, message.presentation, + replyAttentionModifier(model, message, DisplayedReplySurface.Text, ready = message.role == "assistant" && (message.presentation?.text ?: message.text).isNotBlank()), + ) } MessageContextMenu( expanded = menuExpanded, @@ -539,22 +550,19 @@ internal fun DeliveryStatus(message: Message, onRetry: () -> Unit) { /** A bot's Markdown; citations of pages its turn read show as chips after it. */ @Composable -internal fun ReplyContent(text: String, sources: Sources?) { - val reply = remember(text, sources) { - if (sources != null) splitSources(text, sources) else SplitReply(text, emptyList()) - } +internal fun ReplyContent(text: String, presentation: MessagePresentation?, textModifier: Modifier = Modifier) { val uriHandler = LocalUriHandler.current Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { - MarkdownText(text = reply.text) - if (reply.chips.isNotEmpty()) { + MarkdownText(text = presentation?.text ?: text, modifier = textModifier) + if (!presentation?.citations.isNullOrEmpty()) { Row( modifier = Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp), ) { - for (chip in reply.chips) { + for (chip in presentation.citations) { AssistChip( onClick = { if (isWebLink(chip.href)) runCatching { uriHandler.openUri(chip.href) } }, - label = { Text(siteOf(chip.href), maxLines = 1) }, + label = { Text(chip.site, maxLines = 1) }, modifier = Modifier.semantics { contentDescription = chip.title.ifEmpty { chip.href } }, ) } @@ -1218,7 +1226,7 @@ fun SentAttachments( val bitmap = remember(bytes) { bytes?.let { BitmapFactory.decodeByteArray(it, 0, it.size)?.asImageBitmap() } } - LaunchedEffect(message.entryId, index) { + LaunchedEffect(message.entryId, file.id, index) { val entryID = message.entryId if (!entryID.isNullOrEmpty()) { loadImage(entryID, index) @@ -1248,7 +1256,7 @@ fun SentAttachments( } } } else { - FileLabel(name = file.name) + FileLabel(name = if (file.deleted) "File deleted" else file.name) } } } diff --git a/app/src/main/java/dev/crumble/android/ui/GroupChatScreen.kt b/app/src/main/java/dev/crumble/android/ui/GroupChatScreen.kt index 56da58b..27aeb17 100644 --- a/app/src/main/java/dev/crumble/android/ui/GroupChatScreen.kt +++ b/app/src/main/java/dev/crumble/android/ui/GroupChatScreen.kt @@ -61,6 +61,8 @@ import dev.crumble.android.generated.GroupActivity import dev.crumble.android.generated.GroupChat import dev.crumble.android.model.Agent import dev.crumble.android.model.AppModel +import dev.crumble.android.model.DisplayedReplySurface +import dev.crumble.android.push.ChatAttentionChat import dev.crumble.android.model.ChatRow import dev.crumble.android.model.GROUP_NAME_LIMIT import dev.crumble.android.model.GroupConversation @@ -69,7 +71,6 @@ import dev.crumble.android.model.MAX_GROUP_MEMBERS import dev.crumble.android.model.Message import dev.crumble.android.model.groupReactions import dev.crumble.android.model.groupReplyLabel -import dev.crumble.android.model.groupSourcesOf import dev.crumble.android.model.groupStatusLine import dev.crumble.android.model.isGroupRunning import dev.crumble.android.model.isNotice @@ -114,67 +115,69 @@ fun GroupChatView( if (rows.isNotEmpty() && wasNearBottom) listState.animateScrollToItem(0) } - Column(modifier = modifier.fillMaxSize()) { - Box(modifier = Modifier.weight(1f).fillMaxWidth()) { - if (rows.none { it is ChatRow.MessageRow }) { - GroupEmpty(modifier = Modifier.align(Alignment.Center)) - } - LazyColumn( - state = listState, - modifier = Modifier.fillMaxSize(), - reverseLayout = true, - contentPadding = PaddingValues(horizontal = 16.dp, vertical = 12.dp), - verticalArrangement = Arrangement.spacedBy(10.dp, Alignment.Bottom), - ) { - groupActivityRows(conversation.activity, model.agents) - items(rows.asReversed(), key = { it.id }) { row -> - when (row) { - is ChatRow.Older -> OlderRow(conversation.loadingOlder) { model.loadEarlierGroupMessages() } - is ChatRow.Time -> TimeRow(row.label) - is ChatRow.MessageRow -> if (isNotice(row.message)) { - NoticeRow(model, row.message) - } else { - GroupMessageView( - model = model, - conversation = conversation, - message = row.message, - reactions = reactions[row.message.entryId].orEmpty(), - ) + AttentionChat(model, ChatAttentionChat("group", group.id), ready = true) { + Column(modifier = modifier.fillMaxSize()) { + Box(modifier = Modifier.weight(1f).fillMaxWidth().then(attentionViewport())) { + if (rows.none { it is ChatRow.MessageRow }) { + GroupEmpty(modifier = Modifier.align(Alignment.Center)) + } + LazyColumn( + state = listState, + modifier = Modifier.fillMaxSize(), + reverseLayout = true, + contentPadding = PaddingValues(horizontal = 16.dp, vertical = 12.dp), + verticalArrangement = Arrangement.spacedBy(10.dp, Alignment.Bottom), + ) { + groupActivityRows(conversation.activity, model.agents) + items(rows.asReversed(), key = { it.id }) { row -> + when (row) { + is ChatRow.Older -> OlderRow(conversation.loadingOlder) { model.loadEarlierGroupMessages() } + is ChatRow.Time -> TimeRow(row.label) + is ChatRow.MessageRow -> if (isNotice(row.message)) { + NoticeRow(model, row.message) + } else { + GroupMessageView( + model = model, + conversation = conversation, + message = row.message, + reactions = reactions[row.message.entryId].orEmpty(), + ) + } + else -> Unit } - else -> Unit } } } - } - conversation.sendError?.let { - Text( - text = it, - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.error, - modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp), + conversation.sendError?.let { + Text( + text = it, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp), + ) + } + val reply = composer.replyTo + ComposerBar( + draft = composer.draft, + onDraftChange = { text -> model.updateGroupComposer(group.id) { it.copy(draft = text) } }, + attachments = composer.attachments, + onAddAttachment = { model.addGroupAttachment(group.id, it) }, + onRemoveAttachment = { id -> + model.updateGroupComposer(group.id) { current -> current.copy(attachments = current.attachments.filterNot { it.id == id }) } + }, + onAttachmentError = { model.errorText = it }, + replyTitle = reply?.let { "Replying to ${groupReplyLabel(it)}" }, + replyPreview = reply?.text.orEmpty(), + onCancelReply = { model.updateGroupComposer(group.id) { it.copy(replyTo = null) } }, + mentionable = members.filter { it.enabled }, + enabled = true, + placeholder = "Message ${group.name}", + running = isGroupRunning(conversation.activity), + stopEnabled = "group-stop:${group.id}" !in model.pendingMutations, + onStop = { model.stopGroupChat() }, + onSend = { model.sendGroupMessage() }, ) } - val reply = composer.replyTo - ComposerBar( - draft = composer.draft, - onDraftChange = { text -> model.updateGroupComposer(group.id) { it.copy(draft = text) } }, - attachments = composer.attachments, - onAddAttachment = { model.addGroupAttachment(group.id, it) }, - onRemoveAttachment = { id -> - model.updateGroupComposer(group.id) { current -> current.copy(attachments = current.attachments.filterNot { it.id == id }) } - }, - onAttachmentError = { model.errorText = it }, - replyTitle = reply?.let { "Replying to ${groupReplyLabel(it)}" }, - replyPreview = reply?.text.orEmpty(), - onCancelReply = { model.updateGroupComposer(group.id) { it.copy(replyTo = null) } }, - mentionable = members.filter { it.enabled }, - enabled = true, - placeholder = "Message ${group.name}", - running = isGroupRunning(conversation.activity), - stopEnabled = "group-stop:${group.id}" !in model.pendingMutations, - onStop = { model.stopGroupChat() }, - onSend = { model.sendGroupMessage() }, - ) } } @@ -371,7 +374,10 @@ private fun GroupMessageView( color = LocalContentColor.current, ) } else { - ReplyContent(message.text, groupSourcesOf(message)) + ReplyContent( + message.text, message.presentation, + replyAttentionModifier(model, message, DisplayedReplySurface.Text, ready = message.role == "assistant" && (message.presentation?.text ?: message.text).isNotBlank()), + ) } } MessageContextMenu( diff --git a/app/src/main/java/dev/crumble/android/ui/JobScreen.kt b/app/src/main/java/dev/crumble/android/ui/JobScreen.kt index f4398ab..22b44f7 100644 --- a/app/src/main/java/dev/crumble/android/ui/JobScreen.kt +++ b/app/src/main/java/dev/crumble/android/ui/JobScreen.kt @@ -58,13 +58,13 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.DialogProperties import dev.crumble.android.model.AppModel -import dev.crumble.android.model.JobItem +import dev.crumble.android.generated.JobHistoryItem +import dev.crumble.android.generated.JobStepItem +import dev.crumble.android.model.id import dev.crumble.android.model.JobKind import dev.crumble.android.model.JobPanel import dev.crumble.android.model.JobRef import dev.crumble.android.model.JobSummary -import dev.crumble.android.model.jobItems -import dev.crumble.android.model.jobStepVerb import dev.crumble.android.model.jobWorking import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext @@ -72,10 +72,10 @@ import kotlinx.coroutines.withContext private fun JobKind.icon(): ImageVector = if (this == JobKind.coding) Icons.Default.Build else Icons.Default.DesktopWindows private fun stepIcon(tool: String): ImageVector = when (tool) { - "bash" -> Icons.Default.Terminal - "read" -> Icons.Default.Description - "write", "edit" -> Icons.Default.Edit - "computer_use" -> Icons.Default.TouchApp + "terminal" -> Icons.Default.Terminal + "file" -> Icons.Default.Description + "pencil" -> Icons.Default.Edit + "pointer" -> Icons.Default.TouchApp else -> Icons.Default.Build } @@ -229,7 +229,7 @@ private fun JobDownloadButton(model: AppModel, panel: JobPanel) { } @Composable -private fun JobStep(step: JobItem.Step, shape: Shape) { +private fun JobStep(step: JobStepItem, shape: Shape) { var open by remember(step.id) { mutableStateOf(false) } val result = step.result GroupedItem( @@ -241,7 +241,7 @@ private fun JobStep(step: JobItem.Step, shape: Shape) { if (result == null) { CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp, color = LocalContentColor.current) } else { - Icon(stepIcon(step.tool), contentDescription = null) + Icon(stepIcon(step.icon), contentDescription = null) } } }, @@ -263,7 +263,7 @@ private fun JobStep(step: JobItem.Step, shape: Shape) { .padding(8.dp), ) { Text( - text = result.text.trimEnd('\n').ifEmpty { "No output." }, + text = result.content.trimEnd('\n').ifEmpty { "No output." }, style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace), ) } @@ -272,20 +272,20 @@ private fun JobStep(step: JobItem.Step, shape: Shape) { null }, ) { - RowTitle(jobStepVerb(step.tool), maxLines = 1) + RowTitle(step.label, maxLines = 1) step.subject?.takeIf { it.isNotEmpty() }?.let { RowSubtitle(it, maxLines = 1, fontFamily = FontFamily.Monospace) } } } @Composable -private fun JobItemView(item: JobItem, shape: Shape) { +private fun JobItemView(item: JobHistoryItem, shape: Shape) { when (item) { - is JobItem.Task -> Column(verticalArrangement = Arrangement.spacedBy(ROW_GAP)) { + is JobHistoryItem.Variant1 -> Column(verticalArrangement = Arrangement.spacedBy(ROW_GAP)) { GroupLabel("Task") - GroupCard { Text(item.text, style = MaterialTheme.typography.bodyMedium) } + GroupCard { Text(item.value.text, style = MaterialTheme.typography.bodyMedium) } } - is JobItem.Reply -> MarkdownText(text = item.text) - is JobItem.Step -> JobStep(item, shape) + is JobHistoryItem.Variant2 -> MarkdownText(text = item.value.text) + is JobHistoryItem.Variant3 -> JobStep(item.value, shape) } } @@ -298,7 +298,7 @@ fun JobPanelDialog(model: AppModel, panel: JobPanel) { val job = panel.job val current = model.jobs.firstOrNull { it.ref == job } val working = jobWorking(current?.status) - val items = remember(panel.messages) { jobItems(panel.messages) } + val items = panel.items JobDialog( onClose = { model.closeJob() }, title = { JobTitle(job, current) }, @@ -336,8 +336,8 @@ fun JobPanelDialog(model: AppModel, panel: JobPanel) { } itemsIndexed(items.asReversed(), key = { _, item -> item.id }) { reversedIndex, item -> val index = items.lastIndex - reversedIndex - val afterStep = item is JobItem.Step && items.getOrNull(index - 1) is JobItem.Step - val beforeStep = item is JobItem.Step && items.getOrNull(index + 1) is JobItem.Step + val afterStep = item is JobHistoryItem.Variant3 && items.getOrNull(index - 1) is JobHistoryItem.Variant3 + val beforeStep = item is JobHistoryItem.Variant3 && items.getOrNull(index + 1) is JobHistoryItem.Variant3 val position = if (afterStep) 1 else 0 Box(modifier = Modifier.fillMaxWidth().padding(top = if (afterStep) 0.dp else BLOCK_GAP)) { JobItemView(item, groupedShape(position, position + if (beforeStep) 2 else 1)) diff --git a/app/src/main/java/dev/crumble/android/ui/ReplyAttention.kt b/app/src/main/java/dev/crumble/android/ui/ReplyAttention.kt new file mode 100644 index 0000000..f83b2fd --- /dev/null +++ b/app/src/main/java/dev/crumble/android/ui/ReplyAttention.kt @@ -0,0 +1,89 @@ +package dev.crumble.android.ui + +import androidx.compose.foundation.layout.Box +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.layout.boundsInWindow +import androidx.compose.ui.layout.onGloballyPositioned +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.DisplayedReplySurface +import dev.crumble.android.model.Message +import dev.crumble.android.model.attentionChat +import dev.crumble.android.model.attentionEventIDs +import dev.crumble.android.network.APIClient +import dev.crumble.android.push.ChatAttentionChat + +private class AttentionContext(val api: APIClient, val viewId: String, val chat: ChatAttentionChat) { + var viewport by mutableStateOf(Rect.Zero) +} + +internal val LocalAttentionWindowID = staticCompositionLocalOf { null } +private val LocalAttention = staticCompositionLocalOf { null } + +@Composable +internal fun AttentionChat(model: AppModel, chat: ChatAttentionChat, ready: Boolean, content: @Composable () -> Unit) { + val api = model.client + val windowID = LocalAttentionWindowID.current + var context by remember(model, api, chat, ready, windowID) { mutableStateOf(null) } + DisposableEffect(model, api, chat, ready, windowID) { + val owner = windowID != null && model.attentionWindowID == windowID + if (owner) model.updateChatAttention() + val attached = if (owner && ready && api != null && api.token.isNotEmpty() && model.route.attentionChat() == chat) { + AttentionContext(api, model.chatAttention.viewId, chat).also { + model.chatAttention.setDisplayedChat(chat) + context = it + } + } else null + onDispose { + if (model.client === api && model.attentionWindowID == windowID && attached?.viewId == model.chatAttention.viewId) { + model.updateChatAttention() + if (model.route.attentionChat() == chat) model.chatAttention.setDisplayedChat(null) + } + } + } + CompositionLocalProvider(LocalAttention provides context, content = content) +} + +@Composable +internal fun attentionViewport(): Modifier { + val context = LocalAttention.current ?: return Modifier + return Modifier.onGloballyPositioned { context.viewport = it.boundsInWindow() } +} + +internal fun replySurfaceVisible(ready: Boolean, bounds: Rect, viewport: Rect): Boolean = + ready && bounds.width > 0 && bounds.height > 0 && viewport.width > 0 && viewport.height > 0 && bounds.overlaps(viewport) + +@Composable +internal fun ReplyAttention( + model: AppModel, + message: Message, + surface: DisplayedReplySurface, + ready: Boolean = true, + content: @Composable () -> Unit, +) { + Box(replyAttentionModifier(model, message, surface, ready)) { content() } +} + +@Composable +internal fun replyAttentionModifier(model: AppModel, message: Message, surface: DisplayedReplySurface, ready: Boolean = true): Modifier { + val context = LocalAttention.current ?: return Modifier + val ids = message.attentionEventIDs(surface) + if (ids.isEmpty()) return Modifier + var bounds by remember(context, message.id, surface) { mutableStateOf(Rect.Zero) } + val viewport = context.viewport + LaunchedEffect(context, ids, ready, bounds, viewport, model.appActive, model.route, model.client) { + if (model.appActive && model.client === context.api && model.route.attentionChat() == context.chat && replySurfaceVisible(ready, bounds, viewport)) { + model.chatAttention.displayed(context.api, context.viewId, context.chat, ids) + } + } + return Modifier.onGloballyPositioned { bounds = it.boundsInWindow() } +} diff --git a/app/src/main/java/dev/crumble/android/ui/TaskTiming.kt b/app/src/main/java/dev/crumble/android/ui/TaskTiming.kt index b938f3f..ef6a1c6 100644 --- a/app/src/main/java/dev/crumble/android/ui/TaskTiming.kt +++ b/app/src/main/java/dev/crumble/android/ui/TaskTiming.kt @@ -40,17 +40,14 @@ import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog import dev.crumble.android.model.MAX_CRON_CHARS -import dev.crumble.android.model.NextRun import dev.crumble.android.model.Recurrence import dev.crumble.android.model.TaskDraft import dev.crumble.android.model.TaskWhen import dev.crumble.android.model.WEEK import dev.crumble.android.model.choice import dev.crumble.android.model.choosing -import dev.crumble.android.model.describeCron import dev.crumble.android.model.inTimezone import dev.crumble.android.model.minuteChoices -import dev.crumble.android.model.nextRunOf import dev.crumble.android.model.recurrenceOf import dev.crumble.android.model.recurring import dev.crumble.android.model.runningAt @@ -85,7 +82,6 @@ internal fun TaskTimeFields(draft: TaskDraft, onChange: (TaskDraft) -> Unit) { else -> RecurrenceFields(recurrence) { onChange(draft.recurring(it)) } } TimezoneField(draft.timezone) { onChange(draft.inTimezone(it)) } - NextRunLine(draft) } @OptIn(ExperimentalMaterial3Api::class) @@ -226,7 +222,6 @@ private fun CronField(draft: TaskDraft, onChange: (TaskDraft) -> Unit) { onValueChange = { onChange(draft.copy(cron = it.take(MAX_CRON_CHARS))) }, label = { Text("Cron expression") }, placeholder = { Text("0 9 * * 1-5") }, - supportingText = { Text(describeCron(draft.cron, draft.timezone.trim())) }, textStyle = TextStyle(fontFamily = FontFamily.Monospace), singleLine = true, modifier = Modifier.fillMaxWidth(), @@ -272,15 +267,3 @@ private fun TimezoneDialog(current: String, onDismiss: () -> Unit, onPick: (Stri } } } - -@Composable -private fun NextRunLine(draft: TaskDraft) { - val muted = MaterialTheme.colorScheme.onSurfaceVariant - val error = MaterialTheme.colorScheme.error - when (val run = nextRunOf(draft)) { - NextRun.Never -> Text("This schedule never runs.", style = MaterialTheme.typography.bodySmall, color = error) - NextRun.Passed -> Text("This time has passed.", style = MaterialTheme.typography.bodySmall, color = error) - NextRun.Unknown -> Unit - is NextRun.At -> Text("${run.label} ${run.time} (${run.zone})", style = MaterialTheme.typography.bodySmall, color = muted) - } -} diff --git a/app/src/main/java/dev/crumble/android/ui/TasksScreen.kt b/app/src/main/java/dev/crumble/android/ui/TasksScreen.kt index e038378..2f99c5f 100644 --- a/app/src/main/java/dev/crumble/android/ui/TasksScreen.kt +++ b/app/src/main/java/dev/crumble/android/ui/TasksScreen.kt @@ -45,7 +45,13 @@ import androidx.compose.material3.Switch import androidx.compose.material3.Tab import androidx.compose.material3.Text import androidx.compose.material3.TextButton +import kotlinx.coroutines.ensureActive +import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.delay import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -73,7 +79,6 @@ import dev.crumble.android.model.TaskRun import dev.crumble.android.model.TaskTab import dev.crumble.android.model.activityTime import dev.crumble.android.model.canRunScripts -import dev.crumble.android.model.describeTiming import dev.crumble.android.model.finished import dev.crumble.android.model.listedSchedules import dev.crumble.android.model.scriptRunDuration @@ -105,6 +110,8 @@ internal fun TasksPanel(model: AppModel) { @Composable private fun TaskList(model: AppModel) { + val client = model.client + LaunchedEffect(model, client) { if (client != null) model.followTaskSchedules(client) } if (model.agents.isEmpty()) { EmptyWorkspacePlaceholder( icon = Icons.Default.Schedule, @@ -183,10 +190,10 @@ private fun TaskRow(model: AppModel, schedule: Schedule, agent: Agent, shape: Sh maxLines = 2, fontFamily = if (schedule.kind == "script") FontFamily.Monospace else null, ) - RowSubtitle("${schedule.status.label} · ${describeTiming(schedule, model.eventSources)}") + RowSubtitle("${schedule.status.label} · ${schedule.description}") val nextRun = schedule.nextRunAt if (schedule.status == ScheduleStatus.Active && nextRun != null) { - RowSubtitle("Next run ${activityTime(nextRun)}") + RowSubtitle("Next run ${schedule.nextRunLabel}") } val creator = schedule.createdByAgentId if (creator != null && creator != agent.id) { @@ -446,6 +453,25 @@ fun TaskFormDialog( val canScript = canRunScripts(model.capabilities, model.agents.firstOrNull { it.id == draft.agentID }) val editingScript = model.schedules.firstOrNull { it.id == draft.scheduleID }?.kind == "script" + val client = model.client + var previewRetry by remember(draft.id) { mutableIntStateOf(0) } + val previewKey = listOf(client, draft.id, previewRetry, draft.agentID, draft.onEvent, draft.eventSourceID, + draft.repeats, draft.cron, draft.runDate, draft.timezone) + var previewFailed by remember(previewKey) { mutableStateOf(false) } + LaunchedEffect(previewKey) { + if (client != null) { + delay(250) + try { + model.refreshTaskPreview(client, draft) + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + currentCoroutineContext().ensureActive() + previewFailed = true + } + } + } + AlertDialog( onDismissRequest = { model.errorText = "" @@ -548,12 +574,18 @@ fun TaskFormDialog( } else { TaskTimeFields(draft) { model.taskDraft = it } } + val preview = model.taskPreview + when { + preview != null -> Text(preview.text, style = MaterialTheme.typography.bodySmall, color = if (preview.isProblem) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant) + previewFailed -> TextButton(onClick = { previewRetry++ }) { Text("Couldn't load schedule preview. Retry") } + else -> Text("Checking schedule…", style = MaterialTheme.typography.bodySmall) + } } }, confirmButton = { Button( onClick = { model.saveTask() }, - enabled = !model.loading, + enabled = !model.loading && model.taskPreview?.isProblem == false, ) { Text("Save") } diff --git a/app/src/test/java/dev/crumble/android/AutomationsTests.kt b/app/src/test/java/dev/crumble/android/AutomationsTests.kt index cfc27be..d08453d 100644 --- a/app/src/test/java/dev/crumble/android/AutomationsTests.kt +++ b/app/src/test/java/dev/crumble/android/AutomationsTests.kt @@ -2,6 +2,7 @@ package dev.crumble.android import dev.crumble.android.generated.Capabilities import dev.crumble.android.generated.ScriptRun +import dev.crumble.android.generated.SchedulePreview import dev.crumble.android.model.Agent import dev.crumble.android.model.AppModel import dev.crumble.android.model.CrumbleJson @@ -21,7 +22,6 @@ import dev.crumble.android.model.recurrenceOf import dev.crumble.android.model.recurring import dev.crumble.android.model.runningAt import dev.crumble.android.model.canRunScripts -import dev.crumble.android.model.describeTiming import dev.crumble.android.model.finished import dev.crumble.android.model.listedSchedules import dev.crumble.android.model.scriptRunDuration @@ -38,6 +38,7 @@ import java.time.Instant import java.time.LocalDateTime import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.launch import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.runTest @@ -85,7 +86,7 @@ private fun scheduleJson( fun quoted(value: String?) = value?.let { "\"$it\"" } ?: "null" val command = if (kind == "script") "\"./backup.sh\"" else "null" val prompt = if (kind == "script") "" else "Say hi" - return """{"id":"$id","agentId":"a1","name":"Backup","kind":"$kind","prompt":"$prompt","command":$command,"timeoutSeconds":120,"notify":false,"eventSourceId":${quoted(eventSourceId)},"enabled":$enabled,"timezone":"UTC","runAt":${quoted(runAt)},"cron":${quoted(cron)},"nextRunAt":${quoted(nextRunAt)},"createdAt":"2026-11-05T10:00:00Z","createdByAgentId":null}""" + return """{"id":"$id","agentId":"a1","name":"Backup","kind":"$kind","prompt":"$prompt","command":$command,"timeoutSeconds":120,"notify":false,"eventSourceId":${quoted(eventSourceId)},"enabled":$enabled,"timezone":"UTC","runAt":${quoted(runAt)},"cron":${quoted(cron)},"nextRunAt":${quoted(nextRunAt)},"nextRunLabel":"Soon","description":"Once","timing":"Once","createdAt":"2026-11-05T10:00:00Z","createdByAgentId":null}""" } private fun schedule(json: String = scheduleJson()) = CrumbleJson.decodeFromString(Schedule.serializer(), json) @@ -108,6 +109,94 @@ class AutomationsTests { } } + @Test + fun visibleTaskListRefreshesLabelsAndStopsWhenLeaving() = runTest { + val gate = CompletableDeferred() + val transport = HeldTransport { 200 to "[${scheduleJson()}]" } + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.route = Route.Tasks + val api = model.client!! + val follow = scope.launch { model.followTaskSchedules(api) } + testScheduler.advanceTimeBy(59_999) + testScheduler.runCurrent() + assertTrue(transport.requests.isEmpty()) + testScheduler.advanceTimeBy(1) + testScheduler.runCurrent() + assertEquals(1, transport.requests.size) + assertEquals("Soon", model.schedules.single().nextRunLabel) + transport.held["GET /v1/schedules"] = gate + testScheduler.advanceTimeBy(60_000) + testScheduler.runCurrent() + model.route = null + gate.complete(Unit) + testScheduler.runCurrent() + testScheduler.advanceTimeBy(60_000) + testScheduler.runCurrent() + assertEquals(2, transport.requests.size) + follow.cancel() + } + + @Test + fun periodicTaskRefreshPreservesAnOptimisticEdit() = runTest { + val gate = CompletableDeferred() + val transport = HeldTransport { request -> + if (request.method == "GET") 200 to "[${scheduleJson()}]" else 200 to scheduleJson(enabled = false) + } + transport.held["PATCH /v1/schedules/s1"] = gate + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.route = Route.Tasks + model.schedules = listOf(schedule()) + val follow = scope.launch { model.followTaskSchedules(model.client!!) } + model.toggleSchedule("s1") + testScheduler.runCurrent() + assertFalse(model.schedules.single().enabled) + testScheduler.advanceTimeBy(60_000) + testScheduler.runCurrent() + assertFalse(model.schedules.single().enabled) + follow.cancel() + gate.complete(Unit) + testScheduler.runCurrent() + } + + @Test + fun taskSaveRequiresTheCurrentSuccessfulPreview() = runTest { + val gate = CompletableDeferred() + val transport = HeldTransport { request -> + if (request.pathWithQuery == "/v1/schedules/preview") { + 200 to """{"description":"Daily","text":"Ready","isProblem":false,"nextRunAt":null}""" + } else 500 to "" + } + transport.held["POST /v1/schedules/preview"] = gate + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + val first = TaskDraft(scheduleID = "", agentID = "a1", name = "Task", prompt = "Go", repeats = true, cron = "0 9 * * *") + model.taskDraft = first + val loading = scope.launch { model.refreshTaskPreview(model.client!!, first) } + testScheduler.runCurrent() + model.saveTask() + assertTrue(model.schedules.isEmpty()) + val newer = first.copy(cron = "0 10 * * *") + model.taskDraft = newer + gate.complete(Unit) + testScheduler.runCurrent() + loading.join() + assertNull(model.taskPreview) + model.acceptSchedulePreview(model.client!!, newer, SchedulePreview("", "Server warning", true, null)) + model.saveTask() + assertTrue(model.schedules.isEmpty()) + assertEquals("Server warning", model.errorText) + model.acceptSchedulePreview(model.client!!, newer, SchedulePreview("", "Ready", false, null)) + model.taskDraft = first + assertNull(model.taskPreview) + model.taskDraft = newer + assertNull(model.taskPreview) + model.saveTask() + assertTrue(model.schedules.isEmpty()) + assertEquals(1, transport.requests.size) + } + @Test fun scriptTaskOnAnEventAppearsAtOnceAndReconcilesWithoutDuplicates() = runTest { val transport = HeldTransport { 201 to scheduleJson() } @@ -120,6 +209,7 @@ class AutomationsTests { timeoutSeconds = "120", notify = false, onEvent = true, eventSourceID = "e1", ) + model.allowTaskSave() model.saveTask() testScheduler.runCurrent() @@ -151,6 +241,7 @@ class AutomationsTests { val model = modelWith(transport, scope) model.taskDraft = TaskDraft(scheduleID = "", agentID = "a1", name = "Once", prompt = "Hi") + model.allowTaskSave() model.saveTask() testScheduler.runCurrent() @@ -167,6 +258,7 @@ class AutomationsTests { val form = TaskDraft(scheduleID = "", agentID = "a1", name = "Backup", kind = "script", command = "./b.sh", timeoutSeconds = "90", notify = false) model.taskDraft = form + model.allowTaskSave() model.saveTask() testScheduler.advanceUntilIdle() @@ -185,6 +277,7 @@ class AutomationsTests { assertTrue(model.taskDraft!!.repeats) model.taskDraft = model.taskDraft!!.copy(onEvent = true, eventSourceID = "e1") + model.allowTaskSave() model.saveTask() testScheduler.advanceUntilIdle() @@ -278,6 +371,7 @@ class AutomationsTests { val scope = TestScope(StandardTestDispatcher(testScheduler)) val model = modelWith(transport, scope) model.taskDraft = TaskDraft(scheduleID = "", agentID = "a1", name = "Backup", prompt = "Hi") + model.allowTaskSave() model.saveTask() testScheduler.runCurrent() @@ -456,18 +550,13 @@ class AutomationsTests { @Test fun anEventTaskNamesItsSourceAndNeverCountsAsFinished() { val task = schedule() - assertEquals("On event · GitHub", describeTiming(task, listOf(SOURCE))) - assertEquals("On event", describeTiming(task, emptyList())) assertFalse(task.finished) } @Test fun aOneOffReadsRanOnlyAfterItFinished() { - val now = Instant.parse("2026-11-05T12:00:00Z") val done = schedule(scheduleJson(kind = "prompt", runAt = "2026-11-05T10:00:00Z", eventSourceId = null)) val waiting = schedule(scheduleJson(kind = "prompt", runAt = "2026-11-05T14:00:00Z", eventSourceId = null, nextRunAt = "2026-11-05T14:00:00Z")) - assertTrue(describeTiming(done, emptyList(), now).startsWith("Ran ")) - assertTrue(describeTiming(waiting, emptyList(), now).startsWith("Once, ")) assertEquals(ScheduleStatus.Completed, done.status) assertEquals(ScheduleStatus.Active, waiting.status) } @@ -487,18 +576,14 @@ class AutomationsTests { @Test fun scriptValidationMatchesTheWebsite() { - fun script(command: String = "./a.sh", timeout: String = "600", onEvent: Boolean = false, source: String = "") = validateTask( - name = "Task", prompt = "", cron = "0 9 * * *", runAt = "", kind = "script", - command = command, timeoutSeconds = timeout, onEvent = onEvent, eventSourceID = source, + fun script(command: String = "./a.sh", timeout: String = "600") = validateTask( + name = "Task", prompt = "", kind = "script", command = command, timeoutSeconds = timeout, ) assertNull(script()) assertEquals("Task name and command are required.", script(command = " ")) assertEquals("Timeout must be between 1 and 3600 seconds.", script(timeout = "0")) assertEquals("Timeout must be between 1 and 3600 seconds.", script(timeout = "3601")) assertEquals("Timeout must be between 1 and 3600 seconds.", script(timeout = "1.5")) - assertEquals("Choose an event source.", script(onEvent = true)) - assertNull(script(onEvent = true, source = "e1")) - assertNull(validateTask(name = "T", prompt = "Hi", cron = "", runAt = "", onEvent = true, eventSourceID = "e1")) } @Test @@ -510,13 +595,6 @@ class AutomationsTests { assertFalse(canRunScripts(CODING, Agent(id = "a2"))) } - @Test - fun aCronTaskShowsWordedTiming() { - val task = schedule(scheduleJson(kind = "prompt", cron = "0 9 * * 1-5", eventSourceId = null)) - assertEquals("At 09:00, Monday through Friday", describeTiming(task, emptyList(), localZone = "UTC")) - assertEquals("At 09:00, Monday through Friday (UTC)", describeTiming(task, emptyList(), localZone = "Europe/Berlin")) - } - @Test fun anExistingCronOpensInTheMatchingPickerAndAnOddOneAsCustom() = runTest { val scope = TestScope(StandardTestDispatcher(testScheduler)) @@ -543,6 +621,7 @@ class AutomationsTests { draft = draft.choosing(TaskWhen.Weekly) draft = draft.recurring(recurrenceOf(draft.cron)!!.copy(days = listOf(2, 4), hour = 7, minute = 15)) model.taskDraft = draft.inTimezone("Asia/Tokyo") + model.allowTaskSave() model.saveTask() testScheduler.runCurrent() val body = bodyOf(transport.requests.single()) @@ -559,6 +638,7 @@ class AutomationsTests { val draft = TaskDraft(scheduleID = "", agentID = "a1", name = "Once", prompt = "Go", timezone = "UTC") .runningAt(LocalDateTime.of(2026, 12, 1, 9, 0)) model.taskDraft = draft.inTimezone("Asia/Tokyo") + model.allowTaskSave() model.saveTask() testScheduler.runCurrent() assertEquals("2026-12-01T00:00:00Z", bodyOf(transport.requests.single())["runAt"]?.jsonPrimitive?.content) diff --git a/app/src/test/java/dev/crumble/android/BotParityTests.kt b/app/src/test/java/dev/crumble/android/BotParityTests.kt index 061414c..76fe681 100644 --- a/app/src/test/java/dev/crumble/android/BotParityTests.kt +++ b/app/src/test/java/dev/crumble/android/BotParityTests.kt @@ -3,6 +3,7 @@ package dev.crumble.android import dev.crumble.android.generated.BotRequest import dev.crumble.android.generated.Capabilities import dev.crumble.android.model.Agent +import dev.crumble.android.model.AgentDraft import dev.crumble.android.model.AppModel import dev.crumble.android.model.ChartInk import dev.crumble.android.model.ChartShape @@ -16,9 +17,7 @@ import dev.crumble.android.model.MessageOrigin import dev.crumble.android.model.ModelChoice import dev.crumble.android.model.ProviderStatus import dev.crumble.android.model.Schedule -import dev.crumble.android.model.THINKING_LEVELS import dev.crumble.android.model.WEB_SEARCH_OPTIONS -import dev.crumble.android.model.automationTiming import dev.crumble.android.model.automationsOf import dev.crumble.android.model.botListLine import dev.crumble.android.model.botReactions @@ -238,76 +237,47 @@ class BotParityTests { assertEquals("mixed", model.agentDraft!!.webSearchProvider) } - private fun levelTransport() = Replies { request -> - 200 to when { - "/models?provider=openai" in request.pathWithQuery -> - """[{"provider":"openai","id":"deep","name":"D","contextWindow":1,"reasoning":true,"thinkingLevels":["off","low","medium","high","max"]},""" + - """{"provider":"openai","id":"small","name":"S","contextWindow":1,"reasoning":true,"thinkingLevels":["off","low"]},""" + - """{"provider":"openai","id":"flat","name":"F","contextWindow":1,"reasoning":false,"thinkingLevels":["off"]}]""" - request.method == "POST" -> agentFixture("created") - else -> "[]" - } - } - - private fun Replies.savedLevel(): String? = - (CrumbleJson.parseToJsonElement(requests.last { it.method == "POST" }.body!!.toString(Charsets.UTF_8)) as JsonObject)["inference"] - ?.let { it as JsonObject }?.get("thinkingLevel")?.let { (it as JsonPrimitive).content } - - @Test - fun theEditorClampsReasoningToTheModelLikeTheWebsite() = runTest { - val transport = levelTransport() - val model = AppModel(client = APIClient(SERVER, "session", transport), scope = this) - model.createAgent() - model.agentDraft = model.agentDraft!!.copy(name = "Ada", provider = "openai", model = "deep") - model.changeEditorProvider("openai") - runCurrent() - model.agentDraft = model.agentDraft!!.copy(model = "deep", thinking = "max") - assertEquals(listOf("off", "low", "medium", "high", "max"), model.editorLevels) - assertEquals("max", model.editorLevel) - - model.agentDraft = model.agentDraft!!.copy(model = "small") - assertEquals("low", model.editorLevel) - - model.agentDraft = model.agentDraft!!.copy(model = "deep") - assertEquals("max", model.editorLevel) - - model.agentDraft = model.agentDraft!!.copy(model = "small") - model.saveAgentEditor() - runCurrent() - assertEquals("low", transport.savedLevel()) - } - @Test - fun aModelOutsideTheCatalogKeepsAnyLevel() = runTest { - val model = AppModel(client = APIClient(SERVER, "session", levelTransport()), scope = this) - model.createAgent() - model.changeEditorProvider("openai") + fun reasoningPreviewIgnoresAnOlderDraftAndUsesServerOptions() = runTest { + val gate = CompletableDeferred() + val transport = Replies { request -> + if (request.pathWithQuery == "/v1/reasoning/preview") { + 200 to """{"options":[{"value":"off","label":"Disabled"},{"value":"high","label":"Deep"}],"effectiveLevel":"high"}""" + } else 200 to "[]" + } + transport.held["/v1/reasoning/preview"] = gate + val api = APIClient(SERVER, "session", transport) + val model = AppModel(client = api, scope = this) + val original = AgentDraft(isNew = true, agentID = "", provider = "openai", model = "first", thinking = "low") + model.agentDraft = original + val old = launch { model.refreshEditorReasoning(api, original) } runCurrent() - model.agentDraft = model.agentDraft!!.copy(model = "typed-by-hand", thinking = "high") - - assertEquals(THINKING_LEVELS.map { it.value }, model.editorLevels) + model.agentDraft = original.copy(model = "second", thinking = "high") + gate.complete(Unit) + old.join() + assertNull(model.editorReasoning) + transport.held.clear() + model.refreshEditorReasoning(api, model.agentDraft!!) assertEquals("high", model.editorLevel) + assertEquals(listOf("Disabled", "Deep"), model.editorReasoning!!.options.map { it.label }) + assertEquals("high", model.agentDraft!!.thinking) } @Test - fun aProviderChangeClampsOnceItsModelsArrive() = runTest { - val transport = levelTransport() - val model = AppModel(client = APIClient(SERVER, "session", transport), scope = this) - val gate = CompletableDeferred() - model.createAgent() - runCurrent() - model.agentDraft = model.agentDraft!!.copy(thinking = "medium") - transport.held["/v1/models?provider=openai"] = gate - model.changeEditorProvider("openai") - runCurrent() - assertEquals("medium", model.editorLevel) - - gate.complete(Unit) - runCurrent() - model.agentDraft = model.agentDraft!!.copy(model = "flat") - - assertEquals(listOf("off"), model.editorLevels) - assertEquals("off", model.editorLevel) + fun reasoningPreviewFailurePreservesDraftForRetry() = runTest { + var failing = true + val transport = Replies { if (failing) 503 to "" else 200 to """{"options":[{"value":"off","label":"Off"}],"effectiveLevel":"off"}""" } + val api = APIClient(SERVER, "session", transport) + val model = AppModel(client = api, scope = this) + val draft = AgentDraft(isNew = true, agentID = "", provider = "openai", model = "first", thinking = "high") + model.agentDraft = draft + assertTrue(runCatching { model.refreshEditorReasoning(api, draft) }.isFailure) + assertEquals("high", model.agentDraft!!.thinking) + assertNull(model.editorReasoning) + failing = false + model.refreshEditorReasoning(api, draft) + assertEquals("off", model.editorReasoning!!.effectiveLevel) + assertEquals("high", model.agentDraft!!.thinking) } @Test @@ -574,7 +544,7 @@ class BotParityTests { model.workingBots = setOf("a") model.snapshot = ChatSnapshot(status = "idle") assertFalse(model.isWorking("a")) - model.snapshot = ChatSnapshot(status = "running") + model.snapshot = ChatSnapshot(status = "running", working = "thinking") model.workingBots = emptySet() assertTrue(model.isWorking("a")) } @@ -585,7 +555,7 @@ class BotParityTests { val model = AppModel(client = APIClient(SERVER, "session", transport), scope = backgroundScope) model.agents = listOf(a, b) model.selectAgent("a") - model.snapshot = ChatSnapshot(status = "running") + model.snapshot = ChatSnapshot(status = "running", working = "thinking") model.selectAgent("b") runCurrent() @@ -649,7 +619,6 @@ class BotParityTests { fun detailsListThisBotsTasksThatCanStillRun() { val list = listOf(schedule("mine"), schedule("other", agentId = "b"), schedule("done", cron = null), schedule("next", cron = null, nextRunAt = "2030-01-01T00:00:00Z")) assertEquals(listOf("mine", "next"), automationsOf("a", list).map { it.id }) - assertTrue(automationTiming(schedule("off", enabled = false), emptyList()).startsWith("Paused · ")) } @Test diff --git a/app/src/test/java/dev/crumble/android/CallRequestTests.kt b/app/src/test/java/dev/crumble/android/CallRequestTests.kt index b7e989c..87b7862 100644 --- a/app/src/test/java/dev/crumble/android/CallRequestTests.kt +++ b/app/src/test/java/dev/crumble/android/CallRequestTests.kt @@ -81,7 +81,7 @@ class CallRequestTests { @Test fun requestCallResultBecomesARef() = runTest { val transport = CallTransport { - 200 to """{"messages":[{"id":"t1","entryId":"t","role":"toolResult","content":"","toolName":"request_call","toolDetails":${callRequestFixture()}},{"id":"t2","entryId":"t","role":"toolResult","content":"","toolName":"request_call","isError":true}],"hasMore":false,"oldestEntryId":null}""" + 200 to """{"messages":[{"id":"t1","entryId":"t","role":"toolResult","content":"","replyReferences":[],"toolName":"request_call","toolDetails":${callRequestFixture()}},{"id":"t2","entryId":"t","role":"toolResult","content":"","replyReferences":[],"toolName":"request_call","isError":true}],"hasMore":false,"oldestEntryId":null}""" } val client = APIClient(baseURL = "http://crumble.test/", token = "", transport = transport) val messages = client.chatHistory("a1", before = "t", limit = 10).messages.orEmpty() @@ -93,7 +93,7 @@ class CallRequestTests { @Test fun calleeCarriesFromTheCallEvent() = runTest { val transport = CallTransport { - 200 to """{"messages":[{"id":"e1","entryId":"e","role":"event","content":"started","kind":"call-started","call":{"callId":"v1","direction":"outbound","callee":"Dr. Weber"}}],"hasMore":false,"oldestEntryId":null}""" + 200 to """{"messages":[{"id":"e1","entryId":"e","role":"event","content":"started","replyReferences":[],"kind":"call-started","call":{"callId":"v1","direction":"outbound","callee":"Dr. Weber"}}],"hasMore":false,"oldestEntryId":null}""" } val client = APIClient(baseURL = "http://crumble.test/", token = "", transport = transport) val event = client.chatHistory("a1", before = "e", limit = 10).messages.orEmpty().single() @@ -219,7 +219,7 @@ class CallRequestTests { val transport = CallTransport { req -> when (req.pathWithQuery) { calls -> 200 to "[${callRequestFixture(status)}]" - "$calls/c1/transcript?limit=200" -> 200 to """{"messages":[${(1..lines).joinToString(",") { """{"id":"m$it","entryId":"m$it","role":"user","content":"line $it"}""" }}],"hasMore":false,"oldestEntryId":null}""" + "$calls/c1/transcript?limit=200" -> 200 to """{"messages":[${(1..lines).joinToString(",") { """{"id":"m$it","entryId":"m$it","role":"user","content":"line $it","replyReferences":[]}""" }}],"hasMore":false,"oldestEntryId":null}""" else -> 503 to "" } } diff --git a/app/src/test/java/dev/crumble/android/ChatAttentionTests.kt b/app/src/test/java/dev/crumble/android/ChatAttentionTests.kt new file mode 100644 index 0000000..98dfd1e --- /dev/null +++ b/app/src/test/java/dev/crumble/android/ChatAttentionTests.kt @@ -0,0 +1,358 @@ +package dev.crumble.android + +import dev.crumble.android.model.CrumbleJson +import dev.crumble.android.network.APIClient +import dev.crumble.android.network.HttpRequestData +import dev.crumble.android.network.HttpResponseData +import dev.crumble.android.network.HttpStreamResponse +import dev.crumble.android.network.HttpTransport +import dev.crumble.android.push.ChatAttention +import dev.crumble.android.push.ChatAttentionChat +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.jsonPrimitive +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +@OptIn(ExperimentalCoroutinesApi::class) +class ChatAttentionTests { + private val bot = ChatAttentionChat("bot", "a1") + private val group = ChatAttentionChat("group", "g1") + + private class Recording : HttpTransport { + val requests = mutableListOf() + var respond: suspend (HttpRequestData) -> Int = { 204 } + override suspend fun execute(request: HttpRequestData): HttpResponseData { + requests.add(request) + return HttpResponseData(respond(request), ByteArray(0)) + } + override suspend fun openStream(request: HttpRequestData): HttpStreamResponse = error("unexpected stream") + fun api(token: String = "session") = APIClient("https://example.test", token, this) + val seen get() = requests.filter { it.method == "POST" } + val presence get() = requests.filter { it.method == "PUT" } + } + + private fun HttpRequestData.json() = CrumbleJson.parseToJsonElement(body!!.decodeToString()) as JsonObject + private fun HttpRequestData.ids() = (json().getValue("eventIds") as JsonArray).map { it.jsonPrimitive.content } + + @Test + fun presenceNeedsForegroundMatchingMountButNoDeviceOrPermission() = runTest { + val transport = Recording() + val api = transport.api() + val controller = ChatAttention(backgroundScope) + controller.update(api, true, bot) + runCurrent() + assertTrue(transport.requests.isEmpty()) + controller.setDisplayedChat(group) + runCurrent() + assertTrue(transport.requests.isEmpty()) + controller.setDisplayedChat(bot) + runCurrent() + assertEquals("{\"chat\":{\"kind\":\"bot\",\"id\":\"a1\"}}", transport.presence.single().body!!.decodeToString()) + controller.update(api, false, bot) + runCurrent() + assertEquals("{\"chat\":null}", transport.presence.last().body!!.decodeToString()) + controller.update(api, true, group) + controller.setDisplayedChat(group) + runCurrent() + assertEquals("group", (transport.presence.last().json().getValue("chat") as JsonObject).getValue("kind").jsonPrimitive.content) + assertTrue(transport.requests.all { it.pathWithQuery.startsWith("/v1/chat-attention/") }) + controller.update(transport.api(" "), true, bot) + controller.setDisplayedChat(bot) + runCurrent() + assertEquals("{\"chat\":null}", transport.presence.last().body!!.decodeToString()) + } + + @Test + fun heartbeatCollapsesPendingRefreshBehindSerializedClear() = runTest { + val transport = Recording() + val gate = CompletableDeferred() + transport.respond = { if (transport.requests.size == 1) gate.await(); 204 } + val api = transport.api() + val controller = ChatAttention(backgroundScope) + controller.update(api, true, bot) + controller.setDisplayedChat(bot) + runCurrent() + advanceTimeBy(60_001) + runCurrent() + assertEquals(1, transport.presence.size) + controller.update(api, false, bot) + gate.complete(Unit) + runCurrent() + assertTrue(transport.presence.drop(1).all { it.body!!.decodeToString() == "{\"chat\":null}" }) + val count = transport.presence.size + advanceTimeBy(60_001) + runCurrent() + assertEquals(count, transport.presence.size) + controller.update(api, true, bot) + runCurrent() + val resumed = transport.presence.size + advanceTimeBy(30_001) + runCurrent() + assertEquals(resumed + 1, transport.presence.size) + } + + @Test + fun rotationKeepsEarnedUnsentSeenButRejectsOldCallbacksAndAccounts() = runTest { + val transport = Recording() + val api = transport.api() + val controller = ChatAttention(backgroundScope) + controller.update(api, true, bot) + controller.setDisplayedChat(bot) + val old = controller.viewId + controller.displayed(api, old, bot, listOf("earned")) + controller.newView() + assertNotEquals(old, controller.viewId) + controller.setDisplayedChat(bot) + controller.displayed(api, old, bot, listOf("stale")) + controller.displayed(transport.api(), controller.viewId, bot, listOf("other-api")) + controller.displayed(api, controller.viewId, group, listOf("other-chat")) + advanceTimeBy(101) + runCurrent() + assertEquals(listOf("earned"), transport.seen.single().ids()) + val previous = controller.viewId + val newApi = transport.api() + controller.update(newApi, true, bot) + controller.setDisplayedChat(bot) + controller.displayed(api, previous, bot, listOf("old-account")) + controller.displayed(newApi, controller.viewId, bot, listOf("new-account")) + advanceTimeBy(101) + runCurrent() + assertEquals(listOf("new-account"), transport.seen.last().ids()) + } + + @Test + fun batchesDeduplicateAndRetryOriginalChatAfterNavigationAndBackground() = runTest { + val transport = Recording() + var attempts = 0 + transport.respond = { if (it.method == "POST" && attempts++ == 0) 503 else 204 } + val api = transport.api() + val controller = ChatAttention(backgroundScope) + controller.update(api, true, bot) + controller.setDisplayedChat(bot) + val ids = (1..205).map { "e$it" } + controller.displayed(api, controller.viewId, bot, ids + ids) + advanceTimeBy(101) + runCurrent() + assertEquals(100, transport.seen.single().ids().size) + controller.update(api, false, group) + controller.setDisplayedChat(group) + advanceTimeBy(1_001) + runCurrent() + assertEquals(listOf(100, 100, 100, 5), transport.seen.map { it.ids().size }) + assertTrue(transport.seen.all { (it.json().getValue("chat") as JsonObject).getValue("id").jsonPrimitive.content == bot.id }) + assertEquals(ids, transport.seen.drop(1).flatMap { it.ids() }) + controller.update(api, true, bot) + controller.setDisplayedChat(bot) + controller.displayed(api, controller.viewId, bot, ids) + advanceTimeBy(101) + runCurrent() + assertEquals(4, transport.seen.size) + } + + @Test + fun atomicRejectionSplitsAndDropsOnlyInvalidSingles() = runTest { + for (status in listOf(400, 404)) { + val transport = Recording() + transport.respond = { if (it.method == "POST" && "bad" in it.ids()) status else 204 } + val api = transport.api() + val controller = ChatAttention(backgroundScope) + controller.update(api, true, bot) + controller.setDisplayedChat(bot) + controller.displayed(api, controller.viewId, bot, listOf("good", "bad", "also-good")) + advanceTimeBy(101) + runCurrent() + assertEquals(listOf(listOf("good", "bad", "also-good"), listOf("good"), listOf("bad"), listOf("also-good")), transport.seen.map { it.ids() }) + advanceTimeBy(60_000) + runCurrent() + assertEquals(4, transport.seen.size) + } + } + + @Test + fun viewRotationPreservesSubmittedRetryAndReconnectCancelsIt() = runTest { + val transport = Recording() + transport.respond = { if (it.method == "POST") 503 else 204 } + val api = transport.api() + val controller = ChatAttention(backgroundScope) + controller.update(api, true, bot) + controller.setDisplayedChat(bot) + controller.displayed(api, controller.viewId, bot, listOf("earned")) + advanceTimeBy(101) + runCurrent() + controller.newView() + controller.update(api, false, group) + advanceTimeBy(1_001) + runCurrent() + assertEquals(listOf(listOf("earned"), listOf("earned")), transport.seen.map { it.ids() }) + controller.update(transport.api(), true, group) + controller.setDisplayedChat(group) + advanceTimeBy(60_000) + runCurrent() + assertEquals(2, transport.seen.size) + } + + @Test + fun failedPresenceBackoffIsSupersededByClearAndCallbacksRequireMountAndForeground() = runTest { + val transport = Recording() + transport.respond = { if (it.method == "PUT" && transport.presence.size == 1) 503 else 204 } + val api = transport.api() + val controller = ChatAttention(backgroundScope) + controller.update(api, true, bot) + controller.displayed(api, controller.viewId, bot, listOf("unmounted")) + controller.setDisplayedChat(bot) + runCurrent() + controller.update(api, false, bot) + controller.displayed(api, controller.viewId, bot, listOf("background")) + runCurrent() + assertEquals(2, transport.presence.size) + assertEquals("{\"chat\":null}", transport.presence.last().body!!.decodeToString()) + advanceTimeBy(30_001) + runCurrent() + assertTrue(transport.seen.isEmpty()) + assertEquals(2, transport.presence.size) + } + + @Test + fun unauthorizedStopsSeenRetries() = runTest { + val transport = Recording() + transport.respond = { if (it.method == "POST") 401 else 204 } + val api = transport.api() + val controller = ChatAttention(backgroundScope) + controller.update(api, true, bot) + controller.setDisplayedChat(bot) + controller.displayed(api, controller.viewId, bot, listOf("e1")) + advanceTimeBy(101) + runCurrent() + controller.displayed(api, controller.viewId, bot, listOf("e2")) + advanceTimeBy(60_000) + runCurrent() + assertEquals(1, transport.seen.size) + } + + @Test + fun retiredOfflineViewsExpireAndDisconnectStopsEveryOldView() = runTest { + val transport = Recording() + transport.respond = { 503 } + val api = transport.api() + val controller = ChatAttention(backgroundScope) + controller.update(api, true, bot) + controller.setDisplayedChat(bot) + runCurrent() + val firstView = controller.viewId + controller.newView() + controller.setDisplayedChat(bot) + runCurrent() + advanceTimeBy(2_001) + runCurrent() + val retiredCount = transport.presence.count { it.pathWithQuery.endsWith(firstView) } + advanceTimeBy(10_000) + runCurrent() + assertEquals(retiredCount, transport.presence.count { it.pathWithQuery.endsWith(firstView) }) + controller.newView() + controller.setDisplayedChat(bot) + runCurrent() + val closing = launch { controller.disconnect(api) } + runCurrent() + advanceTimeBy(2_001) + runCurrent() + assertTrue(closing.isCompleted) + val count = transport.requests.size + advanceTimeBy(120_000) + runCurrent() + assertEquals(count, transport.requests.size) + } + + @Test + fun disconnectRejectsSameApiDuringClearAndAfterNullUntilDistinctConnection() = runTest { + val transport = Recording() + val clear = CompletableDeferred() + transport.respond = { if (it.method == "PUT" && it.body!!.decodeToString() == "{\"chat\":null}") clear.await(); 204 } + val api = transport.api() + val controller = ChatAttention(backgroundScope) + controller.update(api, true, bot) + controller.setDisplayedChat(bot) + runCurrent() + val closing = launch { controller.disconnect(api) } + runCurrent() + assertFalse(closing.isCompleted) + val count = transport.requests.size + controller.newView() + controller.update(api, true, bot) + controller.setDisplayedChat(bot) + controller.displayed(api, controller.viewId, bot, listOf("during-signout")) + advanceTimeBy(101) + runCurrent() + assertEquals(count, transport.requests.size) + controller.update(null, false, null) + controller.update(api, true, bot) + controller.setDisplayedChat(bot) + controller.displayed(api, controller.viewId, bot, listOf("after-null")) + advanceTimeBy(101) + runCurrent() + assertEquals(count, transport.requests.size) + val replacement = transport.api() + controller.update(replacement, true, group) + controller.setDisplayedChat(group) + controller.displayed(replacement, controller.viewId, group, listOf("replacement")) + advanceTimeBy(101) + runCurrent() + assertEquals(listOf("replacement"), transport.seen.single().ids()) + assertEquals("group", (transport.presence.last().json().getValue("chat") as JsonObject).getValue("kind").jsonPrimitive.content) + clear.complete(Unit) + runCurrent() + assertTrue(closing.isCompleted) + val resumed = transport.presence.size + advanceTimeBy(30_001) + runCurrent() + assertEquals(resumed + 1, transport.presence.size) + } + + @Test + fun disconnectSerializesOldClearInvalidatesImmediatelyAndBoundsWait() = runTest { + val transport = Recording() + val gate = CompletableDeferred() + transport.respond = { if (it.method == "PUT" && transport.presence.size == 1) gate.await(); if (it.method == "POST") 503 else 204 } + val api = transport.api() + val controller = ChatAttention(backgroundScope) + controller.update(api, true, bot) + controller.setDisplayedChat(bot) + val old = controller.viewId + controller.displayed(api, old, bot, listOf("e1")) + advanceTimeBy(101) + runCurrent() + val closing = launch { controller.disconnect(api) } + runCurrent() + controller.displayed(api, old, bot, listOf("late")) + assertFalse(closing.isCompleted) + assertNotEquals(old, controller.viewId) + gate.complete(Unit) + runCurrent() + assertTrue(closing.isCompleted) + assertEquals("{\"chat\":null}", transport.presence.last().body!!.decodeToString()) + advanceTimeBy(60_000) + runCurrent() + assertEquals(1, transport.seen.size) + + val blocked = Recording() + blocked.respond = { CompletableDeferred().await(); 204 } + val blockedApi = blocked.api() + controller.update(blockedApi, true, bot) + controller.setDisplayedChat(bot) + runCurrent() + val timeout = launch { controller.disconnect(blockedApi) } + runCurrent() + advanceTimeBy(2_001) + runCurrent() + assertTrue(timeout.isCompleted) + } +} diff --git a/app/src/test/java/dev/crumble/android/ChatParityTests.kt b/app/src/test/java/dev/crumble/android/ChatParityTests.kt index c7478fb..add9e7e 100644 --- a/app/src/test/java/dev/crumble/android/ChatParityTests.kt +++ b/app/src/test/java/dev/crumble/android/ChatParityTests.kt @@ -8,24 +8,16 @@ import dev.crumble.android.model.ChatRow import dev.crumble.android.model.ChatSnapshot import dev.crumble.android.model.CrumbleJson import dev.crumble.android.model.Inference -import dev.crumble.android.model.JobItem +import dev.crumble.android.generated.JobHistoryItem import dev.crumble.android.model.JobKind import dev.crumble.android.model.JobRef import dev.crumble.android.model.Message import dev.crumble.android.model.ModelSummary -import dev.crumble.android.model.SourceChip -import dev.crumble.android.model.clampLevel import dev.crumble.android.model.costLine import dev.crumble.android.model.headline -import dev.crumble.android.model.jobItems import dev.crumble.android.model.jobMarkdown import dev.crumble.android.model.jobOf -import dev.crumble.android.model.levelsOf import dev.crumble.android.model.mergeJobPages -import dev.crumble.android.model.siteOf -import dev.crumble.android.model.sourceKey -import dev.crumble.android.model.sourcesOf -import dev.crumble.android.model.splitSources import dev.crumble.android.network.APIClient import dev.crumble.android.network.HttpRequestData import dev.crumble.android.network.HttpResponseData @@ -90,76 +82,14 @@ private fun jobFixture(name: String, status: String, usage: String = """{"models private fun history(ids: List, hasMore: Boolean = false, oldest: String? = null) = buildString { append("""{"messages":[""") - append(ids.joinToString(",") { """{"id":"$it","entryId":"$it","role":"user","content":"task $it"}""" }) + append(ids.joinToString(",") { """{"id":"$it","entryId":"$it","role":"user","content":"task $it","replyReferences":[]}""" }) + append("""],"items":[""") + append(ids.joinToString(",") { """{"kind":"task","id":"$it","text":"task $it"}""" }) append("""],"hasMore":$hasMore,"oldestEntryId":${oldest?.let { "\"$it\"" } ?: "null"}}""") } @OptIn(ExperimentalCoroutinesApi::class) class ChatParityTests { - private fun web(tool: String, vararg pages: String) = Message( - id = "tool", role = "toolResult", toolName = tool, - toolDetails = JsonArray(pages.map { json(it) }), - ) - - @Test - fun sourceKeyIgnoresFragmentTrailingSlashAndHostCase() { - assertEquals("example.com/a?b=1", sourceKey("https://EXAMPLE.com/a/?b=1#top")) - assertEquals("example.com", sourceKey("http://example.com/")) - assertEquals("example.com", sourceKey("https://example.com:443")) - assertEquals("example.com:8443/a", sourceKey("https://example.com:8443/a")) - assertEquals("example.com/a?q=x|y", sourceKey("https://example.com/a?q=x|y")) - assertNull(sourceKey("ftp://example.com/a")) - assertNull(sourceKey("not a url")) - } - - @Test - fun sourcesBelongToTheTurnThatReadThem() { - val first = Message(id = "r1", role = "assistant") - val second = Message(id = "r2", role = "assistant") - val page = """{"url":"https://a.com/x","title":"A"}""" - val failed = web("web_extract", """{"url":"https://c.com","title":"C"}""").copy(isError = true) - val messages = listOf( - web("web_search", page, """{"url":"https://b.com","title":"B","error":"blocked"}"""), - failed, - first, - Message(id = "u", role = "user"), - second, - ) - val sources = sourcesOf(messages) - assertEquals(mapOf("r1" to mapOf("a.com/x" to "A")), sources) - } - - @Test - fun splitSourcesMovesCitationsToChipsAndLeavesCodeAlone() { - val sources = mapOf("a.com/x" to "A", "b.com" to "B") - val reply = splitSources( - """ - Fact one ([source](https://a.com/x/), [source](https://b.com)). Again [source](https://a.com/x). - Unread [source](https://z.com) stays, `[source](https://a.com/x)` too. - ``` - [source](https://a.com/x) - ``` - """.trimIndent(), - sources, - ) - assertEquals(listOf(SourceChip("https://a.com/x/", "A"), SourceChip("https://b.com", "B")), reply.chips) - assertEquals( - """ - Fact one. Again. - Unread [source](https://z.com) stays, `[source](https://a.com/x)` too. - ``` - [source](https://a.com/x) - ``` - """.trimIndent(), - reply.text, - ) - } - - @Test - fun siteOfDropsWwwAndPort() { - assertEquals("example.com", siteOf("https://www.Example.com:8443/a")) - } - @Test fun costLineSumsModelsAndHidesZero() { assertEquals("$3.0000", costLine(json("""{"models":{"a/one":{"cost":{"total":1.5}},"b/two":{"cost":{"total":1.5}}}}"""))) @@ -176,20 +106,6 @@ class ChatParityTests { assertTrue(ChatRow.shownInChat(jobResult())) } - @Test - fun jobItemsAttachResultsToSteps() { - val assistant = Message( - id = "m2", role = "assistant", - blocks = json("""[{"type":"text","text":"On it"},{"type":"toolCall","id":"c1","name":"bash","arguments":{"command":"ls"}},{"type":"toolCall","id":"c2","name":"read","arguments":{"path":"a.kt"}}]"""), - ) - val result = Message(id = "m3", role = "toolResult", toolCallId = "c1", isError = true, content = JsonPrimitive("nope")) - val items = jobItems(listOf(Message(id = "m1", role = "user", content = JsonPrimitive("Fix it")), assistant, result)) - assertEquals(JobItem.Task("m1", "Fix it"), items[0]) - assertEquals(JobItem.Reply("m2:0", "On it"), items[1]) - assertEquals(JobItem.Step("c1", "bash", "ls", result), items[2]) - assertEquals(JobItem.Step("c2", "read", "a.kt", null), items[3]) - } - @Test fun jobMarkdownFencesToolOutputAgainstBackticks() { val messages = listOf( @@ -209,15 +125,6 @@ class ChatParityTests { assertEquals(rows("1"), mergeJobPages(rows("1"), emptyList())) } - @Test - fun clampLevelPrefersTheNearestHigherLevel() { - assertEquals("high", clampLevel("medium", listOf("off", "high"))) - assertEquals("low", clampLevel("max", listOf("off", "low"))) - assertEquals("off", clampLevel("high", emptyList())) - assertEquals(7, levelsOf(null).size) - assertEquals(listOf("off"), levelsOf(ModelSummary(thinkingLevels = listOf("off")))) - } - @Test fun changeRowsReadLikeTheWebHeadline() { val skill = ActivityRecord( @@ -350,6 +257,66 @@ class ChatParityTests { model.cancelStream() } + @Test + fun newestJobStepRefreshesAfterSlidingToAnOlderPage() = runTest { + val scope = TestScope(StandardTestDispatcher(testScheduler)) + var shifted = false + val transport = ScriptedTransport { req -> + when (req.pathWithQuery) { + "/v1/agents/a1/coding-jobs" -> 200 to """{"jobs":[${jobFixture("fix", "working")}]}""" + "/v1/agents/a1/desktop-jobs" -> 200 to """{"jobs":[]}""" + "/v1/agents/a1/coding-jobs/fix/history?limit=100" -> if (shifted) { + 200 to history(listOf("2"), hasMore = true, oldest = "2") + } else { + 200 to """{"messages":[{"id":"1","entryId":"1","role":"assistant","content":"","replyReferences":[]}],"items":[{"kind":"step","id":"call","tool":"bash","label":"Ran","icon":"terminal"}],"hasMore":false,"oldestEntryId":"1"}""" + } + "/v1/agents/a1/coding-jobs/fix/history?limit=100&before=2" -> 200 to """{"messages":[{"id":"1","entryId":"1","role":"assistant","content":"","replyReferences":[]}],"items":[{"kind":"step","id":"call","tool":"bash","label":"Ran","icon":"terminal","result":{"id":"r","entryId":"r","role":"toolResult","content":"done","replyReferences":[]}}],"hasMore":false,"oldestEntryId":"1"}""" + else -> 503 to "" + } + } + val model = modelWith(transport, scope) + model.selectAgent("a1") + model.openJob(JobRef(JobKind.coding, "fix", "working")) + testScheduler.runCurrent() + assertNull((model.jobPanel!!.items.first() as JobHistoryItem.Variant3).value.result) + shifted = true + testScheduler.advanceTimeBy(3_100) + testScheduler.runCurrent() + val result = (model.jobPanel!!.items.first() as JobHistoryItem.Variant3).value.result?.content + model.closeJob() + assertEquals("done", result) + } + + @Test + fun loadedEarlierJobStepRefreshesWhenItsResultArrives() = runTest { + val scope = TestScope(StandardTestDispatcher(testScheduler)) + var finished = false + val transport = ScriptedTransport { req -> + when (req.pathWithQuery) { + "/v1/agents/a1/coding-jobs" -> 200 to """{"jobs":[${jobFixture("fix", "working")}]}""" + "/v1/agents/a1/desktop-jobs" -> 200 to """{"jobs":[]}""" + "/v1/agents/a1/coding-jobs/fix/history?limit=100" -> 200 to history(listOf("2"), hasMore = true, oldest = "2") + "/v1/agents/a1/coding-jobs/fix/history?limit=100&before=2" -> { + val result = if (finished) ""","result":{"id":"r","entryId":"r","role":"toolResult","content":"done","replyReferences":[]}""" else "" + 200 to """{"messages":[{"id":"1","entryId":"1","role":"assistant","content":"","replyReferences":[]}],"items":[{"kind":"step","id":"call","tool":"bash","label":"Ran","icon":"terminal"$result}],"hasMore":false,"oldestEntryId":"1"}""" + } + else -> 503 to "" + } + } + val model = modelWith(transport, scope) + model.selectAgent("a1") + model.openJob(JobRef(JobKind.coding, "fix", "working")) + testScheduler.runCurrent() + model.loadEarlierJobActivity() + testScheduler.runCurrent() + assertNull((model.jobPanel!!.items.first() as JobHistoryItem.Variant3).value.result) + finished = true + testScheduler.advanceTimeBy(3_100) + testScheduler.runCurrent() + assertEquals("done", (model.jobPanel!!.items.first() as JobHistoryItem.Variant3).value.result?.content) + model.closeJob() + } + @Test fun jobPanelFollowsAWorkingJobThenStopsPollingWhenIdle() = runTest { val scope = TestScope(StandardTestDispatcher(testScheduler)) diff --git a/app/src/test/java/dev/crumble/android/ConnectionSafetyTests.kt b/app/src/test/java/dev/crumble/android/ConnectionSafetyTests.kt index 7c18565..d273e32 100644 --- a/app/src/test/java/dev/crumble/android/ConnectionSafetyTests.kt +++ b/app/src/test/java/dev/crumble/android/ConnectionSafetyTests.kt @@ -5,7 +5,6 @@ import dev.crumble.android.model.Agent import dev.crumble.android.model.AppModel import dev.crumble.android.model.Route import dev.crumble.android.model.isExposedHttp -import dev.crumble.android.model.splitSources import dev.crumble.android.network.APIClient import dev.crumble.android.network.HttpRequestData import dev.crumble.android.network.HttpResponseData @@ -239,12 +238,6 @@ class ConnectionSafetyTests { assertEquals(2, resets) } - @Test - fun citationsOfOtherSchemesNeverBecomeChips() { - val reply = splitSources("See [source](javascript:alert(1)) and [source](intent://x).", mapOf("x" to "Title")) - assertTrue(reply.chips.isEmpty()) - } - @Test fun backupsLeaveOutTheCredentialPreferences() { val prefs = "${AndroidKeyStoreCredentials.SERVICE}.xml" diff --git a/app/src/test/java/dev/crumble/android/ContractFixtures.kt b/app/src/test/java/dev/crumble/android/ContractFixtures.kt index 15cb4ae..3a2683c 100644 --- a/app/src/test/java/dev/crumble/android/ContractFixtures.kt +++ b/app/src/test/java/dev/crumble/android/ContractFixtures.kt @@ -1,5 +1,7 @@ package dev.crumble.android +import dev.crumble.android.generated.SchedulePreview +import dev.crumble.android.model.AppModel import dev.crumble.android.model.ChatSnapshot import dev.crumble.android.model.CrumbleJson import kotlinx.serialization.json.* @@ -36,7 +38,7 @@ internal fun snapshotFixture(snapshot: ChatSnapshot): String = put("id", "chat"); put("agentId", snapshot.agentId ?: "a1"); put("title", "Chat") put("createdAt", "2026-10-18T10:00:00Z"); put("updatedAt", "2026-10-18T10:00:00Z") }) - put("status", snapshot.status ?: "idle"); put("partial", snapshot.partial.orEmpty()) + put("status", snapshot.status ?: "idle"); put("working", snapshot.working ?: if (snapshot.status == "running") "thinking" else "idle"); put("partial", snapshot.partial.orEmpty()) put("error", snapshot.error?.let(::JsonPrimitive) ?: JsonNull); put("updatedAt", 0) put("hasMore", snapshot.hasMore ?: false) put("oldestEntryId", snapshot.oldestEntryId?.let(::JsonPrimitive) ?: JsonNull) @@ -44,8 +46,28 @@ internal fun snapshotFixture(snapshot: ChatSnapshot): String = val fields = (CrumbleJson.encodeToJsonElement(message) as JsonObject).toMutableMap() fields["entryId"] = JsonPrimitive(message.entryId ?: message.id) fields["content"] = JsonPrimitive(message.text) + fields["replyReferences"] = CrumbleJson.encodeToJsonElement(message.replyReferences) + fields.remove("attachments") + message.attachments?.let { attachments -> + fields["files"] = JsonArray(attachments.map { attachment -> + buildJsonObject { + put("id", attachment.id) + if (attachment.deleted) { + put("deleted", true) + } else { + put("name", attachment.name) + put("mimeType", attachment.mimeType) + put("size", attachment.size) + } + } + }) + } JsonObject(fields) })) }.toString() internal const val executionFixture = """{"id":"e1","agentId":"a1","conversationId":"chat","scheduleId":null,"submissionId":null,"requestId":"req","status":"pending","prompt":"","error":null,"createdAt":"2026-10-18T10:00:00Z","updatedAt":"2026-10-18T10:00:00Z"}""" + +internal fun AppModel.allowTaskSave() { + acceptSchedulePreview(client!!, taskDraft!!, SchedulePreview("", "Ready", false, null)) +} diff --git a/app/src/test/java/dev/crumble/android/CronTests.kt b/app/src/test/java/dev/crumble/android/CronTests.kt deleted file mode 100644 index c33133f..0000000 --- a/app/src/test/java/dev/crumble/android/CronTests.kt +++ /dev/null @@ -1,72 +0,0 @@ -package dev.crumble.android - -import dev.crumble.android.model.describeCron -import dev.crumble.android.model.hasHashedField -import dev.crumble.android.model.nextOccurrence -import dev.crumble.android.model.wordedCron -import java.time.Instant -import java.time.ZoneId -import kotlinx.serialization.json.Json -import kotlinx.serialization.json.JsonArray -import kotlinx.serialization.json.JsonObject -import kotlinx.serialization.json.contentOrNull -import kotlinx.serialization.json.jsonArray -import kotlinx.serialization.json.jsonObject -import kotlinx.serialization.json.jsonPrimitive -import org.junit.Assert.assertEquals -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue -import org.junit.Test - -/** cron-reference.json holds what cronstrue 3.38.0 and cron-parser 5.10.2 answer for these expressions. */ -class CronTests { - private val reference: JsonObject = Json.parseToJsonElement( - checkNotNull(javaClass.classLoader?.getResource("cron-reference.json")).readText(), - ).jsonObject - private val starts = reference.getValue("from").jsonArray.map { (it as JsonArray)[0].jsonPrimitive.content to it[1].jsonPrimitive.content } - private val cases = reference.getValue("out").jsonArray.map { it.jsonObject } - private fun JsonObject.cron() = getValue("c").jsonPrimitive.content - - @Test - fun wordingMatchesCronstrue() { - val differing = cases.mapNotNull { case -> - val cron = case.cron() - val expected = case.getValue("word").jsonPrimitive.contentOrNull - // The app keeps the raw text for L, #, and seconds; cronstrue gives up on name lists it can word. - val raw = cron.any { it in "L#" } || cron == "15 30 9 * * *" - val wanted = if (raw) null else expected - (cron to "$wanted != ${wordedCron(cron)}").takeIf { wanted != wordedCron(cron) && cron != "0 12 * JAN,JUL *" } - } - assertEquals(emptyList>(), differing) - } - - @Test - fun nextRunsMatchCronParser() { - val differing = cases.filterNot { hasHashedField(it.cron()) }.flatMap { case -> - val cron = case.cron() - case.getValue("next").jsonArray.mapIndexedNotNull { index, value -> - val (from, zone) = starts[index] - val expected = value.jsonPrimitive.contentOrNull?.let(Instant::parse) - val actual = nextOccurrence(cron, ZoneId.of(zone), Instant.parse(from)) - "$cron from $from $zone: $expected != $actual".takeIf { expected != actual } - } - } - assertEquals(emptyList(), differing) - } - - @Test - fun describingMatchesTheWebFallbacks() { - assertEquals("At 09:00", describeCron("0 9 * * *", "UTC", "UTC")) - assertEquals("At 09:00 (Asia/Tokyo)", describeCron("0 9 * * *", "Asia/Tokyo", "UTC")) - assertEquals("0 0 15 * 1", describeCron("0 0 15 * 1", "UTC", "UTC")) - assertEquals("0 9 * * 1/2", describeCron("0 9 * * 1/2", "UTC", "UTC")) - assertEquals("not a cron (Asia/Tokyo)", describeCron("not a cron", "Asia/Tokyo", "UTC")) - } - - @Test - fun onlyAWholeHTokenCountsAsHashed() { - assertTrue(hasHashedField("H * * * *")) - assertTrue(hasHashedField("0 H/2 * * *")) - assertFalse(hasHashedField("0 9 * MAR THU")) - } -} diff --git a/app/src/test/java/dev/crumble/android/CrumbleTests.kt b/app/src/test/java/dev/crumble/android/CrumbleTests.kt index 3de4a1c..1d735d2 100644 --- a/app/src/test/java/dev/crumble/android/CrumbleTests.kt +++ b/app/src/test/java/dev/crumble/android/CrumbleTests.kt @@ -23,7 +23,6 @@ import dev.crumble.android.model.MentionCompletion import dev.crumble.android.model.Message import dev.crumble.android.model.MessageDeliveryState import dev.crumble.android.model.NotificationContext -import dev.crumble.android.model.OutgoingAttachment import dev.crumble.android.model.PendingAttachment import dev.crumble.android.model.Route import dev.crumble.android.model.Schedule @@ -174,11 +173,11 @@ class CrumbleTests { @Test fun runningPartialChatShowsOnlyThinkingUntilTurnCompletes() { - val partial = ChatSnapshot(status = "running", partial = "draft text", agentId = "a1") + val partial = ChatSnapshot(status = "running", working = "thinking", partial = "draft text", agentId = "a1") assertEquals(listOf(ChatRow.Thinking), ChatRow.rows(emptyList(), partial, hasMore = false)) - val first = Message(id = "m1", role = "assistant", blocks = JsonPrimitive("first")) - val second = Message(id = "m2", role = "assistant", blocks = JsonPrimitive("second")) + val first = Message(id = "m1", role = "assistant", blocks = listOf(dev.crumble.android.generated.TranscriptBlock.Variant1(dev.crumble.android.generated.TranscriptTextBlock("text", "first")))) + val second = Message(id = "m2", role = "assistant", blocks = listOf(dev.crumble.android.generated.TranscriptBlock.Variant1(dev.crumble.android.generated.TranscriptTextBlock("text", "second")))) val completed = ChatRow.rows(listOf(first, second), ChatSnapshot(status = "idle", partial = null), hasMore = false) assertEquals(listOf("m1", "m2"), completed.filterIsInstance().map { it.message.id }) assertTrue(completed.none { it is ChatRow.Partial || it is ChatRow.Thinking }) @@ -295,7 +294,7 @@ class CrumbleTests { val (client, stub) = StubTransport.client { req -> when { req.pathWithQuery.startsWith("/v1/agents/a1/chat/history") -> - 200 to """{"messages":[{"id":"a1:8:0","entryId":"a1:8","role":"user","content":"older"}],"hasMore":false,"oldestEntryId":"a1:8"}""" + 200 to """{"messages":[{"id":"a1:8:0","entryId":"a1:8","role":"user","content":"older","replyReferences":[]}],"hasMore":false,"oldestEntryId":"a1:8"}""" req.pathWithQuery == "/v1/agents/a1/messages" -> 202 to executionFixture else -> 404 to "" } @@ -316,16 +315,16 @@ class CrumbleTests { content = "", requestID = "req", replyTo = "", - attachments = listOf(OutgoingAttachment(name = "dot.png", mimeType = "image/png", data = "AAAA")), + files = listOf("33333333-3333-4333-8333-333333333333"), ) val bodyStr = String(stub.requests.last().body ?: ByteArray(0), StandardCharsets.UTF_8) val obj = CrumbleJson.parseToJsonElement(bodyStr) as JsonObject assertNull(obj["replyTo"]) - val attachmentsArr = obj["attachments"] as JsonArray - assertEquals(JsonPrimitive("image/png"), (attachmentsArr.first() as JsonObject)["mimeType"]) + assertNull(obj["attachments"]) + assertEquals(JsonArray(listOf(JsonPrimitive("33333333-3333-4333-8333-333333333333"))), obj["files"]) val msg = CrumbleJson.decodeFromString( Message.serializer(), - """{"id":"a1:5:0","role":"user","content":"","attachments":[{"name":"dot.png","mimeType":"image/png","size":70,"kind":"image"}]}""", + """{"id":"a1:5:0","role":"user","content":"","attachments":[{"id":"33333333-3333-4333-8333-333333333333","name":"dot.png","mimeType":"image/png","size":70}]}""", ) assertTrue(msg.attachments?.first()?.isImage == true) assertTrue(ChatRow.shownInChat(msg)) @@ -334,7 +333,10 @@ class CrumbleTests { @Test fun failedSendsKeepTheirAttachments() = runTest { val testScope = TestScope(StandardTestDispatcher(testScheduler)) - val (client, _) = StubTransport.client { 500 to """{"error":"busy"}""" } + val (client, stub) = StubTransport.client { request -> + if (request.pathWithQuery.endsWith("/files")) 201 to uploadedFileFixture() + else 500 to """{"error":"busy"}""" + } val model = AppModel(client = client, scope = testScope) model.snapshot = ChatSnapshot(status = "idle", agentId = "a1") model.attachments = listOf(PendingAttachment(name = "notes.txt", mimeType = "text/plain", data = "hi".toByteArray())) @@ -343,6 +345,7 @@ class CrumbleTests { advanceUntilIdle() assertEquals(listOf("notes.txt"), model.attachments.map { it.name }) assertTrue(model.errorText.contains("busy")) + assertEquals(listOf("/files", "/messages"), stub.requests.map { "/" + it.pathWithQuery.substringAfterLast("/") }) } @Test @@ -367,7 +370,7 @@ class CrumbleTests { @Test fun taskPickersPreserveTheInstantAndSubmitOnlyTheSelectedMode() = runTest { val testScope = TestScope(StandardTestDispatcher(testScheduler)) - val response = """{"id":"s1","agentId":"a1","name":"Greeting","kind":"prompt","prompt":"Say hi","command":null,"timeoutSeconds":600,"notify":true,"eventSourceId":null,"enabled":true,"timezone":"Europe/Berlin","runAt":"2026-10-18T10:10:00Z","cron":null,"nextRunAt":null,"createdAt":"2026-10-18T10:00:00Z","createdByAgentId":null}""" + val response = """{"id":"s1","agentId":"a1","name":"Greeting","kind":"prompt","prompt":"Say hi","command":null,"timeoutSeconds":600,"notify":true,"eventSourceId":null,"enabled":true,"timezone":"Europe/Berlin","runAt":"2026-10-18T10:10:00Z","cron":null,"nextRunAt":null,"nextRunLabel":"Soon","description":"Once","timing":"Once","createdAt":"2026-10-18T10:00:00Z","createdByAgentId":null}""" val (client, stub) = StubTransport.client { req -> 200 to if (req.method == "PATCH") response else "[]" } @@ -384,6 +387,7 @@ class CrumbleTests { assertEquals(12, zdt.hour) assertEquals(10, zdt.minute) model.taskDraft = draft.copy(repeats = repeats) + model.allowTaskSave() model.saveTask() advanceUntilIdle() assertFalse(model.loading) @@ -499,7 +503,7 @@ class CrumbleTests { @Test fun requestBotResultBecomesAChatRow() = runTest { val (client, _) = StubTransport.client { - 200 to """{"messages":[{"id":"t1","entryId":"t","role":"toolResult","content":"","toolName":"request_bot","toolDetails":{"id":"r1","proposal":{"name":"Scout"}}},{"id":"t2","entryId":"t","role":"toolResult","content":"","toolName":"request_bot","isError":true}],"hasMore":false,"oldestEntryId":null}""" + 200 to """{"messages":[{"id":"t1","entryId":"t","role":"toolResult","content":"","replyReferences":[],"toolName":"request_bot","toolDetails":{"id":"r1","proposal":{"name":"Scout"}}},{"id":"t2","entryId":"t","role":"toolResult","content":"","replyReferences":[],"toolName":"request_bot","isError":true}],"hasMore":false,"oldestEntryId":null}""" } val messages = client.chatHistory("a1", before = "t", limit = 10).messages.orEmpty() assertEquals(BotRequestRef("r1", "Scout"), messages[0].botRequest) @@ -870,12 +874,9 @@ class CrumbleTests { } @Test - fun tasksNeedExactlyOneScheduleMode() { - assertNotNull(validateTask(name = "", prompt = "", cron = "", runAt = "")) - assertNotNull(validateTask(name = "Daily", prompt = "Check inbox", cron = "0 9 * * *", runAt = "2026-10-18T09:00:00Z")) - assertNull(validateTask(name = "Daily", prompt = "Check inbox", cron = "0 9 * * *", runAt = "")) - assertNull(validateTask(name = "Once", prompt = "Check inbox", cron = "", runAt = "2026-10-18T09:00:00Z")) - assertNotNull(validateTask(name = "Once", prompt = "Check inbox", cron = "", runAt = "tomorrow")) + fun tasksNeedNameAndPrompt() { + assertNotNull(validateTask(name = "", prompt = "")) + assertNull(validateTask(name = "Daily", prompt = "Check inbox")) } @Test @@ -884,7 +885,6 @@ class CrumbleTests { val fractional = taskRunDate("2026-10-18T12:10:00.123Z")!! val whole = taskRunDate("2026-10-18T12:10:00Z")!! assertTrue(abs((fractional.toEpochMilli() - whole.toEpochMilli()) - 123L) <= 1L) - assertNotNull(validateTask(name = "Task", prompt = "Hi", cron = "0 9 * * *", runAt = "", timezone = "Not/AZone")) } @Test @@ -898,13 +898,13 @@ class CrumbleTests { val tool = Message( id = "a1:1:0", role = "assistant", - blocks = JsonArray(listOf(JsonObject(mapOf("type" to JsonPrimitive("toolCall"))))), + blocks = listOf(dev.crumble.android.generated.TranscriptBlock.Variant4(dev.crumble.android.generated.TranscriptToolCallBlock("toolCall", "c", "tool", emptyMap()))), ) val reply = Message( id = "a1:1:1", role = "assistant", content = JsonPrimitive("Hi"), - blocks = JsonArray(listOf(JsonObject(mapOf("type" to JsonPrimitive("text"), "text" to JsonPrimitive("Hi"))))), + blocks = listOf(dev.crumble.android.generated.TranscriptBlock.Variant1(dev.crumble.android.generated.TranscriptTextBlock("text", "Hi"))), ) assertFalse(ChatRow.shownInChat(tool)) assertTrue(ChatRow.shownInChat(reply)) diff --git a/app/src/test/java/dev/crumble/android/DraftsAndReadsTests.kt b/app/src/test/java/dev/crumble/android/DraftsAndReadsTests.kt index 79aeb7e..8d5ff71 100644 --- a/app/src/test/java/dev/crumble/android/DraftsAndReadsTests.kt +++ b/app/src/test/java/dev/crumble/android/DraftsAndReadsTests.kt @@ -1,6 +1,7 @@ package dev.crumble.android import dev.crumble.android.model.Agent +import dev.crumble.android.model.AttachmentInfo import dev.crumble.android.model.AppModel import dev.crumble.android.model.ChatSnapshot import dev.crumble.android.model.CrumbleJson @@ -57,6 +58,7 @@ private class Scripted : HttpTransport { responses["GET /v1/agents/a1/memories"] = 200 to "[]" responses["GET /v1/agents/a2/memories"] = 200 to "[]" responses[SEND] = 202 to executionFixture + responses["POST /v1/agents/a1/files"] = 201 to uploadedFileFixture() } fun hold(key: String) = CompletableDeferred().also { held[key] = it } @@ -80,7 +82,7 @@ private class Scripted : HttpTransport { } private fun scheduleJson(id: String, name: String) = - """{"id":"$id","agentId":"a1","name":"$name","kind":"prompt","prompt":"Hi","command":null,"timeoutSeconds":600,"notify":false,"eventSourceId":null,"enabled":true,"timezone":"UTC","runAt":null,"cron":"0 9 * * *","nextRunAt":null,"createdAt":"2026-11-05T10:00:00Z","createdByAgentId":null}""" + """{"id":"$id","agentId":"a1","name":"$name","kind":"prompt","prompt":"Hi","command":null,"timeoutSeconds":600,"notify":false,"eventSourceId":null,"enabled":true,"timezone":"UTC","runAt":null,"cron":"0 9 * * *","nextRunAt":null,"nextRunLabel":"Soon","description":"Once","timing":"Once","createdAt":"2026-11-05T10:00:00Z","createdByAgentId":null}""" private fun scheduleOf(id: String, name: String = "Task") = CrumbleJson.decodeFromString(Schedule.serializer(), scheduleJson(id, name)) @@ -210,6 +212,12 @@ class DraftsAndReadsTests { assertEquals(1, transport.requestIDs().toSet().size) assertEquals(2, transport.requestIDs().size) + assertEquals(1, transport.sent("POST /v1/agents/a1/files").size) + transport.sent(SEND).forEach { request -> + val body = CrumbleJson.parseToJsonElement(request.body!!.toString(StandardCharsets.UTF_8)).jsonObject + assertEquals(listOf("33333333-3333-4333-8333-333333333333"), body["files"]!!.jsonArray.map { it.jsonPrimitive.content }) + assertNull(body["attachments"]) + } assertEquals(1, model.messages.count { it.text == "only once" }) assertEquals(MessageDeliveryState.sending, model.messages.single().deliveryState) assertEquals("", model.draft) @@ -412,6 +420,7 @@ class DraftsAndReadsTests { model.schedules = listOf(scheduleOf("s1", "Before")) model.openTaskForm("s1") model.taskDraft = model.taskDraft!!.copy(name = "Mine") + model.allowTaskSave() model.saveTask() runCurrent() @@ -466,11 +475,18 @@ class DraftsAndReadsTests { @Test fun attachmentImagesDoNotOutliveTheSession() = scenario { val transport = Scripted().apply { - responses["GET /v1/agents/a1/attachments/a1%3A1/0"] = 200 to "image" + responses["GET /v1/agents/a1/files/33333333-3333-4333-8333-333333333333"] = 200 to "image" + responses["GET /v1/agents/a1/chat?limit=5"] = 200 to snapshotFixture(ChatSnapshot( + agentId = "a1", messages = listOf(Message( + id = "a1:1:0", entryId = "a1:1", role = "user", + attachments = listOf(AttachmentInfo(id = "33333333-3333-4333-8333-333333333333", name = "image.png", mimeType = "image/png", size = 5)), + )), + )) } val model = model(transport) openChat(model) model.loadAttachmentImage("a1:1", 0) + assertEquals("/v1/agents/a1/files/33333333-3333-4333-8333-333333333333", transport.requests.last().pathWithQuery) assertEquals(1, model.attachmentBytes.size) model.token = "session" @@ -509,6 +525,7 @@ class DraftsAndReadsTests { model.schedules = listOf(scheduleOf("s1"), scheduleOf("s2")) model.openTaskForm("s1") model.taskDraft = model.taskDraft!!.copy(name = "Renamed") + model.allowTaskSave() model.saveTask() runCurrent() diff --git a/app/src/test/java/dev/crumble/android/FileCompatibilityTests.kt b/app/src/test/java/dev/crumble/android/FileCompatibilityTests.kt new file mode 100644 index 0000000..e12cbe1 --- /dev/null +++ b/app/src/test/java/dev/crumble/android/FileCompatibilityTests.kt @@ -0,0 +1,379 @@ +package dev.crumble.android + +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.AttachmentInfo +import dev.crumble.android.model.Message +import dev.crumble.android.model.ChatSnapshot +import dev.crumble.android.model.CrumbleJson +import dev.crumble.android.model.MessageDeliveryState +import dev.crumble.android.model.PendingAttachment +import dev.crumble.android.network.APIClient +import dev.crumble.android.network.HttpRequestData +import dev.crumble.android.network.HttpResponseData +import dev.crumble.android.network.HttpStreamResponse +import dev.crumble.android.network.HttpTransport +import dev.crumble.android.network.domain +import java.io.ByteArrayInputStream +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import org.junit.Assert.* +import org.junit.Test + +private const val FILE = "33333333-3333-4333-8333-333333333333" +private const val OTHER_FILE = "44444444-4444-4444-8444-444444444444" +private const val GROUP = "11111111-1111-4111-8111-111111111111" +private const val BOT = "/v1/agents/a1" +private const val GROUP_PATH = "/v1/group-chats/$GROUP" + +internal fun uploadedFileFixture(id: String = FILE) = + """{"file":{"id":"$id","name":"image.png","mimeType":"image/png","size":4,"createdAt":"2026-11-14T00:00:00Z"},"existed":false}""" + +private class FileTransport : HttpTransport { + val requests = mutableListOf() + var uploadCount = 0 + var failUpload: Int? = null + var sendStatus = 202 + var sendError = "busy" + var heldUpload: CompletableDeferred? = null + var heldDownload: CompletableDeferred? = null + var snapshot = snapshotFixture(ChatSnapshot(agentId = "a1")) + var groupMessages = "[]" + val downloads = byteArrayOf(0, -1, 10, 127) + + fun sends() = requests.filter { it.method == "POST" && it.pathWithQuery.endsWith("/messages") } + fun uploads() = requests.filter { it.method == "POST" && it.pathWithQuery.endsWith("/files") } + + override suspend fun execute(request: HttpRequestData): HttpResponseData { + requests.add(request) + val path = request.pathWithQuery + if (request.method == "POST" && path.endsWith("/files")) { + uploadCount++ + val number = uploadCount + heldUpload?.await() + return if (number == failUpload) HttpResponseData(503, """{"error":"upload failed"}""".toByteArray()) + else HttpResponseData(201, uploadedFileFixture(if (number == 1) FILE else OTHER_FILE).toByteArray()) + } + if (request.method == "GET" && "/files/" in path) { + heldDownload?.await() + return HttpResponseData(200, downloads) + } + val (status, body) = when { + request.method == "POST" && path.endsWith("/messages") -> sendStatus to + if (sendStatus >= 400) """{"error":"$sendError"}""" + else if (path.startsWith("/v1/group-chats/")) """{"requestId":"r","entryId":"e"}""" else executionFixture + path.startsWith("$BOT/chat") -> 200 to snapshot + path == "$GROUP_PATH/chat" -> 200 to """{"messages":$groupMessages,"hasMore":false,"oldestEntryId":null,"groupChat":{"id":"$GROUP","name":"Team","memberIds":["a1","a2"],"createdAt":"t","updatedAt":"t"},"activity":{"paused":false,"botTurns":0,"members":[]},"updatedAt":1}""" + path == "/v1/agents" -> 200 to "[${agentFixture("a1")}]" + path.endsWith("/memories") || path == "/v1/group-chats" -> 200 to "[]" + else -> 404 to "" + } + return HttpResponseData(status, body.toByteArray()) + } + + override suspend fun openStream(request: HttpRequestData) = HttpStreamResponse(503, ByteArrayInputStream(byteArrayOf())) +} + +@OptIn(ExperimentalCoroutinesApi::class) +class FileCompatibilityTests { + private fun TestScope.open(transport: FileTransport): AppModel = AppModel( + client = APIClient("https://crumble.test", "owner", transport), + scope = backgroundScope, + transport = transport, + ).also { + it.selectAgent("a1") + runCurrent() + it.applySnapshot(ChatSnapshot(agentId = "a1")) + } + + private fun image(name: String = "image.png") = PendingAttachment( + name = name, mimeType = "image/png", data = byteArrayOf(0, -1, 10, 127), + ) + + private fun body(request: HttpRequestData) = CrumbleJson.parseToJsonElement(request.body!!.toString(Charsets.UTF_8)).jsonObject + + @Test + fun botSendUploadsRawBytesAndUsesFileIds() = runTest { + val transport = FileTransport() + val app = open(transport) + app.draft = "Look" + app.addAttachment(image("über %.png")) + app.sendMessage() + assertEquals(MessageDeliveryState.sending, app.messages.single().deliveryState) + runCurrent() + + assertEquals(1, transport.uploads().size) + val upload = transport.uploads().single() + assertEquals("$BOT/files", upload.pathWithQuery) + assertArrayEquals(byteArrayOf(0, -1, 10, 127), upload.body) + assertEquals("image/png", upload.headers.entries.single { it.key.equals("content-type", true) }.value) + assertEquals("%C3%BCber%20%25.png", upload.headers.entries.single { it.key.equals("x-file-name", true) }.value) + assertEquals("Bearer owner", upload.headers["Authorization"]) + assertEquals(120_000, upload.timeoutMs) + val sent = body(transport.sends().single()) + assertEquals(JsonArray(listOf(JsonPrimitive(FILE))), sent["files"]) + assertFalse(sent.containsKey("attachments")) + assertEquals("Look", sent["content"]!!.jsonPrimitive.content) + assertEquals("application/json", transport.sends().single().headers["Content-Type"]) + } + + @Test + fun partialUploadFailureRetainsTheDraftAndReusesSuccessfulFiles() = runTest { + val transport = FileTransport().apply { failUpload = 2 } + val app = open(transport) + app.draft = "Look" + app.attachments = listOf(image("one.png"), image("two.png")) + app.sendMessage() + runCurrent() + assertEquals(2, transport.uploads().size) + assertTrue(transport.sends().isEmpty()) + val failed = app.messages.single() + assertEquals(MessageDeliveryState.failed, failed.deliveryState) + assertEquals("Look", app.draft) + assertEquals(2, app.attachments.size) + + app.sendMessage() + runCurrent() + assertEquals(3, transport.uploads().size) + val sent = body(transport.sends().single()) + assertEquals(failed.requestId, sent["requestId"]!!.jsonPrimitive.content) + assertEquals(listOf(FILE, OTHER_FILE), sent["files"]!!.jsonArray.map { it.jsonPrimitive.content }) + assertEquals(1, app.messages.size) + } + + @Test + fun connectionChangeDuringUploadCannotSendOrRestoreTheOldDraft() = runTest { + val gate = CompletableDeferred() + val transport = FileTransport().apply { heldUpload = gate } + val app = open(transport) + app.draft = "Old connection" + app.addAttachment(image()) + app.sendMessage() + runCurrent() + assertEquals(1, transport.uploads().size) + app.signOut() + runCurrent() + app.draft = "New draft" + gate.complete(Unit) + runCurrent() + assertTrue(transport.sends().isEmpty()) + assertEquals("New draft", app.draft) + } + + private fun fileSnapshot(files: String): String { + val fields = CrumbleJson.parseToJsonElement(snapshotFixture(ChatSnapshot(agentId = "a1"))).jsonObject.toMutableMap() + fields["messages"] = CrumbleJson.parseToJsonElement("""[{"id":"m1","entryId":"a1:1","role":"user","content":"Look","replyReferences":[],"files":$files}]""") + return JsonObject(fields).toString() + } + + @Test + fun transcriptFilesDecodeFromHttpAndEventsAndFetchById() = runTest { + val transport = FileTransport().apply { + snapshot = fileSnapshot("""[{"id":"$FILE","name":"image.png","mimeType":"image/png","size":4},{"id":"$OTHER_FILE","deleted":true}]""") + } + val api = APIClient("https://crumble.test", "owner", transport) + val message = api.chat("a1").messages!!.single() + assertEquals(2, message.attachments.orEmpty().size) + assertTrue(message.attachments!![0].isImage) + assertFalse(message.attachments[1].isImage) + assertEquals(FILE, message.attachments[0].id) + assertTrue(message.attachments[1].deleted) + val event = CrumbleJson.decodeFromString(transport.snapshot).domain() + assertEquals(message.attachments, event.messages!!.single().attachments) + val app = open(transport) + app.applySnapshot(api.chat("a1")) + app.loadAttachmentImage("a1:1", 0) + assertEquals("$BOT/files/$FILE", transport.requests.last().pathWithQuery) + assertArrayEquals(transport.downloads, app.attachmentImageBytes(message, 0)) + val count = transport.requests.size + app.loadAttachmentImage("a1:1", 1) + assertEquals(count, transport.requests.size) + } + + @Test + fun ambiguousSendFailureRetriesWithTheSameFilesAndRequestId() = runTest { + val transport = FileTransport().apply { sendStatus = 503 } + val app = open(transport) + app.draft = "Look" + app.addAttachment(image()) + app.sendMessage() + runCurrent() + val failed = app.messages.single() + assertEquals(MessageDeliveryState.failed, failed.deliveryState) + transport.sendStatus = 202 + app.retryMessage(failed) + runCurrent() + assertEquals(1, transport.uploads().size) + assertEquals(2, transport.sends().size) + assertEquals(body(transport.sends()[0]), body(transport.sends()[1])) + } + + @Test + fun definitelyDeletedUploadIsReuploadedOnExplicitRetry() = runTest { + val transport = FileTransport().apply { + sendStatus = 400 + sendError = "image.png was deleted from the library" + } + val app = open(transport) + app.draft = "Look" + app.addAttachment(image()) + app.sendMessage() + runCurrent() + val failed = app.messages.single() + transport.sendStatus = 202 + app.retryMessage(failed) + runCurrent() + assertEquals(2, transport.uploads().size) + val sent = transport.sends().map(::body) + assertEquals(sent[0]["requestId"], sent[1]["requestId"]) + assertEquals(JsonArray(listOf(JsonPrimitive(FILE))), sent[0]["files"]) + assertEquals(JsonArray(listOf(JsonPrimitive(OTHER_FILE))), sent[1]["files"]) + } + + @Test + fun navigatingDuringUploadKeepsTheSendWithItsOriginalBot() = runTest { + val gate = CompletableDeferred() + val transport = FileTransport().apply { heldUpload = gate } + val app = open(transport) + app.draft = "For a1" + app.addAttachment(image()) + app.sendMessage() + runCurrent() + app.selectAgent("a2") + app.draft = "For a2" + gate.complete(Unit) + runCurrent() + assertEquals("$BOT/messages", transport.sends().single().pathWithQuery) + assertEquals("For a2", app.draft) + assertEquals("a2", app.selectedAgentID) + } + + @Test + fun deletionHidesCachedImagesAndDoesNotFetchAgain() = runTest { + val transport = FileTransport().apply { + snapshot = fileSnapshot("""[{"id":"$FILE","name":"image.png","mimeType":"image/png","size":4}]""") + } + val api = APIClient("https://crumble.test", "owner", transport) + val app = open(transport) + app.applySnapshot(api.chat("a1")) + app.loadAttachmentImage("a1:1", 0) + assertArrayEquals(transport.downloads, app.attachmentImageBytes(app.messages.single(), 0)) + transport.snapshot = fileSnapshot("""[{"id":"$FILE","deleted":true}]""") + app.applySnapshot(api.chat("a1")) + assertNull(app.attachmentImageBytes(app.messages.single(), 0)) + val count = transport.requests.size + app.loadAttachmentImage("a1:1", 0) + assertEquals(count, transport.requests.size) + } + + @Test + fun deletionDuringDownloadDiscardsItsLateBytes() = runTest { + val gate = CompletableDeferred() + val transport = FileTransport().apply { + snapshot = fileSnapshot("""[{"id":"$FILE","name":"image.png","mimeType":"image/png","size":4}]""") + heldDownload = gate + } + val api = APIClient("https://crumble.test", "owner", transport) + val app = open(transport) + app.applySnapshot(api.chat("a1")) + val download = backgroundScope.launch { app.loadAttachmentImage("a1:1", 0) } + runCurrent() + assertEquals("$BOT/files/$FILE", transport.requests.last().pathWithQuery) + transport.snapshot = fileSnapshot("""[{"id":"$FILE","deleted":true}]""") + app.applySnapshot(api.chat("a1")) + gate.complete(Unit) + download.join() + assertTrue(app.attachmentBytes.isEmpty()) + assertNull(app.attachmentImageBytes(app.messages.single(), 0)) + } + + private fun sharedFileMessage(id: String, deleted: Boolean = false) = Message( + id = id, entryId = id, role = "user", content = JsonPrimitive("Look"), + attachments = listOf(if (deleted) AttachmentInfo(id = FILE, deleted = true) + else AttachmentInfo(id = FILE, name = "image.png", mimeType = "image/png", size = 4)), + ) + + @Test + fun partialDeletionInvalidatesEveryRetainedReferenceToTheFile() = runTest { + val transport = FileTransport() + val app = open(transport) + app.applySnapshot(ChatSnapshot(agentId = "a1", messages = listOf(sharedFileMessage("old"), sharedFileMessage("recent")))) + app.loadAttachmentImage("old", 0) + assertArrayEquals(transport.downloads, app.attachmentImageBytes(app.messages.first(), 0)) + app.applySnapshot(ChatSnapshot(agentId = "a1", messages = listOf(sharedFileMessage("recent", deleted = true)))) + assertEquals(2, app.messages.size) + assertTrue(app.messages.all { it.attachments!!.single().deleted }) + assertTrue(app.attachmentBytes.isEmpty()) + assertNull(app.attachmentImageBytes(app.messages.first(), 0)) + val count = transport.requests.size + app.loadAttachmentImage("old", 0) + assertEquals(count, transport.requests.size) + } + + @Test + fun partialDeletionDiscardsAnOlderReferencesInflightDownload() = runTest { + val gate = CompletableDeferred() + val transport = FileTransport().apply { heldDownload = gate } + val app = open(transport) + app.applySnapshot(ChatSnapshot(agentId = "a1", messages = listOf(sharedFileMessage("old"), sharedFileMessage("recent")))) + val download = backgroundScope.launch { app.loadAttachmentImage("old", 0) } + runCurrent() + app.applySnapshot(ChatSnapshot(agentId = "a1", messages = listOf(sharedFileMessage("recent", deleted = true)))) + gate.complete(Unit) + download.join() + assertTrue(app.attachmentBytes.isEmpty()) + assertNull(app.attachmentImageBytes(app.messages.first(), 0)) + } + + @Test + fun groupUploadsRetainFilesAndRequestIdAcrossRetry() = runTest { + val transport = FileTransport().apply { failUpload = 2 } + val app = open(transport) + app.openGroupChat(GROUP) + runCurrent() + assertNotNull(app.groupConversation?.group) + app.updateGroupComposer(GROUP) { it.copy(draft = "Look", attachments = listOf(image("one.png"), image("two.png"))) } + app.sendGroupMessage() + runCurrent() + assertEquals(2, transport.uploads().size) + assertTrue(transport.sends().isEmpty()) + val failed = app.groupOutgoing[GROUP]!!.single() + assertEquals(MessageDeliveryState.failed, failed.deliveryState) + assertArrayEquals(image().data, app.groupAttachmentImageBytes(failed, 0)) + app.retryGroupMessage(failed) + runCurrent() + assertEquals(3, transport.uploads().size) + assertTrue(transport.uploads().all { it.pathWithQuery == "$GROUP_PATH/files" }) + val send = transport.sends().single() + assertEquals("$GROUP_PATH/messages", send.pathWithQuery) + assertEquals(failed.requestId, body(send)["requestId"]!!.jsonPrimitive.content) + assertEquals(listOf(FILE, OTHER_FILE), body(send)["files"]!!.jsonArray.map { it.jsonPrimitive.content }) + } + + @Test + fun groupHistoryFetchesByFileIdAndSkipsDeletedFiles() = runTest { + val transport = FileTransport().apply { + groupMessages = """[{"id":"m1","entryId":"g:1","role":"user","content":"Look","replyReferences":[],"files":[{"id":"$FILE","name":"image.png","mimeType":"image/png","size":4},{"id":"$OTHER_FILE","deleted":true}]}]""" + } + val app = open(transport) + app.openGroupChat(GROUP) + runCurrent() + val message = app.groupConversation!!.messages.single() + assertEquals(listOf(FILE, OTHER_FILE), message.attachments!!.map { it.id }) + app.loadGroupAttachmentImage("g:1", 0) + assertEquals("$GROUP_PATH/files/$FILE", transport.requests.last().pathWithQuery) + assertArrayEquals(transport.downloads, app.groupAttachmentImageBytes(message, 0)) + val count = transport.requests.size + app.loadGroupAttachmentImage("g:1", 1) + assertEquals(count, transport.requests.size) + } +} diff --git a/app/src/test/java/dev/crumble/android/GeneratedContractTests.kt b/app/src/test/java/dev/crumble/android/GeneratedContractTests.kt index 69d7029..076ce29 100644 --- a/app/src/test/java/dev/crumble/android/GeneratedContractTests.kt +++ b/app/src/test/java/dev/crumble/android/GeneratedContractTests.kt @@ -6,7 +6,6 @@ import dev.crumble.android.generated.UpdateScheduleRequest import dev.crumble.android.model.ChatSnapshot import dev.crumble.android.model.CrumbleJson import dev.crumble.android.model.CrumblePatchJson -import dev.crumble.android.model.OutgoingAttachment import dev.crumble.android.network.APIClient import dev.crumble.android.network.APIError import dev.crumble.android.network.HttpRequestData @@ -27,6 +26,33 @@ import org.junit.Test @OptIn(kotlinx.serialization.ExperimentalSerializationApi::class) class GeneratedContractTests { + @Test + fun presentationSurvivesHttpAndEventDecodingWithoutChangingRawContent() = runTest { + val presentation = dev.crumble.android.generated.MessagePresentation("Clean reply", listOf(dev.crumble.android.generated.Citation("https://example.com", "Example", "example.com"))) + val message = dev.crumble.android.model.Message(id = "m1", entryId = "e1", role = "assistant", content = JsonPrimitive("Raw [source](https://example.com)"), presentation = presentation) + val snapshot = ChatSnapshot(agentId = "a1", messages = listOf(message)) + val payload = snapshotFixture(snapshot) + val (client, _) = StubTransport.client { 200 to payload } + val fromHttp = client.chat("a1").messages!!.single() + assertEquals(message.text, fromHttp.text) + assertEquals(presentation, fromHttp.presentation) + val event = CrumbleJson.decodeFromString(payload) + assertEquals(presentation, event.messages.single().presentation) + } + + @Test + fun schedulePreviewUsesServerTextAndSendsTheDraft() = runTest { + val (client, transport) = StubTransport.client { + 200 to """{"description":"Server description","text":"Server preview","isProblem":false,"nextRunAt":null}""" + } + val preview = client.previewSchedule("0 9 * * *", null, null, "Europe/Berlin") + assertEquals("Server preview", preview.text) + assertEquals("Server description", preview.description) + val body = Json.parseToJsonElement(transport.requests.single().body!!.toString(Charsets.UTF_8)).jsonObject + assertEquals("0 9 * * *", body.getValue("cron").jsonPrimitive.content) + assertEquals("Europe/Berlin", body.getValue("timezone").jsonPrimitive.content) + } + @Test fun patchRoundTripDistinguishesAbsentFromExplicitNull() { val absent = CrumblePatchJson.decodeFromString("{}") @@ -119,14 +145,18 @@ class GeneratedContractTests { } @Test - fun generatedMessageOperationPreservesAttachmentTimeoutAndOptionalOmission() = runTest { + fun generatedMessageOperationPreservesFileTimeoutAndOptionalOmission() = runTest { val (client, transport) = StubTransport.client { 202 to executionFixture } client.sendChatMessage("a1", "text", "request", "") - client.sendChatMessage("a1", "", "request", "", listOf(OutgoingAttachment("image", "image/png", "AAAA"))) + client.sendChatMessage("a1", "", "request", "", listOf("33333333-3333-4333-8333-333333333333")) assertEquals(listOf(20_000, 120_000), transport.requests.map { it.timeoutMs }) val body = Json.parseToJsonElement(transport.requests.first().body!!.toString(Charsets.UTF_8)).jsonObject assertFalse(body.containsKey("replyTo")) assertFalse(body.containsKey("attachments")) + assertFalse(body.containsKey("files")) + val withFile = Json.parseToJsonElement(transport.requests.last().body!!.toString(Charsets.UTF_8)).jsonObject + assertEquals(JsonArray(listOf(JsonPrimitive("33333333-3333-4333-8333-333333333333"))), withFile["files"]) + assertFalse(withFile.containsKey("attachments")) } @Test @@ -164,8 +194,8 @@ class GeneratedContractTests { } catch (_: SSEClosedError) { } assertEquals("Hello", preview) - val message = CrumblePatchJson.decodeFromString("""{"id":"m1","entryId":"e1","role":"assistant","content":"","blocks":{"provider":[null,true,1,"text"]}}""") - assertEquals(JsonPrimitive(true), message.blocks!!.jsonObject["provider"]!!.jsonArray[1]) + val message = CrumblePatchJson.decodeFromString("""{"id":"m1","entryId":"e1","role":"assistant","content":"","replyReferences":[],"blocks":[{"type":"thinking","thinking":"reason"}]}""") + assertTrue(message.blocks!!.single() is dev.crumble.android.generated.TranscriptBlock.Variant2) } @Test diff --git a/app/src/test/java/dev/crumble/android/GroupChatTests.kt b/app/src/test/java/dev/crumble/android/GroupChatTests.kt index f98bc0a..594c80e 100644 --- a/app/src/test/java/dev/crumble/android/GroupChatTests.kt +++ b/app/src/test/java/dev/crumble/android/GroupChatTests.kt @@ -15,13 +15,11 @@ import dev.crumble.android.model.GroupSnapshot import dev.crumble.android.model.Message import dev.crumble.android.model.MessageDeliveryState import dev.crumble.android.model.MessageOrigin -import dev.crumble.android.model.MessageSource import dev.crumble.android.model.NotificationContext import dev.crumble.android.model.PendingAttachment import dev.crumble.android.model.Route import dev.crumble.android.model.groupReactions import dev.crumble.android.model.groupReplyLabel -import dev.crumble.android.model.groupSourcesOf import dev.crumble.android.model.groupStatusLine import dev.crumble.android.model.isGroupRunning import dev.crumble.android.model.isValidGroup @@ -59,6 +57,7 @@ import org.junit.Test private const val G1 = "11111111-1111-4111-8111-111111111111" private const val G2 = "22222222-2222-4222-8222-222222222222" +private const val FILE = "33333333-3333-4333-8333-333333333333" private const val BASE = "/v1/group-chats" private const val RECONNECTING = "Reconnecting…" @@ -66,7 +65,7 @@ private fun groupJson(id: String = G1, name: String = "Team", members: List = emptyList(), @@ -86,6 +85,7 @@ private class GroupTransport : HttpTransport { val responses = mutableMapOf>( "GET $BASE" to (200 to "[${groupJson()}]"), "GET $BASE/$G1/chat" to (200 to snapshotJson()), + "POST $BASE/$G1/files" to (201 to uploadedFileFixture(FILE)), "POST $BASE/$G1/messages" to (201 to """{"requestId":"r","entryId":"e"}"""), "POST $BASE/$G1/stop" to (204 to ""), "DELETE $BASE/$G1" to (204 to ""), @@ -101,7 +101,7 @@ private class GroupTransport : HttpTransport { requests.add(request) val key = key(request) held[key]?.await() - if (bytes.isNotEmpty() && "/attachments/" in key) return HttpResponseData(200, bytes) + if (bytes.isNotEmpty() && request.method == "GET" && "/files/" in key) return HttpResponseData(200, bytes) val (status, body) = responses[key] ?: (500 to """{"error":"unscripted $key"}""") return HttpResponseData(status, body.toByteArray(StandardCharsets.UTF_8)) } @@ -185,8 +185,8 @@ class GroupChatTests { val sent = bodyOf(transport.sent("POST $BASE/$G1/messages").single()) assertEquals("r1", sent["requestId"]!!.jsonPrimitive.content) assertEquals("e1", sent["replyTo"]!!.jsonPrimitive.content) - assertArrayEquals(byteArrayOf(1, 2), api.groupAttachment(G1, "e:1", 0)) - assertEquals("/v1/group-chats/$G1/attachments/e%3A1/0", transport.requests.last().pathWithQuery) + assertArrayEquals(byteArrayOf(1, 2), api.groupFile(G1, FILE)) + assertEquals("$BASE/$G1/files/$FILE", transport.requests.last().pathWithQuery) api.stopGroupChat(G1) val failure = runCatching { api.groupChatEvents(G1) {} }.exceptionOrNull() assertEquals(404, (failure as dev.crumble.android.network.APIError).statusCode) @@ -556,7 +556,11 @@ class GroupChatTests { val sends = transport.sent("POST $BASE/$G1/messages").map { bodyOf(it) } assertEquals(2, sends.size) assertEquals(sends[0]["requestId"], sends[1]["requestId"]) - assertEquals("a.png", sends[1]["attachments"]!!.jsonArray[0].jsonObject["name"]!!.jsonPrimitive.content) + assertEquals(1, transport.sent("POST $BASE/$G1/files").size) + assertEquals(listOf(FILE), sends[0]["files"]!!.jsonArray.map { it.jsonPrimitive.content }) + assertEquals(sends[0]["files"], sends[1]["files"]) + assertFalse(sends[0].containsKey("attachments")) + assertFalse(sends[1].containsKey("attachments")) } @Test @@ -694,12 +698,33 @@ class GroupChatTests { } @Test - fun groupImagesComeFromTheGroupAttachmentRoute() = runTest { + fun groupImagesComeFromTheGroupFileRoute() = runTest { val transport = GroupTransport().apply { bytes = byteArrayOf(9) } - val app = opened(transport) + val fileRow = row(1).dropLast(1) + ""","files":[{"id":"$FILE","name":"image.png","mimeType":"image/png","size":1}]}""" + val app = opened(transport, listOf(fileRow)) + val message = app.groupConversation!!.messages.single() + app.loadGroupAttachmentImage("$G1:1", 0) + assertEquals("$BASE/$G1/files/$FILE", transport.requests.last().pathWithQuery) + assertArrayEquals(byteArrayOf(9), app.groupAttachmentImageBytes(message, 0)) + } + + @Test + fun aPartialSnapshotDeletesEveryGroupReferenceToTheSameFile() = runTest { + val transport = GroupTransport().apply { bytes = byteArrayOf(9) } + val files = ""","files":[{"id":"$FILE","name":"image.png","mimeType":"image/png","size":1}]}""" + val app = opened(transport, listOf(row(1).dropLast(1) + files, row(2).dropLast(1) + files)) app.loadGroupAttachmentImage("$G1:1", 0) - assertEquals("/v1/group-chats/$G1/attachments/11111111-1111-4111-8111-111111111111%3A1/0", transport.requests.last().pathWithQuery) - assertArrayEquals(byteArrayOf(9), app.groupAttachmentImageBytes(Message(entryId = "$G1:1"), 0)) + assertArrayEquals(byteArrayOf(9), app.groupAttachmentImageBytes(app.groupConversation!!.messages.first(), 0)) + val deleted = row(2).dropLast(1) + ""","files":[{"id":"$FILE","deleted":true}]}""" + nextStream(app, transport, snapshotJson(listOf(deleted))) + val messages = app.groupConversation!!.messages + assertEquals(2, messages.size) + assertTrue(messages.all { it.attachments!!.single().deleted }) + assertTrue(app.attachmentBytes.isEmpty()) + assertNull(app.groupAttachmentImageBytes(messages.first(), 0)) + val count = transport.requests.size + app.loadGroupAttachmentImage("$G1:1", 0) + assertEquals(count, transport.requests.size) } @Test @@ -744,10 +769,6 @@ class GroupChatTests { ) assertEquals(mapOf("e1" to listOf("Ada 👍", "👍")), reactions) - val sources = groupSourcesOf(Message(sources = listOf(MessageSource("https://example.com/a/", "A"), MessageSource("ftp://x", "X")))) - assertEquals(mapOf("example.com/a" to "A"), sources) - assertNull(groupSourcesOf(Message())) - assertEquals("You", groupReplyLabel(Message(role = "user"))) assertEquals("Ada", groupReplyLabel(Message(role = "assistant", origin = MessageOrigin("bot", "Ada")))) assertEquals("a bot", groupReplyLabel(Message(role = "assistant"))) diff --git a/app/src/test/java/dev/crumble/android/PushContractTests.kt b/app/src/test/java/dev/crumble/android/PushContractTests.kt index 1084c2f..6abf21e 100644 --- a/app/src/test/java/dev/crumble/android/PushContractTests.kt +++ b/app/src/test/java/dev/crumble/android/PushContractTests.kt @@ -2,7 +2,7 @@ package dev.crumble.android import dev.crumble.android.model.ActivityEvent import dev.crumble.android.network.APIClient -import dev.crumble.android.push.PushPresence +import dev.crumble.android.push.ChatAttentionChat import dev.crumble.android.push.PushRegistration import dev.crumble.android.push.parsePushReplyData import dev.crumble.android.push.parsePushReplyPayload @@ -31,11 +31,11 @@ class PushContractTests { } @Test - fun pushApiUsesEscapedInstallationIdAndExplicitPresenceNull() = runTest { + fun pushApiUsesEscapedInstallationIdAndIndependentAttention() = runTest { val (client, stub) = StubTransport.client(token = "token") { request -> when (request.method) { "GET" -> 200 to """{"serverId":"s1","transports":{"apns":false,"fcm":true}}""" - "PUT" -> if (request.pathWithQuery.endsWith("/presence")) 204 to "" else 200 to """{"serverId":"s1","remoteDelivery":true}""" + "PUT" -> if (request.pathWithQuery.startsWith("/v1/chat-attention/")) 204 to "" else 200 to """{"serverId":"s1","remoteDelivery":true}""" "DELETE" -> 204 to "" else -> 500 to "" } @@ -47,11 +47,14 @@ class PushContractTests { assertEquals("/v1/push/devices/installation%2Fid", registration.pathWithQuery) assertEquals("Bearer token", registration.headers["Authorization"]) assertTrue(String(registration.body!!, StandardCharsets.UTF_8).contains("\"platform\":\"android\"")) - client.updatePushPresence("installation/id", PushPresence(active = false, agentId = null)) + client.putChatAttentionView("installation/id", null) + assertEquals("/v1/chat-attention/views/installation%2Fid", stub.requests[2].pathWithQuery) val presenceBody = String(stub.requests[2].body!!, StandardCharsets.UTF_8) - assertTrue(presenceBody.contains("\"agentId\":null")) + assertTrue(presenceBody.contains("\"chat\":null")) client.unregisterPushDevice("installation/id") assertEquals("DELETE", stub.requests[3].method) + client.putChatAttentionView("view", ChatAttentionChat("group", "g1")) + assertEquals("""{"chat":{"kind":"group","id":"g1"}}""", String(stub.requests[4].body!!, StandardCharsets.UTF_8)) } @Test(expected = IllegalArgumentException::class) diff --git a/app/src/test/java/dev/crumble/android/RecurrenceTests.kt b/app/src/test/java/dev/crumble/android/RecurrenceTests.kt index eece0ce..30f6874 100644 --- a/app/src/test/java/dev/crumble/android/RecurrenceTests.kt +++ b/app/src/test/java/dev/crumble/android/RecurrenceTests.kt @@ -1,16 +1,13 @@ package dev.crumble.android -import dev.crumble.android.model.NextRun import dev.crumble.android.model.Recurrence import dev.crumble.android.model.TaskDraft import dev.crumble.android.model.TaskWhen import dev.crumble.android.model.choice import dev.crumble.android.model.choosing import dev.crumble.android.model.cronOf -import dev.crumble.android.model.humanRun import dev.crumble.android.model.inTimezone import dev.crumble.android.model.minuteChoices -import dev.crumble.android.model.nextRunOf import dev.crumble.android.model.recurrenceOf import dev.crumble.android.model.runningAt import dev.crumble.android.model.timezoneChoices @@ -105,33 +102,4 @@ class RecurrenceTests { assertTrue("Mars/Base" in timezoneChoices("", "Mars/Base", zones)) } - @Test - fun runsReadRelativeToTheTasksZone() { - val zone = ZoneId.of("UTC") - fun at(text: String) = humanRun(Instant.parse(text), zone, now, Locale.UK) - assertEquals("today at 12:00", at("2026-11-05T12:00:00Z")) - assertEquals("tomorrow at 09:00", at("2026-11-06T09:00:00Z")) - assertEquals("Monday at 09:00", at("2026-11-09T09:00:00Z")) - assertEquals("Mon, Nov 16 at 09:00", humanRun(Instant.parse("2026-11-16T09:00:00Z"), zone, now, Locale.US).replace(' ', ' ').replace(" AM", "").replace("9:00", "09:00")) - } - - @Test - fun theDayBoundaryIsTheTasksNotTheDevices() { - assertEquals("tomorrow at 00:30", humanRun(Instant.parse("2026-11-05T15:30:00Z"), ZoneId.of("Asia/Tokyo"), now, Locale.UK)) - } - - @Test - fun previewMatchesTheEditorStates() { - val repeating = draft().copy(repeats = true, cron = "0 9 * * *") - assertEquals(NextRun.At("Next run", "tomorrow at 09:00", "UTC"), nextRunOf(repeating, now, Locale.UK)) - assertEquals(NextRun.Never, nextRunOf(repeating.copy(cron = "0 0 31 2 *"), now)) - assertEquals(NextRun.Never, nextRunOf(repeating.copy(cron = "nonsense"), now)) - assertEquals(NextRun.Never, nextRunOf(repeating.copy(cron = ""), now)) - assertEquals(NextRun.Never, nextRunOf(repeating.copy(timezone = "Not/AZone"), now)) - assertEquals(NextRun.Unknown, nextRunOf(repeating.copy(cron = "H * * * *"), now)) - - val once = draft().copy(runDate = Instant.parse("2026-11-05T12:00:00Z")) - assertEquals(NextRun.At("Runs", "today at 12:00", "UTC"), nextRunOf(once, now, Locale.UK)) - assertEquals(NextRun.Passed, nextRunOf(once.copy(runDate = now.minusSeconds(60)), now)) - } } diff --git a/app/src/test/java/dev/crumble/android/ReplyAttentionTests.kt b/app/src/test/java/dev/crumble/android/ReplyAttentionTests.kt new file mode 100644 index 0000000..16b526c --- /dev/null +++ b/app/src/test/java/dev/crumble/android/ReplyAttentionTests.kt @@ -0,0 +1,157 @@ +package dev.crumble.android + +import androidx.compose.ui.geometry.Rect +import androidx.compose.runtime.snapshotFlow +import androidx.compose.runtime.snapshots.Snapshot +import dev.crumble.android.generated.CredentialRequest +import dev.crumble.android.generated.Credentials +import dev.crumble.android.model.DisplayedReplySurface +import dev.crumble.android.model.SecretRequestRef +import dev.crumble.android.model.Route +import dev.crumble.android.model.attentionEventIDs +import dev.crumble.android.model.credentialReadKey +import dev.crumble.android.model.replyCardReady +import dev.crumble.android.network.domain +import dev.crumble.android.ui.replySurfaceVisible +import dev.crumble.android.model.ActivityEvent +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.ChatSnapshot +import dev.crumble.android.model.CrumbleJson +import dev.crumble.android.model.Message +import dev.crumble.android.network.APIClient +import dev.crumble.android.network.HttpRequestData +import dev.crumble.android.network.HttpResponseData +import dev.crumble.android.network.HttpStreamResponse +import dev.crumble.android.network.HttpTransport +import java.io.ByteArrayInputStream +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.encodeToJsonElement +import kotlinx.serialization.json.jsonObject +import org.junit.Assert.* +import org.junit.Test + +@OptIn(ExperimentalCoroutinesApi::class) +class ReplyAttentionTests { + @Test + fun foregroundChangesReevaluateVisibleReplySurfaces() = runTest { + val model = AppModel(scope = backgroundScope, loadCredentials = false) + val observed = mutableListOf() + backgroundScope.launch { snapshotFlow { model.appActive }.collect { observed.add(it) } } + runCurrent() + model.appActive = false + Snapshot.sendApplyNotifications() + runCurrent() + model.appActive = true + Snapshot.sendApplyNotifications() + runCurrent() + assertEquals(listOf(true, false, true), observed) + } + + @Test + fun historyReferencesReachTheDomainMessage() = runTest { + val refs = """[{"eventId":"reply-event","surface":{"kind":"text"}}]""" + val (api, _) = StubTransport.client { + 200 to """{"messages":[{"id":"m1","entryId":"e1","role":"assistant","content":"Answer","replyReferences":$refs}],"hasMore":false,"oldestEntryId":null}""" + } + val message = api.chatHistory("a1", "", 5).messages!!.single() + assertEquals(CrumbleJson.parseToJsonElement(refs), CrumbleJson.encodeToJsonElement(message).jsonObject["replyReferences"]) + val event = CrumbleJson.decodeFromString(snapshotFixture(ChatSnapshot(agentId = "a1", messages = listOf(message)))).domain() + assertEquals(message.replyReferences, event.messages!!.single().replyReferences) + } + + @Test + fun onlyExactSurfaceIdentityAndVisibleReadyContentCounts() { + val message = CrumbleJson.decodeFromString("""{"id":"m1","role":"assistant","content":"Answer","replyReferences":[{"eventId":"text","surface":{"kind":"text"}},{"eventId":"tool","surface":{"kind":"tool-card","toolCallId":"t1"}},{"eventId":"held","surface":{"kind":"held-action","actionId":"a1"}}]}""") + assertEquals(listOf("text"), message.attentionEventIDs(DisplayedReplySurface.Text)) + assertEquals(listOf("tool"), message.attentionEventIDs(DisplayedReplySurface.ToolCard("t1"))) + assertEquals(listOf("held"), message.attentionEventIDs(DisplayedReplySurface.HeldAction("a1"))) + assertTrue(message.attentionEventIDs(DisplayedReplySurface.ToolCard("another")).isEmpty()) + assertTrue(message.attentionEventIDs(DisplayedReplySurface.HeldAction("another")).isEmpty()) + val viewport = Rect(0f, 100f, 300f, 400f) + val content = Rect(10f, 150f, 200f, 200f) + assertTrue(replySurfaceVisible(true, content, viewport)) + assertFalse(replySurfaceVisible(false, content, viewport)) + assertFalse(replySurfaceVisible(true, Rect.Zero, viewport)) + assertFalse(replySurfaceVisible(true, content, Rect.Zero)) + assertFalse(replySurfaceVisible(true, Rect(10f, 0f, 200f, 100f), viewport)) + assertFalse(replySurfaceVisible(true, Rect(10f, 400f, 200f, 500f), viewport)) + } + + @Test + fun secretCardsRequireWaitingOrFreshConfirmedContentNotPlaceholders() = runTest { + val model = AppModel(scope = backgroundScope, loadCredentials = false) + model.selectAgent("a1") + val ref = SecretRequestRef("TOKEN", listOf("example.test"), "now") + val message = Message(id = "m", credentialRequest = ref, toolCallId = "t1") + assertFalse(model.replyCardReady(message)) + model.decisionsFailed = true + assertFalse(model.replyCardReady(message)) + model.decisionsFailed = false + model.botCredentials = mapOf("a1" to Credentials(emptyList(), emptyList())) + assertFalse(model.replyCardReady(message)) + model.freshSecretRequests = setOf(credentialReadKey(ref)) + assertTrue(model.replyCardReady(message)) + model.freshSecretRequests = emptySet() + model.botCredentials = mapOf("a1" to Credentials(emptyList(), listOf(CredentialRequest("TOKEN", listOf("example.test"), "Needed", "now")))) + assertTrue(model.replyCardReady(message)) + } + + @Test + fun activeReplyEventRefreshesReferencesWithoutReplacingNewerSnapshotsOrNavigation() = runTest { + val requests = mutableListOf() + var held: CompletableDeferred? = null + var response = ChatSnapshot(agentId = "a1") + val transport = object : HttpTransport { + override suspend fun execute(request: HttpRequestData): HttpResponseData { + requests.add(request) + val body = when { + request.pathWithQuery.contains("/chat") -> { + val captured = snapshotFixture(response) + held?.await() + captured + } + request.pathWithQuery == "/v1/agents" -> "[${agentFixture("a1")}]" + else -> "[]" + } + return HttpResponseData(200, body.toByteArray()) + } + override suspend fun openStream(request: HttpRequestData) = HttpStreamResponse(503, ByteArrayInputStream(byteArrayOf())) + } + val api = APIClient("https://crumble.test", "owner", transport) + val app = AppModel(client = api, scope = backgroundScope) + app.selectAgent("a1") + runCurrent() + app.appActive = true + val gate = CompletableDeferred() + held = gate + response = ChatSnapshot(agentId = "a1", messages = listOf(Message(id = "answer", entryId = "e1", role = "assistant", content = JsonPrimitive("Old")))) + requests.clear() + app.handleActivity(ActivityEvent(type = "reply", agentId = "a1", eventId = "reply-event")) + runCurrent() + assertEquals(1, requests.count { it.pathWithQuery.contains("/chat") }) + app.applySnapshot(ChatSnapshot(agentId = "a1", messages = listOf(Message(id = "answer", entryId = "e1", role = "assistant", content = JsonPrimitive("New"))))) + gate.complete(Unit) + runCurrent() + assertEquals("New", app.messages.single().text) + + val navigationGate = CompletableDeferred() + held = navigationGate + app.draft = "Keep this draft" + app.handleActivity(ActivityEvent(type = "reply", agentId = "a1", eventId = "later-event")) + runCurrent() + app.route = Route.Tasks + app.selectAgent("a1") + runCurrent() + navigationGate.complete(Unit) + runCurrent() + assertEquals("New", app.messages.single().text) + assertEquals("Keep this draft", app.draft) + } +} diff --git a/app/src/test/java/dev/crumble/android/SecretsTests.kt b/app/src/test/java/dev/crumble/android/SecretsTests.kt index 5f9192d..64d116f 100644 --- a/app/src/test/java/dev/crumble/android/SecretsTests.kt +++ b/app/src/test/java/dev/crumble/android/SecretsTests.kt @@ -250,7 +250,7 @@ class SecretsTests { fun transcriptResultsBecomeRequestCards() { fun message(tool: String, isError: Boolean = false) = CrumbleJson.decodeFromString( TranscriptMessage.serializer(), - """{"id":"m","entryId":"e","role":"toolResult","content":"","toolName":"$tool","isError":$isError,"toolDetails":{"name":"ACME","hosts":["a.io"],"requestedAt":"t1"}}""", + """{"id":"m","entryId":"e","role":"toolResult","content":"","replyReferences":[],"toolName":"$tool","isError":$isError,"toolDetails":{"name":"ACME","hosts":["a.io"],"requestedAt":"t1"}}""", ).domain() assertEquals(SecretRequestRef("ACME", listOf("a.io"), "t1"), message("request_credential").credentialRequest) assertEquals(SecretRequestRef("ACME", listOf("a.io"), "t1"), message("request_login").loginRequest) diff --git a/contract/assets/chat-snapshot.schema.json b/contract/assets/chat-snapshot.schema.json index 16275c4..abf4021 100644 --- a/contract/assets/chat-snapshot.schema.json +++ b/contract/assets/chat-snapshot.schema.json @@ -22,7 +22,12 @@ "content": { "type": "string" }, - "blocks": {}, + "blocks": { + "type": "array", + "items": { + "$ref": "#/$defs/TranscriptBlock" + } + }, "stopReason": { "type": "string" }, @@ -38,6 +43,76 @@ "replyPreview": { "type": "string" }, + "replyReferences": { + "type": "array", + "items": { + "type": "object", + "properties": { + "eventId": { + "type": "string", + "minLength": 1 + }, + "surface": { + "oneOf": [ + { + "type": "object", + "properties": { + "kind": { + "type": "string", + "const": "text" + } + }, + "required": [ + "kind" + ], + "additionalProperties": true + }, + { + "type": "object", + "properties": { + "kind": { + "type": "string", + "const": "tool-card" + }, + "toolCallId": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "kind", + "toolCallId" + ], + "additionalProperties": true + }, + { + "type": "object", + "properties": { + "kind": { + "type": "string", + "const": "held-action" + }, + "actionId": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "kind", + "actionId" + ], + "additionalProperties": true + } + ] + } + }, + "required": [ + "eventId", + "surface" + ], + "additionalProperties": true + } + }, "origin": { "type": "object", "properties": { @@ -168,35 +243,52 @@ ], "additionalProperties": true }, - "attachments": { + "files": { "type": "array", "items": { - "type": "object", - "properties": { - "name": { - "type": "string" - }, - "mimeType": { - "type": "string" - }, - "size": { - "type": "number" + "anyOf": [ + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "mimeType": { + "type": "string" + }, + "size": { + "type": "number" + } + }, + "required": [ + "id", + "name", + "mimeType", + "size" + ], + "additionalProperties": true }, - "kind": { - "type": "string", - "enum": [ - "image", - "text" - ] + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "deleted": { + "type": "boolean", + "const": true + } + }, + "required": [ + "id", + "deleted" + ], + "additionalProperties": true } - }, - "required": [ - "name", - "mimeType", - "size", - "kind" - ], - "additionalProperties": true + ] } }, "toolCallId": { @@ -209,6 +301,9 @@ "type": "boolean" }, "toolDetails": {}, + "presentation": { + "$ref": "#/$defs/MessagePresentation" + }, "sources": { "type": "array", "items": { @@ -233,7 +328,8 @@ "id", "entryId", "role", - "content" + "content", + "replyReferences" ], "additionalProperties": true } @@ -297,6 +393,19 @@ "failed" ] }, + "working": { + "type": "string", + "enum": [ + "idle", + "thinking", + "writing", + "searching", + "remembering", + "tinkering", + "struggling", + "failed" + ] + }, "updatedAt": { "type": "number" }, @@ -316,8 +425,146 @@ "conversation", "partial", "status", + "working", "updatedAt", "error" ], - "additionalProperties": true + "additionalProperties": true, + "$defs": { + "TranscriptBlock": { + "oneOf": [ + { + "$ref": "#/$defs/TranscriptTextBlock" + }, + { + "$ref": "#/$defs/TranscriptThinkingBlock" + }, + { + "$ref": "#/$defs/TranscriptImageBlock" + }, + { + "$ref": "#/$defs/TranscriptToolCallBlock" + } + ] + }, + "TranscriptTextBlock": { + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "text" + }, + "text": { + "type": "string" + } + }, + "required": [ + "type", + "text" + ], + "additionalProperties": true + }, + "TranscriptThinkingBlock": { + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "thinking" + }, + "thinking": { + "type": "string" + }, + "redacted": { + "type": "boolean" + } + }, + "required": [ + "type", + "thinking" + ], + "additionalProperties": true + }, + "TranscriptImageBlock": { + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "image" + }, + "mimeType": { + "type": "string" + } + }, + "required": [ + "type", + "mimeType" + ], + "additionalProperties": true + }, + "TranscriptToolCallBlock": { + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "toolCall" + }, + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "arguments": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "type", + "id", + "name", + "arguments" + ], + "additionalProperties": true + }, + "MessagePresentation": { + "type": "object", + "properties": { + "text": { + "type": "string" + }, + "citations": { + "type": "array", + "items": { + "$ref": "#/$defs/Citation" + } + } + }, + "required": [ + "text", + "citations" + ], + "additionalProperties": true + }, + "Citation": { + "type": "object", + "properties": { + "href": { + "type": "string" + }, + "title": { + "type": "string" + }, + "site": { + "type": "string" + } + }, + "required": [ + "href", + "title", + "site" + ], + "additionalProperties": true + } + } } diff --git a/contract/assets/group-chat-snapshot.schema.json b/contract/assets/group-chat-snapshot.schema.json new file mode 100644 index 0000000..d099d68 --- /dev/null +++ b/contract/assets/group-chat-snapshot.schema.json @@ -0,0 +1,576 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "messages": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "entryId": { + "type": "string" + }, + "requestId": { + "type": "string" + }, + "role": { + "type": "string" + }, + "content": { + "type": "string" + }, + "blocks": { + "type": "array", + "items": { + "$ref": "#/$defs/TranscriptBlock" + } + }, + "stopReason": { + "type": "string" + }, + "timestamp": { + "type": "number" + }, + "kind": { + "type": "string" + }, + "replyTo": { + "type": "string" + }, + "replyPreview": { + "type": "string" + }, + "replyReferences": { + "type": "array", + "items": { + "type": "object", + "properties": { + "eventId": { + "type": "string", + "minLength": 1 + }, + "surface": { + "oneOf": [ + { + "type": "object", + "properties": { + "kind": { + "type": "string", + "const": "text" + } + }, + "required": [ + "kind" + ], + "additionalProperties": true + }, + { + "type": "object", + "properties": { + "kind": { + "type": "string", + "const": "tool-card" + }, + "toolCallId": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "kind", + "toolCallId" + ], + "additionalProperties": true + }, + { + "type": "object", + "properties": { + "kind": { + "type": "string", + "const": "held-action" + }, + "actionId": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "kind", + "actionId" + ], + "additionalProperties": true + } + ] + } + }, + "required": [ + "eventId", + "surface" + ], + "additionalProperties": true + } + }, + "origin": { + "type": "object", + "properties": { + "kind": { + "type": "string" + }, + "name": { + "type": "string" + }, + "agentId": { + "type": "string" + }, + "via": { + "type": "string" + }, + "source": { + "type": "string" + } + }, + "required": [ + "kind" + ], + "additionalProperties": true + }, + "communication": { + "type": "object", + "properties": { + "executionId": { + "type": "string" + }, + "fromAgentId": { + "type": "string" + }, + "fromName": { + "type": "string" + }, + "toAgentId": { + "type": "string" + }, + "toName": { + "type": "string" + }, + "status": { + "type": "string", + "enum": [ + "sent", + "done", + "failed", + "cancelled" + ] + } + }, + "required": [ + "executionId", + "fromAgentId", + "fromName", + "toAgentId", + "toName", + "status" + ], + "additionalProperties": true + }, + "jobQuestion": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "kind": { + "type": "string" + }, + "job": { + "type": "string" + }, + "options": { + "type": "array", + "items": { + "type": "string" + } + }, + "multiple": { + "type": "boolean" + } + }, + "required": [ + "id", + "kind", + "job" + ], + "additionalProperties": true + }, + "heldAction": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "job": { + "type": "string" + } + }, + "required": [ + "id", + "job" + ], + "additionalProperties": true + }, + "call": { + "type": "object", + "properties": { + "callId": { + "type": "string" + }, + "direction": { + "type": "string", + "enum": [ + "inbound", + "outbound" + ] + }, + "callee": { + "type": "string" + } + }, + "required": [ + "callId", + "direction" + ], + "additionalProperties": true + }, + "files": { + "type": "array", + "items": { + "anyOf": [ + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "mimeType": { + "type": "string" + }, + "size": { + "type": "number" + } + }, + "required": [ + "id", + "name", + "mimeType", + "size" + ], + "additionalProperties": true + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "deleted": { + "type": "boolean", + "const": true + } + }, + "required": [ + "id", + "deleted" + ], + "additionalProperties": true + } + ] + } + }, + "toolCallId": { + "type": "string" + }, + "toolName": { + "type": "string" + }, + "isError": { + "type": "boolean" + }, + "toolDetails": {}, + "presentation": { + "$ref": "#/$defs/MessagePresentation" + }, + "sources": { + "type": "array", + "items": { + "type": "object", + "properties": { + "url": { + "type": "string" + }, + "title": { + "type": "string" + } + }, + "required": [ + "url", + "title" + ], + "additionalProperties": true + } + } + }, + "required": [ + "id", + "entryId", + "role", + "content", + "replyReferences" + ], + "additionalProperties": true + } + }, + "hasMore": { + "type": "boolean" + }, + "oldestEntryId": { + "type": [ + "string", + "null" + ] + }, + "groupChat": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "memberIds": { + "type": "array", + "items": { + "type": "string" + } + }, + "createdAt": { + "type": "string" + }, + "updatedAt": { + "type": "string" + } + }, + "required": [ + "id", + "name", + "memberIds", + "createdAt", + "updatedAt" + ], + "additionalProperties": true + }, + "activity": { + "type": "object", + "properties": { + "paused": { + "type": "boolean" + }, + "botTurns": { + "type": "number" + }, + "members": { + "type": "array", + "items": { + "type": "object", + "properties": { + "agentId": { + "type": "string" + }, + "status": { + "type": "string", + "enum": [ + "idle", + "queued", + "running", + "disabled" + ] + }, + "error": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "agentId", + "status", + "error" + ], + "additionalProperties": true + } + } + }, + "required": [ + "paused", + "botTurns", + "members" + ], + "additionalProperties": true + }, + "updatedAt": { + "type": "number" + } + }, + "required": [ + "messages", + "hasMore", + "oldestEntryId", + "groupChat", + "activity", + "updatedAt" + ], + "additionalProperties": true, + "$defs": { + "TranscriptBlock": { + "oneOf": [ + { + "$ref": "#/$defs/TranscriptTextBlock" + }, + { + "$ref": "#/$defs/TranscriptThinkingBlock" + }, + { + "$ref": "#/$defs/TranscriptImageBlock" + }, + { + "$ref": "#/$defs/TranscriptToolCallBlock" + } + ] + }, + "TranscriptTextBlock": { + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "text" + }, + "text": { + "type": "string" + } + }, + "required": [ + "type", + "text" + ], + "additionalProperties": true + }, + "TranscriptThinkingBlock": { + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "thinking" + }, + "thinking": { + "type": "string" + }, + "redacted": { + "type": "boolean" + } + }, + "required": [ + "type", + "thinking" + ], + "additionalProperties": true + }, + "TranscriptImageBlock": { + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "image" + }, + "mimeType": { + "type": "string" + } + }, + "required": [ + "type", + "mimeType" + ], + "additionalProperties": true + }, + "TranscriptToolCallBlock": { + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "toolCall" + }, + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "arguments": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "type", + "id", + "name", + "arguments" + ], + "additionalProperties": true + }, + "MessagePresentation": { + "type": "object", + "properties": { + "text": { + "type": "string" + }, + "citations": { + "type": "array", + "items": { + "$ref": "#/$defs/Citation" + } + } + }, + "required": [ + "text", + "citations" + ], + "additionalProperties": true + }, + "Citation": { + "type": "object", + "properties": { + "href": { + "type": "string" + }, + "title": { + "type": "string" + }, + "site": { + "type": "string" + } + }, + "required": [ + "href", + "title", + "site" + ], + "additionalProperties": true + } + } +} diff --git a/contract/assets/openapi.json b/contract/assets/openapi.json index 34532a2..e11d319 100644 --- a/contract/assets/openapi.json +++ b/contract/assets/openapi.json @@ -1308,6 +1308,19 @@ "failed" ] }, + "working": { + "type": "string", + "enum": [ + "idle", + "thinking", + "writing", + "searching", + "remembering", + "tinkering", + "struggling", + "failed" + ] + }, "updatedAt": { "type": "number" }, @@ -1324,6 +1337,7 @@ "conversation", "partial", "status", + "working", "updatedAt", "error" ] @@ -1349,7 +1363,10 @@ "type": "string" }, "blocks": { - "description": "Provider content blocks, with inline image bytes removed." + "type": "array", + "items": { + "$ref": "#/components/schemas/TranscriptBlock" + } }, "stopReason": { "type": "string" @@ -1367,6 +1384,78 @@ "replyPreview": { "type": "string" }, + "replyReferences": { + "type": "array", + "items": { + "type": "object", + "properties": { + "eventId": { + "type": "string", + "minLength": 1 + }, + "surface": { + "oneOf": [ + { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "text" + ] + } + }, + "required": [ + "kind" + ] + }, + { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "tool-card" + ] + }, + "toolCallId": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "kind", + "toolCallId" + ] + }, + { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "held-action" + ] + }, + "actionId": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "kind", + "actionId" + ] + } + ] + } + }, + "required": [ + "eventId", + "surface" + ] + } + }, "origin": { "$ref": "#/components/schemas/MessageOrigin" }, @@ -1443,10 +1532,52 @@ ], "description": "On a `call-started` or `call-ended` event: the call." }, - "attachments": { + "files": { "type": "array", "items": { - "$ref": "#/components/schemas/AttachmentInfo" + "anyOf": [ + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "mimeType": { + "type": "string" + }, + "size": { + "type": "number" + } + }, + "required": [ + "id", + "name", + "mimeType", + "size" + ] + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "deleted": { + "type": "boolean", + "enum": [ + true + ] + } + }, + "required": [ + "id", + "deleted" + ] + } + ] } }, "toolCallId": { @@ -1461,6 +1592,9 @@ "toolDetails": { "description": "Provider-specific tool details, including nested code-mode calls. A successful `desktop_screenshot` result has `{ mimeType, size }`; read its image from `GET /v1/agents/{id}/attachments/{entryId}/0`." }, + "presentation": { + "$ref": "#/components/schemas/MessagePresentation" + }, "sources": { "type": "array", "items": { @@ -1485,7 +1619,117 @@ "id", "entryId", "role", - "content" + "content", + "replyReferences" + ] + }, + "TranscriptBlock": { + "oneOf": [ + { + "$ref": "#/components/schemas/TranscriptTextBlock" + }, + { + "$ref": "#/components/schemas/TranscriptThinkingBlock" + }, + { + "$ref": "#/components/schemas/TranscriptImageBlock" + }, + { + "$ref": "#/components/schemas/TranscriptToolCallBlock" + } + ], + "discriminator": { + "propertyName": "type", + "mapping": { + "text": "#/components/schemas/TranscriptTextBlock", + "thinking": "#/components/schemas/TranscriptThinkingBlock", + "image": "#/components/schemas/TranscriptImageBlock", + "toolCall": "#/components/schemas/TranscriptToolCallBlock" + } + } + }, + "TranscriptTextBlock": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "text" + ] + }, + "text": { + "type": "string" + } + }, + "required": [ + "type", + "text" + ] + }, + "TranscriptThinkingBlock": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "thinking" + ] + }, + "thinking": { + "type": "string" + }, + "redacted": { + "type": "boolean" + } + }, + "required": [ + "type", + "thinking" + ] + }, + "TranscriptImageBlock": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "image" + ] + }, + "mimeType": { + "type": "string" + } + }, + "required": [ + "type", + "mimeType" + ] + }, + "TranscriptToolCallBlock": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "toolCall" + ] + }, + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "arguments": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "type", + "id", + "name", + "arguments" ] }, "MessageOrigin": { @@ -1551,31 +1795,41 @@ "status" ] }, - "AttachmentInfo": { + "MessagePresentation": { "type": "object", "properties": { - "name": { + "text": { "type": "string" }, - "mimeType": { + "citations": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Citation" + } + } + }, + "required": [ + "text", + "citations" + ] + }, + "Citation": { + "type": "object", + "properties": { + "href": { "type": "string" }, - "size": { - "type": "number" + "title": { + "type": "string" }, - "kind": { - "type": "string", - "enum": [ - "image", - "text" - ] + "site": { + "type": "string" } }, "required": [ - "name", - "mimeType", - "size", - "kind" + "href", + "title", + "site" ] }, "Conversation": { @@ -1721,39 +1975,168 @@ "status" ] }, - "DesktopJobs": { - "type": "object", - "properties": { - "jobs": { - "type": "array", - "items": { - "$ref": "#/components/schemas/DesktopJob" + "JobHistoryPage": { + "allOf": [ + { + "$ref": "#/components/schemas/TranscriptPage" + }, + { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/JobHistoryItem" + } + } }, - "description": "Oldest job first." + "required": [ + "items" + ] } - }, - "required": [ - "jobs" ] }, - "DesktopJob": { - "type": "object", - "properties": { - "name": { - "type": "string" + "JobHistoryItem": { + "oneOf": [ + { + "$ref": "#/components/schemas/JobTaskItem" }, - "conversationId": { - "type": "string" + { + "$ref": "#/components/schemas/JobReplyItem" }, - "status": { + { + "$ref": "#/components/schemas/JobStepItem" + } + ], + "discriminator": { + "propertyName": "kind", + "mapping": { + "task": "#/components/schemas/JobTaskItem", + "reply": "#/components/schemas/JobReplyItem", + "step": "#/components/schemas/JobStepItem" + } + } + }, + "JobTaskItem": { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": [ - "working", - "idle" + "task" ] }, - "model": { - "type": "object", + "id": { + "type": "string" + }, + "text": { + "type": "string" + } + }, + "required": [ + "kind", + "id", + "text" + ] + }, + "JobReplyItem": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "reply" + ] + }, + "id": { + "type": "string" + }, + "text": { + "type": "string" + } + }, + "required": [ + "kind", + "id", + "text" + ] + }, + "JobStepItem": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "step" + ] + }, + "id": { + "type": "string" + }, + "tool": { + "type": "string" + }, + "label": { + "type": "string" + }, + "icon": { + "type": "string", + "enum": [ + "terminal", + "file", + "pencil", + "pointer", + "tool" + ] + }, + "subject": { + "type": "string" + }, + "result": { + "$ref": "#/components/schemas/TranscriptMessage" + } + }, + "required": [ + "kind", + "id", + "tool", + "label", + "icon" + ] + }, + "DesktopJobs": { + "type": "object", + "properties": { + "jobs": { + "type": "array", + "items": { + "$ref": "#/components/schemas/DesktopJob" + }, + "description": "Oldest job first." + } + }, + "required": [ + "jobs" + ] + }, + "DesktopJob": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "conversationId": { + "type": "string" + }, + "status": { + "type": "string", + "enum": [ + "working", + "idle" + ] + }, + "model": { + "type": "object", "properties": { "provider": { "type": "string" @@ -1862,6 +2245,49 @@ "expiresAt" ] }, + "UploadFile": { + "type": "object", + "properties": { + "file": { + "$ref": "#/components/schemas/LibraryFile" + }, + "existed": { + "type": "boolean" + } + }, + "required": [ + "file", + "existed" + ] + }, + "LibraryFile": { + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "mimeType": { + "type": "string" + }, + "size": { + "type": "integer" + }, + "createdAt": { + "type": "string" + } + }, + "required": [ + "id", + "name", + "mimeType", + "size", + "createdAt" + ] + }, "Compaction": { "type": "object", "properties": { @@ -3534,6 +3960,15 @@ "null" ] }, + "nextRunLabel": { + "type": "string" + }, + "description": { + "type": "string" + }, + "timing": { + "type": "string" + }, "createdAt": { "type": "string" }, @@ -3559,10 +3994,39 @@ "eventSourceId", "enabled", "nextRunAt", + "nextRunLabel", + "description", + "timing", "createdAt", "createdByAgentId" ] }, + "SchedulePreview": { + "type": "object", + "properties": { + "description": { + "type": "string" + }, + "text": { + "type": "string" + }, + "isProblem": { + "type": "boolean" + }, + "nextRunAt": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "description", + "text", + "isProblem", + "nextRunAt" + ] + }, "ScheduleRun": { "type": "object", "properties": { @@ -3943,6 +4407,57 @@ "message" ] }, + "ReasoningPreview": { + "type": "object", + "properties": { + "options": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ReasoningOption" + } + }, + "effectiveLevel": { + "type": "string", + "enum": [ + "off", + "minimal", + "low", + "medium", + "high", + "xhigh", + "max" + ] + } + }, + "required": [ + "options", + "effectiveLevel" + ] + }, + "ReasoningOption": { + "type": "object", + "properties": { + "value": { + "type": "string", + "enum": [ + "off", + "minimal", + "low", + "medium", + "high", + "xhigh", + "max" + ] + }, + "label": { + "type": "string" + } + }, + "required": [ + "value", + "label" + ] + }, "Model": { "type": "object", "properties": { @@ -5008,9 +5523,9 @@ } } }, - "/v1/push/devices/{installationId}/presence": { + "/v1/chat-attention/views/{viewId}": { "put": { - "operationId": "putPushPresence", + "operationId": "putChatAttentionView", "security": [ { "BearerAuth": [] @@ -5023,10 +5538,10 @@ { "schema": { "type": "string", - "format": "uuid" + "minLength": 1 }, "required": true, - "name": "installationId", + "name": "viewId", "in": "path" } ], @@ -5037,20 +5552,32 @@ "schema": { "type": "object", "properties": { - "active": { - "type": "boolean" - }, - "agentId": { + "chat": { "type": [ - "string", + "object", "null" ], - "format": "uuid" + "properties": { + "kind": { + "type": "string", + "enum": [ + "bot", + "group" + ] + }, + "id": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "kind", + "id" + ] } }, "required": [ - "active", - "agentId" + "chat" ] } } @@ -5143,10 +5670,9 @@ } } }, - "/v1/admin/users": { - "get": { - "operationId": "listUsers", - "description": "Every account on the server, oldest first. Admins only.", + "/v1/chat-attention/seen": { + "post": { + "operationId": "postChatAttentionSeen", "security": [ { "BearerAuth": [] @@ -5155,29 +5681,173 @@ "SessionCookie": [] } ], - "responses": { - "200": { - "description": "Success", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "users": { - "type": "array", - "items": { - "$ref": "#/components/schemas/AdminUser" + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "chat": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "bot", + "group" + ] + }, + "id": { + "type": "string", + "minLength": 1 } - } + }, + "required": [ + "kind", + "id" + ] }, - "required": [ - "users" - ] - } + "eventIds": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "minItems": 1, + "maxItems": 100 + } + }, + "required": [ + "chat", + "eventIds" + ] } } - }, - "400": { + } + }, + "responses": { + "204": { + "description": "Success, no response body" + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/admin/users": { + "get": { + "operationId": "listUsers", + "description": "Every account on the server, oldest first. Admins only.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "users": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AdminUser" + } + } + }, + "required": [ + "users" + ] + } + } + } + }, + "400": { "description": "Invalid request or operation", "content": { "application/json": { @@ -7111,7 +7781,7 @@ "null" ], "maxLength": 64, - "description": "The name callers hear; null uses the bot's name." + "description": "The caller name sent to the telephone system; null uses the bot's name." }, "callsOwner": { "type": "boolean" @@ -7362,7 +8032,7 @@ "null" ], "maxLength": 64, - "description": "The name callers hear; null uses the bot's name." + "description": "The caller name sent to the telephone system; null uses the bot's name." }, "callsOwner": { "type": "boolean" @@ -7436,7 +8106,7 @@ "null" ], "maxLength": 64, - "description": "The name callers hear; null uses the bot's name." + "description": "The caller name sent to the telephone system; null uses the bot's name." }, "callsOwner": { "type": "boolean" @@ -12877,21 +13547,1024 @@ } } } - }, + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/Agent" + }, + { + "type": "null" + } + ] + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "delete": { + "operationId": "deleteAgent", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "204": { + "description": "Success, no response body" + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/duplicate": { + "post": { + "operationId": "duplicateAgent", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "201": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/Agent" + }, + { + "type": "null" + } + ] + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/chat": { + "get": { + "operationId": "getChat", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + }, + { + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 200 + }, + "required": false, + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ChatSnapshot" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/chat/history": { + "get": { + "operationId": "getChatHistory", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + }, + { + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 200 + }, + "required": false, + "name": "limit", + "in": "query" + }, + { + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "required": false, + "name": "before", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TranscriptPage" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/coding-jobs": { + "get": { + "operationId": "listCodingJobs", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CodingJobs" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/coding-jobs/{name}/answer": { + "post": { + "operationId": "answerCodingJob", + "description": "Answers the coding job's open question, which resumes the job. 409 when the job no longer waits on that question.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "name", + "in": "path" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "questionId": { + "type": "string", + "minLength": 1 + }, + "text": { + "type": "string", + "minLength": 1, + "maxLength": 32000 + } + }, + "required": [ + "questionId", + "text" + ] + } + } + } + }, + "responses": { + "204": { + "description": "Success, no response body" + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/coding-jobs/{name}/history": { + "get": { + "operationId": "getCodingJobHistory", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "name", + "in": "path" + }, + { + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 200 + }, + "required": false, + "name": "limit", + "in": "query" + }, + { + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "required": false, + "name": "before", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/JobHistoryPage" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/desktop-jobs": { + "get": { + "operationId": "listDesktopJobs", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { - "anyOf": [ - { - "$ref": "#/components/schemas/Agent" - }, - { - "type": "null" - } - ] + "$ref": "#/components/schemas/DesktopJobs" } } } @@ -12977,9 +14650,11 @@ } } } - }, - "delete": { - "operationId": "deleteAgent", + } + }, + "/v1/agents/{id}/desktop/control": { + "get": { + "operationId": "getDesktopControl", "security": [ { "BearerAuth": [] @@ -12999,8 +14674,15 @@ } ], "responses": { - "204": { - "description": "Success, no response body" + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DesktopControl" + } + } + } }, "400": { "description": "Invalid request or operation", @@ -13083,11 +14765,10 @@ } } } - } - }, - "/v1/agents/{id}/duplicate": { - "post": { - "operationId": "duplicateAgent", + }, + "put": { + "operationId": "putDesktopControl", + "description": "Take control of the bot desktop (holder owner) or hand it back (holder bot). 409 when the bot has no bot desktop.", "security": [ { "BearerAuth": [] @@ -13106,20 +14787,35 @@ "in": "path" } ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "holder": { + "type": "string", + "enum": [ + "bot", + "owner" + ] + } + }, + "required": [ + "holder" + ] + } + } + } + }, "responses": { - "201": { + "200": { "description": "Success", "content": { "application/json": { "schema": { - "anyOf": [ - { - "$ref": "#/components/schemas/Agent" - }, - { - "type": "null" - } - ] + "$ref": "#/components/schemas/DesktopControl" } } } @@ -13207,9 +14903,18 @@ } } }, - "/v1/agents/{id}/chat": { + "/v1/agents/{id}/desktop/events": { "get": { - "operationId": "getChat", + "operationId": "streamDesktopEvents", + "x-sse-events": { + "control": { + "$ref": "#/components/schemas/DesktopControl" + }, + "heartbeat": { + "$ref": "#/components/schemas/HeartbeatEvent" + } + }, + "description": "Server-sent events. A control event carries the DesktopControl JSON object in data, once on connect and on every change. Heartbeat events carry {} every 15 seconds. Authenticate with the Authorization header.", "security": [ { "BearerAuth": [] @@ -13226,25 +14931,15 @@ "required": true, "name": "id", "in": "path" - }, - { - "schema": { - "type": "integer", - "minimum": 1, - "maximum": 200 - }, - "required": false, - "name": "limit", - "in": "query" } ], "responses": { "200": { - "description": "Success", + "description": "SSE stream, not a JSON array", "content": { - "application/json": { + "text/event-stream": { "schema": { - "$ref": "#/components/schemas/ChatSnapshot" + "type": "string" } } } @@ -13332,9 +15027,9 @@ } } }, - "/v1/agents/{id}/chat/history": { + "/v1/agents/{id}/desktop/status": { "get": { - "operationId": "getChatHistory", + "operationId": "getDesktopStatus", "security": [ { "BearerAuth": [] @@ -13351,26 +15046,6 @@ "required": true, "name": "id", "in": "path" - }, - { - "schema": { - "type": "integer", - "minimum": 1, - "maximum": 200 - }, - "required": false, - "name": "limit", - "in": "query" - }, - { - "schema": { - "type": "string", - "minLength": 1, - "maxLength": 200 - }, - "required": false, - "name": "before", - "in": "query" } ], "responses": { @@ -13379,7 +15054,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/TranscriptPage" + "$ref": "#/components/schemas/DesktopStatus" } } } @@ -13467,9 +15142,10 @@ } } }, - "/v1/agents/{id}/coding-jobs": { - "get": { - "operationId": "listCodingJobs", + "/v1/agents/{id}/desktop/viewer": { + "post": { + "operationId": "createDesktopViewer", + "description": "Issue a single-use viewer link for the bot desktop. The page and its WebSocket live outside /v1 and need no Authorization header: the link is the credential. With passive=true the link is watch-only: it neither boots the bot's machine nor keeps it awake, and its connection ends when the machine stops. 409 when the bot has no bot desktop.", "security": [ { "BearerAuth": [] @@ -13486,15 +15162,23 @@ "required": true, "name": "id", "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": false, + "name": "passive", + "in": "query" } ], "responses": { - "200": { + "201": { "description": "Success", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CodingJobs" + "$ref": "#/components/schemas/DesktopViewer" } } } @@ -13582,10 +15266,9 @@ } } }, - "/v1/agents/{id}/coding-jobs/{name}/answer": { - "post": { - "operationId": "answerCodingJob", - "description": "Answers the coding job's open question, which resumes the job. 409 when the job no longer waits on that question.", + "/v1/agents/{id}/desktop-jobs/{name}/history": { + "get": { + "operationId": "getDesktopJobHistory", "security": [ { "BearerAuth": [] @@ -13610,36 +15293,38 @@ "required": true, "name": "name", "in": "path" + }, + { + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 200 + }, + "required": false, + "name": "limit", + "in": "query" + }, + { + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "required": false, + "name": "before", + "in": "query" } ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "questionId": { - "type": "string", - "minLength": 1 - }, - "text": { - "type": "string", - "minLength": 1, - "maxLength": 32000 - } - }, - "required": [ - "questionId", - "text" - ] + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/JobHistoryPage" + } } } - } - }, - "responses": { - "204": { - "description": "Success, no response body" }, "400": { "description": "Invalid request or operation", @@ -13724,9 +15409,9 @@ } } }, - "/v1/agents/{id}/coding-jobs/{name}/history": { - "get": { - "operationId": "getCodingJobHistory", + "/v1/agents/{id}/messages": { + "post": { + "operationId": "sendMessage", "security": [ { "BearerAuth": [] @@ -13743,43 +15428,59 @@ "required": true, "name": "id", "in": "path" - }, - { - "schema": { - "type": "string" - }, - "required": true, - "name": "name", - "in": "path" - }, - { - "schema": { - "type": "integer", - "minimum": 1, - "maximum": 200 - }, - "required": false, - "name": "limit", - "in": "query" - }, - { - "schema": { - "type": "string", - "minLength": 1, - "maxLength": 200 - }, - "required": false, - "name": "before", - "in": "query" } - ], + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "content": { + "type": "string", + "maxLength": 32000 + }, + "requestId": { + "type": "string", + "format": "uuid" + }, + "replyTo": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "files": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + }, + "maxItems": 8, + "default": [] + }, + "timezone": { + "type": "string", + "minLength": 1, + "maxLength": 100 + } + }, + "required": [ + "content", + "requestId" + ], + "additionalProperties": false + } + } + } + }, "responses": { - "200": { + "202": { "description": "Success", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/TranscriptPage" + "$ref": "#/components/schemas/Execution" } } } @@ -13867,9 +15568,9 @@ } } }, - "/v1/agents/{id}/desktop-jobs": { - "get": { - "operationId": "listDesktopJobs", + "/v1/agents/{id}/files": { + "post": { + "operationId": "uploadFile", "security": [ { "BearerAuth": [] @@ -13886,15 +15587,44 @@ "required": true, "name": "id", "in": "path" + }, + { + "schema": { + "type": "string", + "minLength": 1 + }, + "required": true, + "name": "x-file-name", + "in": "header" + }, + { + "schema": { + "type": "string", + "minLength": 1 + }, + "required": true, + "name": "content-type", + "in": "header" } ], + "requestBody": { + "required": true, + "content": { + "*/*": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + }, "responses": { - "200": { + "201": { "description": "Success", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/DesktopJobs" + "$ref": "#/components/schemas/UploadFile" } } } @@ -13980,11 +15710,9 @@ } } } - } - }, - "/v1/agents/{id}/desktop/control": { + }, "get": { - "operationId": "getDesktopControl", + "operationId": "listFiles", "security": [ { "BearerAuth": [] @@ -14001,6 +15729,26 @@ "required": true, "name": "id", "in": "path" + }, + { + "schema": { + "type": "string", + "format": "uuid" + }, + "required": false, + "name": "before", + "in": "query" + }, + { + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 200, + "default": 50 + }, + "required": false, + "name": "limit", + "in": "query" } ], "responses": { @@ -14009,7 +15757,10 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/DesktopControl" + "type": "array", + "items": { + "$ref": "#/components/schemas/LibraryFile" + } } } } @@ -14095,10 +15846,11 @@ } } } - }, - "put": { - "operationId": "putDesktopControl", - "description": "Take control of the bot desktop (holder owner) or hand it back (holder bot). 409 when the bot has no bot desktop.", + } + }, + "/v1/agents/{id}/files/{fileId}": { + "get": { + "operationId": "getFile", "security": [ { "BearerAuth": [] @@ -14115,37 +15867,25 @@ "required": true, "name": "id", "in": "path" + }, + { + "schema": { + "type": "string", + "format": "uuid" + }, + "required": true, + "name": "fileId", + "in": "path" } ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "holder": { - "type": "string", - "enum": [ - "bot", - "owner" - ] - } - }, - "required": [ - "holder" - ] - } - } - } - }, "responses": { "200": { - "description": "Success", + "description": "File bytes with safe download headers", "content": { - "application/json": { + "application/octet-stream": { "schema": { - "$ref": "#/components/schemas/DesktopControl" + "type": "string", + "format": "binary" } } } @@ -14231,20 +15971,9 @@ } } } - } - }, - "/v1/agents/{id}/desktop/events": { - "get": { - "operationId": "streamDesktopEvents", - "x-sse-events": { - "control": { - "$ref": "#/components/schemas/DesktopControl" - }, - "heartbeat": { - "$ref": "#/components/schemas/HeartbeatEvent" - } - }, - "description": "Server-sent events. A control event carries the DesktopControl JSON object in data, once on connect and on every change. Heartbeat events carry {} every 15 seconds. Authenticate with the Authorization header.", + }, + "delete": { + "operationId": "deleteFile", "security": [ { "BearerAuth": [] @@ -14261,18 +15990,20 @@ "required": true, "name": "id", "in": "path" + }, + { + "schema": { + "type": "string", + "format": "uuid" + }, + "required": true, + "name": "fileId", + "in": "path" } ], "responses": { - "200": { - "description": "SSE stream, not a JSON array", - "content": { - "text/event-stream": { - "schema": { - "type": "string" - } - } - } + "204": { + "description": "Success, no response body" }, "400": { "description": "Invalid request or operation", @@ -14357,9 +16088,9 @@ } } }, - "/v1/agents/{id}/desktop/status": { - "get": { - "operationId": "getDesktopStatus", + "/v1/group-chats/{id}/files": { + "post": { + "operationId": "uploadGroupFile", "security": [ { "BearerAuth": [] @@ -14376,15 +16107,44 @@ "required": true, "name": "id", "in": "path" + }, + { + "schema": { + "type": "string", + "minLength": 1 + }, + "required": true, + "name": "x-file-name", + "in": "header" + }, + { + "schema": { + "type": "string", + "minLength": 1 + }, + "required": true, + "name": "content-type", + "in": "header" } ], + "requestBody": { + "required": true, + "content": { + "*/*": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + }, "responses": { - "200": { + "201": { "description": "Success", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/DesktopStatus" + "$ref": "#/components/schemas/UploadFile" } } } @@ -14470,12 +16230,9 @@ } } } - } - }, - "/v1/agents/{id}/desktop/viewer": { - "post": { - "operationId": "createDesktopViewer", - "description": "Issue a single-use viewer link for the bot desktop. The page and its WebSocket live outside /v1 and need no Authorization header: the link is the credential. With passive=true the link is watch-only: it neither boots the bot's machine nor keeps it awake, and its connection ends when the machine stops. 409 when the bot has no bot desktop.", + }, + "get": { + "operationId": "listGroupFiles", "security": [ { "BearerAuth": [] @@ -14495,20 +16252,35 @@ }, { "schema": { - "type": "string" + "type": "string", + "format": "uuid" }, "required": false, - "name": "passive", + "name": "before", + "in": "query" + }, + { + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 200, + "default": 50 + }, + "required": false, + "name": "limit", "in": "query" } ], "responses": { - "201": { + "200": { "description": "Success", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/DesktopViewer" + "type": "array", + "items": { + "$ref": "#/components/schemas/LibraryFile" + } } } } @@ -14596,9 +16368,9 @@ } } }, - "/v1/agents/{id}/desktop-jobs/{name}/history": { + "/v1/group-chats/{id}/files/{fileId}": { "get": { - "operationId": "getDesktopJobHistory", + "operationId": "getGroupFile", "security": [ { "BearerAuth": [] @@ -14618,40 +16390,22 @@ }, { "schema": { - "type": "string" + "type": "string", + "format": "uuid" }, "required": true, - "name": "name", + "name": "fileId", "in": "path" - }, - { - "schema": { - "type": "integer", - "minimum": 1, - "maximum": 200 - }, - "required": false, - "name": "limit", - "in": "query" - }, - { - "schema": { - "type": "string", - "minLength": 1, - "maxLength": 200 - }, - "required": false, - "name": "before", - "in": "query" } ], "responses": { "200": { - "description": "Success", + "description": "File bytes with safe download headers", "content": { - "application/json": { + "application/octet-stream": { "schema": { - "$ref": "#/components/schemas/TranscriptPage" + "type": "string", + "format": "binary" } } } @@ -14737,11 +16491,9 @@ } } } - } - }, - "/v1/agents/{id}/messages": { - "post": { - "operationId": "sendMessage", + }, + "delete": { + "operationId": "deleteGroupFile", "security": [ { "BearerAuth": [] @@ -14758,82 +16510,20 @@ "required": true, "name": "id", "in": "path" + }, + { + "schema": { + "type": "string", + "format": "uuid" + }, + "required": true, + "name": "fileId", + "in": "path" } ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "content": { - "type": "string", - "maxLength": 32000 - }, - "requestId": { - "type": "string", - "format": "uuid" - }, - "replyTo": { - "type": "string", - "minLength": 1, - "maxLength": 200 - }, - "attachments": { - "type": "array", - "items": { - "type": "object", - "properties": { - "name": { - "type": "string", - "minLength": 1, - "maxLength": 200 - }, - "mimeType": { - "type": "string", - "minLength": 1, - "maxLength": 100 - }, - "data": { - "type": "string", - "minLength": 1, - "pattern": "^[A-Za-z0-9+/]*={0,2}$" - } - }, - "required": [ - "name", - "mimeType", - "data" - ] - }, - "maxItems": 8, - "default": [] - }, - "timezone": { - "type": "string", - "minLength": 1, - "maxLength": 100 - } - }, - "required": [ - "content", - "requestId" - ] - } - } - } - }, "responses": { - "202": { - "description": "Success", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Execution" - } - } - } + "204": { + "description": "Success, no response body" }, "400": { "description": "Invalid request or operation", @@ -16319,186 +18009,12 @@ } ], "responses": { - "200": { - "description": "Success", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/TranscriptPage" - } - } - } - }, - "400": { - "description": "Invalid request or operation", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - } - } - } - }, - "401": { - "description": "Missing, expired, or invalid account session", - "content": { - "text/plain": { - "schema": { - "type": "string" - } - } - } - }, - "404": { - "description": "Resource not found", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - } - } - } - }, - "405": { - "description": "Resource is read-only", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - } - } - } - }, - "409": { - "description": "Conflicting request", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - } - } - } - }, - "413": { - "description": "Request body exceeds the size limit", - "content": { - "text/plain": { - "schema": { - "type": "string" - } - } - } - }, - "500": { - "description": "Internal server error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - } - } - } - }, - "503": { - "description": "Service unavailable", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - } - } - } - } - } - } - }, - "/v1/group-chats/{id}/messages": { - "post": { - "operationId": "sendGroupMessage", - "security": [ - { - "BearerAuth": [] - }, - { - "SessionCookie": [] - } - ], - "parameters": [ - { - "schema": { - "type": "string" - }, - "required": true, - "name": "id", - "in": "path" - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "content": { - "type": "string", - "maxLength": 32000 - }, - "requestId": { - "type": "string", - "format": "uuid" - }, - "replyTo": { - "type": "string", - "minLength": 1, - "maxLength": 200 - }, - "attachments": { - "type": "array", - "items": { - "type": "object", - "properties": { - "name": { - "type": "string", - "minLength": 1, - "maxLength": 200 - }, - "mimeType": { - "type": "string", - "minLength": 1, - "maxLength": 100 - }, - "data": { - "type": "string", - "minLength": 1, - "pattern": "^[A-Za-z0-9+/]*={0,2}$" - } - }, - "required": [ - "name", - "mimeType", - "data" - ] - }, - "maxItems": 8, - "default": [] - } - }, - "required": [ - "content", - "requestId" - ] - } - } - } - }, - "responses": { - "201": { + "200": { "description": "Success", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GroupMessageReceipt" + "$ref": "#/components/schemas/TranscriptPage" } } } @@ -16586,9 +18102,9 @@ } } }, - "/v1/group-chats/{id}/attachments/{entryId}/{index}": { - "get": { - "operationId": "getGroupAttachment", + "/v1/group-chats/{id}/messages": { + "post": { + "operationId": "sendGroupMessage", "security": [ { "BearerAuth": [] @@ -16605,45 +18121,54 @@ "required": true, "name": "id", "in": "path" - }, - { - "schema": { - "type": "string" - }, - "required": true, - "name": "entryId", - "in": "path" - }, - { - "schema": { - "type": [ - "integer", - "null" - ], - "minimum": 0, - "maximum": 7 - }, - "required": true, - "name": "index", - "in": "path" } ], - "responses": { - "200": { - "description": "Attachment bytes; Content-Type identifies the image or text format", - "headers": { - "Cache-Control": { - "schema": { - "type": "string" + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "content": { + "type": "string", + "maxLength": 32000 + }, + "requestId": { + "type": "string", + "format": "uuid" + }, + "replyTo": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "files": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + }, + "maxItems": 8, + "default": [] + } }, - "description": "private, max-age=31536000, immutable" + "required": [ + "content", + "requestId" + ], + "additionalProperties": false } - }, + } + } + }, + "responses": { + "201": { + "description": "Success", "content": { - "*/*": { + "application/json": { "schema": { - "type": "string", - "format": "binary" + "$ref": "#/components/schemas/GroupMessageReceipt" } } } @@ -23419,17 +24944,210 @@ "name": "agentId", "in": "query" } - ], + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Schedule" + } + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "post": { + "operationId": "createSchedule", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "agentId": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "kind": { + "type": "string", + "enum": [ + "prompt", + "script" + ], + "default": "prompt" + }, + "prompt": { + "type": "string", + "maxLength": 32000, + "default": "" + }, + "command": { + "type": [ + "string", + "null" + ], + "maxLength": 8000, + "default": null + }, + "timeoutSeconds": { + "type": "integer", + "minimum": 1, + "maximum": 3600, + "default": 600 + }, + "notify": { + "type": "boolean", + "default": true + }, + "cron": { + "type": [ + "string", + "null" + ], + "maxLength": 100, + "default": null + }, + "timezone": { + "type": "string", + "maxLength": 100, + "default": "UTC" + }, + "runAt": { + "type": [ + "string", + "null" + ], + "format": "date-time", + "default": null + }, + "eventSourceId": { + "type": [ + "string", + "null" + ], + "minLength": 1, + "maxLength": 200, + "default": null + }, + "enabled": { + "type": "boolean", + "default": true + } + }, + "required": [ + "agentId", + "name" + ] + } + } + } + }, "responses": { - "200": { + "201": { "description": "Success", "content": { "application/json": { "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Schedule" - } + "$ref": "#/components/schemas/Schedule" } } } @@ -23454,6 +25172,16 @@ } } }, + "403": { + "description": "Script tasks need coding jobs and must stay with their creator", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, "404": { "description": "Resource not found", "content": { @@ -23515,9 +25243,11 @@ } } } - }, + } + }, + "/v1/schedules/preview": { "post": { - "operationId": "createSchedule", + "operationId": "previewSchedule", "security": [ { "BearerAuth": [] @@ -23533,96 +25263,46 @@ "schema": { "type": "object", "properties": { - "agentId": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string", - "minLength": 1, - "maxLength": 200 - }, - "kind": { - "type": "string", - "enum": [ - "prompt", - "script" - ], - "default": "prompt" - }, - "prompt": { - "type": "string", - "maxLength": 32000, - "default": "" - }, - "command": { - "type": [ - "string", - "null" - ], - "maxLength": 8000, - "default": null - }, - "timeoutSeconds": { - "type": "integer", - "minimum": 1, - "maximum": 3600, - "default": 600 - }, - "notify": { - "type": "boolean", - "default": true - }, "cron": { "type": [ "string", "null" ], - "maxLength": 100, - "default": null - }, - "timezone": { - "type": "string", - "maxLength": 100, - "default": "UTC" + "maxLength": 100 }, "runAt": { "type": [ "string", "null" ], - "format": "date-time", - "default": null + "format": "date-time" }, "eventSourceId": { "type": [ "string", "null" ], - "minLength": 1, - "maxLength": 200, - "default": null + "maxLength": 200 }, - "enabled": { - "type": "boolean", - "default": true + "timezone": { + "type": "string", + "maxLength": 100 } }, "required": [ - "agentId", - "name" + "timezone" ] } } } }, "responses": { - "201": { + "200": { "description": "Success", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Schedule" + "$ref": "#/components/schemas/SchedulePreview" } } } @@ -23647,16 +25327,6 @@ } } }, - "403": { - "description": "Script tasks need coding jobs and must stay with their creator", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - } - } - } - }, "404": { "description": "Resource not found", "content": { @@ -24668,6 +26338,148 @@ } } }, + "/v1/reasoning/preview": { + "post": { + "operationId": "previewReasoning", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "provider": { + "type": "string", + "maxLength": 80 + }, + "model": { + "type": "string", + "maxLength": 200 + }, + "thinkingLevel": { + "type": "string", + "enum": [ + "off", + "minimal", + "low", + "medium", + "high", + "xhigh", + "max" + ], + "default": "off" + } + }, + "required": [ + "provider", + "model" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReasoningPreview" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, "/v1/models": { "get": { "operationId": "listModels", diff --git a/docs/designs/2026-11-14-chat-attention.md b/docs/designs/2026-11-14-chat-attention.md new file mode 100644 index 0000000..0b2a8cb --- /dev/null +++ b/docs/designs/2026-11-14-chat-attention.md @@ -0,0 +1,44 @@ +# Android chat attention + +## Goal + +Adopt the completed server notification contract in the existing Android compatibility PR. Server behavior is defined in `../bot/apps/server/src/contract/push.ts` and `../bot/docs/designs/unseen-reply-push.md`. + +## Contract + +- Replace installation-linked presence with `PUT /v1/chat-attention/views/{viewId}`, sending `{chat: {kind, id}}` or `{chat: null}`. +- Use a random view ID for each native view lifetime and replace it on connection changes. Presence must not depend on notification permission, Firebase, or push registration. +- Report only a mounted bot or group chat in a foreground-active app. Report immediately on attention changes, refresh every 30 seconds, and clear on pause, route leave, logout, or account change. +- Serialize requests for each view. Collapse obsolete pending refreshes so a delayed refresh cannot follow a clear. +- Preserve server `replyReferences` on domain messages from HTTP and event streams. Keep exact event and surface identities. +- Acknowledge exact rendered surfaces through `POST /v1/chat-attention/seen`, with 1-100 distinct event IDs for their original bot or group chat. +- Text acknowledgements require actual nonempty reply content visible within the active viewport. Card acknowledgements require the matching ready card, not a mounted row, summary, loading state, or error. Settled confirmed card content counts. +- Batch acknowledgements and retry failed batches while the same connection remains signed in. Submitted batches retain their original chat across navigation. Never acknowledge incoming events or fetched history without display evidence. +- Refresh the matching active snapshot when a live reply event may precede its history references. Keep unrelated drafts and pending messages intact. + +## Architecture + +Add a testable coroutine-based attention controller, independent of push delivery and registration. The activity's retained AppModel owns it without retaining the Activity. Activity recreation rotates the view ID but preserves already-earned seen batches in the retained controller. Compose reports the mounted chat, actual surface bounds, and readiness. A stale callback carries its original API identity, view ID, and chat and cannot acknowledge after replacement or navigation. + +Before revoking an old session, the model requests a serialized clear through the old API, invalidates old callbacks and seen queues, and rotates identity. Bound this best-effort clear to two seconds; a lost clear expires through the server TTL. An empty-token API is signed out. + +Presence and seen retries use bounded backoff. Transient seen failures retry on their original chat. Split a terminally rejected batch into individual acknowledgements so one rejected ID cannot block valid IDs; drop terminally rejected individual IDs. Authentication failure stops old-account retries. + +A live-event refresh captures API identity, selection/group version, and snapshot revision. Apply it only if all remain current. A newer streamed snapshot invalidates the pending HTTP response. Use existing optimistic reconciliation. + +### Ready surfaces + +Wrap actual rendered text/card content, not lazy rows. Intersect its bounds with the chat list viewport, and acknowledge only when active and ready. + +- Assistant text: nonempty rendered Markdown text in bot or group chats. Citation chips alone do not count. +- Held action: matching `heldAction.id` with a loaded action, pending or confirmed settled; missing, loading, or unavailable actions are not ready. +- Credential/login: the existing `secretRequestState` is Waiting, Saved, or Declined. Loading and Unavailable are not ready. Match the message's `toolCallId` to the reference. +- Call/bot requests: matching loaded request, pending or confirmed settled; missing request is not ready. Match the message's `toolCallId`. +- Job question cards have no new acknowledgement boundary without a verified producer mapping. The server adds no standalone question event; ordinary referenced reply text remains supported. +- Group cards and collapsed event/notice summaries not currently rendered as those exact surfaces remain unacknowledged. + +Keep push registration, notification settings, local delivery, FCM payloads, duplicate tracking, and notification tap routing unchanged. Remove the old presence request and its registration-dependent runtime heartbeat. + +## Verification + +Add regression coverage for presence without push registration, bot/group identity, foreground and mounted-view gates, serialized clears, account changes, exact surface matching and readiness, batched retry, original-chat retention, and event/reference refresh races. Demonstrate the old behavior fails before fixing it. Run Python contract tests, generated-output checks, Android unit tests, lint, and debug assembly. No emulator-based CI or live providers. Report native viewport/lifecycle behavior not manually verified. diff --git a/docs/designs/2026-11-14-file-compatibility.md b/docs/designs/2026-11-14-file-compatibility.md new file mode 100644 index 0000000..c2f5892 --- /dev/null +++ b/docs/designs/2026-11-14-file-compatibility.md @@ -0,0 +1,39 @@ +# File compatibility with the current server + +## Goal + +Restore existing Android attachment behavior against the current server contract in `../bot/openapi/`. Do not add new product surfaces. + +## Scope + +- Extend contract generation and its transport boundary to support upload headers, raw binary requests, and binary download responses. Explicit MIME headers override the JSON default. +- Include the group snapshot export in contract copying and generation so group event files are checked too. +- Refresh contract assets and generated Kotlin models and operations from the server's committed export. +- Upload bot and group chat attachments before sending messages. Submit returned file IDs through `files`, not inline `attachments`. +- Read transcript file metadata and deleted-file markers. Fetch attachment contents by file ID for bot and group chats. +- Preserve existing image previews, drafts, reply targets, optimistic sends, and duplicate-free retries. +- Update documentation, changelog, and regression coverage. + +## Behavior + +A send displays its optimistic message immediately. Bot upload failures preserve the draft and attachments through the existing restoration behavior. Group failures retain attachments and reply identity on the failed row, retried through its Retry action; do not add group composer restoration. Retries reuse the message request ID. Reuse successfully uploaded files when retrying that send within the same server and chat; never share uploaded IDs across chats or connections. + +If the server definitively rejects a send because a cached file was deleted or is missing from its library, discard that send's upload IDs. The next explicit retry uploads from retained local bytes, retaining the message request ID. Ambiguous failures keep cached IDs. + +Late uploads or sends from a previous connection must not alter the current connection's state. Navigating between chats must not lose drafts or route attachments to the wrong chat. Server refreshes must not overwrite pending sends. Reconciliation must not duplicate messages. + +Transcript file IDs are authoritative for content requests and cache identity, scoped by connection and chat. Derive image preview eligibility from MIME metadata. Deleted files remain recognizable without content fetches or crashes. Deleted metadata hides cached images immediately. Downloads completing after deletion must not republish their bytes. + +## Notification boundary + +This boundary applied to the initial file migration. After the server notification work finished, the owner approved [Android chat attention](2026-11-14-chat-attention.md) in the same PR; that design supersedes this boundary. + +Notification behavior belongs to another agent. Do not implement chat attention, alter notification suppression, or modify push registration/presence lifecycle code. Generated contract changes include server notification declarations mechanically. If removed operations block compilation, coordinate an integration boundary without preserving obsolete generated endpoints or inventing replacement behavior. + +## Out of scope + +Library browsing, manual file management, new attachment picker types, notification migration, server changes, and unrelated client features. + +## Verification + +Demonstrate failing regressions before fixing compatibility. Cover upload headers and bytes, file IDs in sends, partial upload failure and retry, deleted files, group downloads, and connection changes during upload. Run Python generator tests, generated-output verification, Android unit tests, lint, and the debug build. No real server credentials or paid services in tests. Report notification integration blockers separately. diff --git a/docs/plans/2026-11-14-chat-attention.md b/docs/plans/2026-11-14-chat-attention.md new file mode 100644 index 0000000..661c951 --- /dev/null +++ b/docs/plans/2026-11-14-chat-attention.md @@ -0,0 +1,83 @@ +# Android chat attention implementation plan + +> Implement one task at a time. Review each deliverable before starting the next. + +**Goal:** Report native chat attention and acknowledge exact displayed reply surfaces using the current server contract. +**Architecture:** A coroutine controller serializes independent view presence and retries per-chat seen batches. Compose supplies mounted-view and surface visibility evidence; push registration remains separate. +**Source:** `docs/designs/2026-11-14-chat-attention.md`. + +## Decisions + +- Include notification adoption in PR #17 after the server implementation finished. +- Preserve push delivery, registration, notification preferences, and taps. +- Fail closed for uncertain surface readiness; never infer seen state from event receipt or history fetches. + +## Constraints + +- Reuse generated contract operations and types. No new dependencies. +- No simulator or emulator tests in CI. Default tests use recording transports, never real providers. +- Run Python tests, contract checks, Android unit tests, lint, and debug assembly. + +## Out of scope + +Server changes, notification preferences, unread badge synchronization, provider behavior, and unsupported new card interfaces. + +## Review focus + +- Active refresh already in flight when the app pauses must be followed by a clear, never by another stale refresh. +- A delayed rendering callback cannot cross account, server, or chat identity. +- A failed submitted seen batch retains its original chat when navigation changes. +- Loading, collapsed, offscreen, and error card states must not count as seen. + +## Files + +- `push/ChatAttention.kt` (new): controller and exact-surface matching helpers. +- `network/APIClient.kt`, `push/PushContract.kt`: new attention operations, removal of legacy presence contract. +- `model/Models.kt`, `network/ContractAdapters.kt`: reply references on domain messages. +- `model/ReplyAttention.kt` (new): exact-surface identity, route identity, and canonical card readiness. +- `MainActivity.kt`, `push/PushRuntime.kt`, `push/PushSyncWorker.kt`: independent attention lifecycle and removal of registration-dependent reporting. +- `ui/ReplyAttention.kt` (new), `ui/ChatScreen.kt`, `ui/GroupChatScreen.kt`: viewport and mounted-chat reporting. +- `ui/DecisionCards.kt` supplies existing readiness states; `model/Secrets.kt` supplies `secretRequestState`. Add a shared model readiness helper used at the real card dispatch boundaries, not at rows. +- `model/AppModel.kt`: refresh the active matching snapshot after live reply events. +- `ChatAttentionTests.kt`, `ReplyAttentionTests.kt` (new), existing push contract and chat fixtures: regression coverage. +- `README.md`, `CHANGELOG.md`, earlier compatibility docs: replace the deferred-notification limitation with implemented behavior. + +### Task 1: Contract and controller + +**Interfaces:** add `APIClient.putChatAttentionView(viewID: String, chat: ChatAttentionChat?)` and `postChatAttentionSeen(chat: ChatAttentionChat, eventIDs: List)`. Create `ChatAttentionChat(kind: String, id: String)`. `ChatAttention(scope: CoroutineScope)` exposes `val viewId: String`, `update(api: APIClient?, active: Boolean, chat: ChatAttentionChat?)`, `setDisplayedChat(chat: ChatAttentionChat?)`, `newView()`, `displayed(api: APIClient, viewId: String, chat: ChatAttentionChat, eventIDs: List)`, and `suspend disconnect(api: APIClient)`. Disconnect uses a bounded best-effort old-API clear and invalidates old seen work. New views retain seen batches within the same connection. Domain messages retain generated `TranscriptMessageReplyReferencesItem` values; SSE adapters convert their structurally identical references to that canonical type. + +- [x] Add regressions and demonstrate failures before implementation. +- [x] Implement serialized presence, heartbeat, view rotation, and scoped acknowledgement batching/retry. +- [x] Preserve generated reply references in domain messages. +- [x] Verify controller and API regressions. + +### Task 2: Native view and renderer integration + +**Interfaces:** create `AttentionChat(model, chat, ready, content)` as the mounted-view provider, `attentionViewport(): Modifier` for the real list bounds, and `ReplyAttention(model, message, surface, ready, content)` around exact rendered content. Surface matching uses canonical generated references and original API/view/chat identity. Readiness follows the specification's Ready surfaces section and existing card state helpers. The activity updates foreground/route/API independently from Compose mounting. The retained model clears attention before old-session revocation. + +- [x] Connect native foreground state and mounted chat presence independently of push registration. +- [x] Report only exact ready visible surfaces, with stale-callback identity checks. +- [x] Refresh the matching active snapshot after live replies without replacing optimistic state. +- [x] Remove legacy presence reporting and update its tests. +- [x] Update documentation and run all project checks. +- [x] Review against the specification in a fresh reviewer context. + +## Deviations + +- Task 1 · Bound every retired view's clear to two seconds and track its connection ownership. Review found abandoned view retries could otherwise outlive logout. +- Task 1 · Reject a disconnected API identity across null updates until a distinct connection is installed. Review found Activity recreation could otherwise reconnect during sign-out. +- Task 2 · Use an attention modifier directly on Markdown text, excluding citation-only visibility. Card content uses the specified wrapper. +- Task 2 · Keep an Activity window token separate from the connection-rotated server view ID. Old Activity callbacks cannot mount or report for a new window. +- Task 2 · Make `appActive` observable Compose state. Review found unchanged geometry would otherwise prevent acknowledgement after resuming. +- Task 2 · Question cards remain without an acknowledgement boundary because the server introduces no standalone question producer. Existing ordinary referenced text remains supported. + +## Verification + +- The old presence endpoint assertion failed before migration and passes through the new independent API. +- Both teardown regressions failed before the fixes and pass afterward. The foreground-observation regression also failed before its fix. +- Controller tests cover mount/foreground gates, bot/group identity, serialized clear/heartbeat, view rotation, scoped retries, 100-ID batching, invalid batches, disconnection, and authentication failure. +- Renderer policy tests cover exact surface identity, viewport intersection, secret-card readiness, preserved HTTP/event references, and refresh ordering across stream updates and navigation. +- Python tests: 12 passed. Android unit tests: 508 passed, no failures or skips. Contract verification, lint, debug assembly, and `git diff --check` passed. +- Fresh implementation review and focused correction review completed with no remaining findings. +- Native viewport/lifecycle behavior was not manually tested on a device or emulator. Live providers and cross-client delivery were not tested. +- Previous PR CI passed, but its unit-test job took 2m23s, above the repository's two-minute target. CI configuration was not changed by notification adoption; the next run's duration remains unverified. diff --git a/docs/plans/2026-11-14-file-compatibility.md b/docs/plans/2026-11-14-file-compatibility.md new file mode 100644 index 0000000..be2f3c0 --- /dev/null +++ b/docs/plans/2026-11-14-file-compatibility.md @@ -0,0 +1,84 @@ +# File compatibility implementation plan + +> Implement one task at a time. Review each deliverable before starting the next. + +**Goal:** Restore existing Android file sends and transcript attachments against the current server. +**Architecture:** Keep generated wire types authoritative. Adapt files at the network boundary and retain upload progress with each pending send. +**Source:** `docs/designs/2026-11-14-file-compatibility.md`. + +## Decisions + +- Prioritize compatibility, not new server features. +- Leave notification behavior to the other agent. +- Preserve optimistic sends, drafts, retry request IDs, and server/chat isolation. + +## Constraints + +- No new dependencies or server modifications. +- Regression tests must fail before fixes and pass afterward. +- Run Python tests, contract check, Android tests, lint, and debug assembly. + +## Out of scope + +Library browsing, new picker types, notification migration, and unrelated cleanup. + +## Review focus + +- Partial upload failure preserves already uploaded IDs for retry. +- Late uploads after reconnection cannot send to the new connection or alter its draft. +- Deleted transcript files do not trigger downloads. +- Group file downloads use file IDs rather than entry indices. + +## Files + +- `scripts/generate-contract.py`, `scripts/templates/ContractBoundary.kt`: support upload headers and raw bodies. +- `scripts/test_contract.py`: generator regression coverage. +- `contract/assets/`, `app/src/main/java/dev/crumble/android/generated/`: refreshed server contract. +- `app/src/main/java/dev/crumble/android/network/APIClient.kt`, `ContractAdapters.kt`: upload, send, download, and transcript conversion. +- `app/src/main/java/dev/crumble/android/model/Models.kt`, `AppModel.kt`: file identity and send lifecycle. +- `app/src/main/java/dev/crumble/android/model/Attachments.kt`: pending raw file bytes. +- `app/src/main/java/dev/crumble/android/ui/ChatScreen.kt`: shared attachment rendering, including deleted-file placeholders. +- `app/src/test/java/dev/crumble/android/FileCompatibilityTests.kt`: new file lifecycle regressions. +- Existing tests in `GeneratedContractTests.kt`, `CrumbleTests.kt`, `DraftsAndReadsTests.kt`, and `GroupChatTests.kt`: update old wire expectations and fixtures. +- `README.md`, `CHANGELOG.md`: document compatibility behavior. + +### Task 1: Upload-capable contract generation + +**Interfaces:** `HttpRequestData` already carries `headers: Map` and `body: ByteArray?` (`network/APIClient.kt:95`). Add an optional headers argument to generated `ContractBoundary.request` and `send`, forwarding it through the existing transport. + +- [x] Add and demonstrate failing generator regressions for header parameters and binary bodies. +- [x] Support these constructs using the existing HTTP transport, then regenerate from `../bot/openapi/`. +- [x] Verify generated output and Python tests. +- [x] Resolve compile integration with removed presence operation without implementing notification behavior. + +### Task 2: File-aware sends and transcript attachments + +**Interfaces:** `PendingAttachment` holds name, MIME type, raw bytes, and a local UUID (`model/Attachments.kt:22`). `PendingSend` holds immutable content, reply target, and attachments (`model/AppModel.kt:412`); add per-send successful upload IDs. Keep `sendChatMessage` and `sendGroupMessage` callers explicit: send file IDs after uploads. `AttachmentInfo` (`model/Models.kt:173`) gains file ID and deletion state. Preserve entry/index UI loader signatures; resolve current transcript metadata before fetching by file ID. + +- [x] Add and demonstrate failing regressions for uploads, file-ID sends, partial retry, deleted files, group downloads, and connection changes. +- [x] Add file metadata conversion and content fetching by ID. +- [x] Upload before sending while retaining successful uploads for retry within the originating connection and chat. +- [x] Preserve existing optimistic state and failure recovery. +- [x] Run targeted tests, then all project checks. +- [x] Update README and changelog. + +## Deviations + +- Task 1 · planned: resolve removed presence operation without notification behavior changes · did: retain the identical legacy presence request at the hand-written HTTP boundary · why: generated operations must match the current server; notification migration remains owned by another agent. The legacy presence route remains incompatible until that work lands. +- Task 1 · planned: refresh the existing export set · did: also copy and generate the group snapshot event export · why: spec review found otherwise-unverified group event file schemas. +- Task 2 · planned: preserve existing failure behavior · did: retain group attachments on the failed row without adding composer restoration · why: restoring a group composer would require a separate duplicate-send policy. +- Task 2 · planned: retain successful upload IDs · did: clear them only after a definitive missing/deleted-file rejection, retaining the message request ID · why: otherwise deleted uploads prevent recovery. +- Task 2 · planned: update attachment tests · did: also update wire fixtures in `CallRequestTests.kt`, `ChatParityTests.kt`, and `SecretsTests.kt` · why: the refreshed server contract requires `replyReferences` on every transcript message. + +## Verification and review + +- Four initial file compatibility regressions failed against the old client and pass after implementation. +- Three generator compatibility regressions failed before generator changes and pass afterward. +- Review found deletion across retained references was incomplete. Two added bot regressions failed before correction; bot and group regressions now pass. +- Python tests: 12 passed. Android unit tests: 492 passed, no failures or skips. +- Generated-output verification, asset comparison with `../bot/openapi/`, `git diff --check`, lint, and debug assembly passed. +- The first full Android run failed on stale transcript fixtures and exhausted memory in a polling test. Updating required `replyReferences` fields resolved both failures without changing runtime behavior. +- Independent implementation review and focused correction review completed with no remaining findings. +- Live server and device or emulator behavior were not tested. Notification compatibility was deferred in this phase. The owner subsequently approved [Android chat attention](2026-11-14-chat-attention.md) in the same PR, replacing the legacy presence boundary. + +Keep one implementer for the send lifecycle because upload progress and optimistic reconciliation share state. The owner authorized committing, pushing, and opening PR #17 after verification. diff --git a/scripts/contract.py b/scripts/contract.py index f1ea6f1..7acc72a 100644 --- a/scripts/contract.py +++ b/scripts/contract.py @@ -7,7 +7,7 @@ import tempfile ROOT = pathlib.Path(__file__).resolve().parents[1] -ASSETS = ("openapi.json", "chat-snapshot.schema.json", "activity-event.schema.json", "heartbeat.schema.json") +ASSETS = ("openapi.json", "chat-snapshot.schema.json", "group-chat-snapshot.schema.json", "activity-event.schema.json", "heartbeat.schema.json") GENERATED = ROOT / "app/src/main/java/dev/crumble/android/generated" diff --git a/scripts/generate-contract.py b/scripts/generate-contract.py index b102400..793aa66 100644 --- a/scripts/generate-contract.py +++ b/scripts/generate-contract.py @@ -1,12 +1,12 @@ #!/usr/bin/env python3 -"""Crumble Kotlin contract generator 1.2.0; Python standard library only.""" +"""Crumble Kotlin contract generator 1.3.0; Python standard library only.""" import argparse import copy import json import pathlib import re -VERSION = "1.2.0" +VERSION = "1.3.0" ROOT = pathlib.Path(__file__).resolve().parents[1] PACKAGE = "dev.crumble.android.generated" HEADER = "// Generated by scripts/generate-contract.py " + VERSION + ". Do not edit.\npackage " + PACKAGE + "\n\n" @@ -28,21 +28,49 @@ def quoted(value): return json.dumps(value, ensure_ascii=False).replace("$", "\\$") +def comparable(value): + if isinstance(value, list): + return [comparable(item) for item in value] + if not isinstance(value, dict): + return value + result = {} + for key, item in value.items(): + if key == "discriminator" or (key == "additionalProperties" and item is True): + continue + if key == "const" and "enum" not in value: + result["enum"] = [comparable(item)] + else: + result[key] = comparable(item) + return result + + def project(document, events): document = copy.deepcopy(document) schemas = document["components"]["schemas"] + canonical = set(schemas) for name, event in events.items(): event = copy.deepcopy(event) definitions = event.pop("$defs", {}) - mapping = {key: name + pascal(key) for key in definitions} + mapping = {key: key if key in canonical else name + pascal(key) for key in definitions} + def reference(value): + pointer = value.removeprefix("#/$defs/").split("/") + key = pointer[0].replace("~1", "/").replace("~0", "~") + target = mapping[key].replace("~", "~0").replace("/", "~1") + return "/".join(["#/components/schemas", target, *pointer[1:]]) + def refs(value): if isinstance(value, dict): - return {k: ("#/components/schemas/" + mapping[v.split("/")[-1]] if k == "$ref" and v.startswith("#/$defs/") else refs(v)) for k, v in value.items()} + return {k: (reference(v) if k == "$ref" and v.startswith("#/$defs/") else refs(v)) for k, v in value.items()} if isinstance(value, list): return [refs(v) for v in value] return value for key, value in definitions.items(): - schemas[mapping[key]] = refs(value) + rewritten = refs(value) + if key in canonical: + if comparable(schemas[key]) != comparable(rewritten): + raise ValueError("event definition conflicts with HTTP schema: " + key) + else: + schemas[mapping[key]] = rewritten schemas[name] = refs(event) return document @@ -251,7 +279,7 @@ def operations(self): if method not in ("get", "post", "patch", "put", "delete"): raise ValueError("unsupported path entry: " + method) op = operation["operationId"] - params, query = [], [] + params, query, headers = [], [], [] route = quoted(path) for param in operation.get("parameters", []): key = param["name"] @@ -264,16 +292,26 @@ def operations(self): elif param["in"] == "query": value = "it" if t == "String" else "it.toString()" query.append(" `" + key + "`" + ("?.let" if optional else ".let") + " { query.add(" + quoted(key + "=") + " + boundary.escape(" + value + ")) }") + elif param["in"] == "header": + value = "it" if t == "String" else "it.toString()" + headers.append(" `" + key + "`" + ("?.let" if optional else ".let") + " { headers[" + quoted(key) + "] = " + value + " }") else: raise ValueError("unsupported parameter location") body = "null" if "requestBody" in operation: content = operation["requestBody"]["content"] - if list(content) != ["application/json"]: + if list(content) == ["application/json"]: + t = self.type(content["application/json"]["schema"], pascal(op) + "Request", True) + body = "boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8)" + elif len(content) == 1 and next(iter(content)) in ("*/*", "application/octet-stream"): + schema = content[next(iter(content))]["schema"] + self.validate(schema) + if schema.get("type") != "string" or schema.get("format") != "binary": + raise ValueError("binary request requires a binary string schema") + t, body = "ByteArray", "body" + else: raise ValueError("unsupported request media type") - t = self.type(content["application/json"]["schema"], pascal(op) + "Request", True) params.insert(0, "body: " + t) - body = "boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8)" params.append("timeoutMs: Int = 20_000") success = [(status, value) for status, value in operation["responses"].items() if status.startswith("2")] if len(success) != 1: @@ -285,7 +323,7 @@ def operations(self): streaming = media == "text/event-stream" if media == "application/json": t = self.type(content[media]["schema"], pascal(op) + "Response") - elif media in ("image/*", "*/*"): + elif media in ("image/*", "*/*", "application/octet-stream"): t = "ByteArray" elif media is None: t = "Unit" @@ -296,10 +334,13 @@ def operations(self): lines += [" suspend fun " + op + "(" + ", ".join(params) + "): " + t + " {"] lines += [" val query = mutableListOf()"] + query lines += [" val path = " + route + ' + if (query.isEmpty()) "" else "?" + query.joinToString("&")'] + if headers: + lines += [" val headers = mutableMapOf()"] + headers + arguments = quoted(method.upper()) + ", path, " + body + ", timeoutMs" + (", headers" if headers else "") + ")" if streaming: - lines += [" return boundary.request(" + quoted(method.upper()) + ", path, " + body + ", timeoutMs)"] + lines += [" return boundary.request(" + arguments] else: - call = "boundary.send(" + quoted(method.upper()) + ", path, " + body + ", timeoutMs)" + call = "boundary.send(" + arguments if t == "Unit": lines += [" " + call] elif t == "ByteArray": @@ -330,12 +371,15 @@ def main(): parser.add_argument("--output", type=pathlib.Path, default=ROOT / "app/src/main/java/dev/crumble/android/generated") args = parser.parse_args() document = json.loads((args.assets / "openapi.json").read_text()) - events = {name: json.loads((args.assets / filename).read_text()) for name, filename in [("SnapshotEventPayload", "chat-snapshot.schema.json"), ("ActivityEventPayload", "activity-event.schema.json"), ("HeartbeatEventPayload", "heartbeat.schema.json")]} - event_projection = project({"openapi": "3.1.0", "info": {"title": "Crumble SSE payloads", "version": document["info"]["version"]}, "components": {"schemas": {}}, "paths": {}}, events) + events = {name: json.loads((args.assets / filename).read_text()) for name, filename in [("SnapshotEventPayload", "chat-snapshot.schema.json"), ("GroupSnapshotEventPayload", "group-chat-snapshot.schema.json"), ("ActivityEventPayload", "activity-event.schema.json"), ("HeartbeatEventPayload", "heartbeat.schema.json")]} + canonical = document["components"]["schemas"] + event_definitions = {key for event in events.values() for key in event.get("$defs", {})} + shared = {key: canonical[key] for key in sorted(event_definitions) if key in canonical} + event_projection = project({"openapi": "3.1.0", "info": {"title": "Crumble SSE payloads", "version": document["info"]["version"]}, "components": {"schemas": shared}, "paths": {}}, events) for name, schema in event_projection["components"]["schemas"].items(): - if name in document["components"]["schemas"]: + if name in canonical and canonical[name] != schema: raise ValueError("event projection collides with HTTP schema: " + name) - document["components"]["schemas"][name] = schema + canonical[name] = schema Generator(document).generate(args.output) (args.output / "event-projection.json").write_text(json.dumps(event_projection, indent=2, ensure_ascii=False) + "\n") diff --git a/scripts/templates/ContractBoundary.kt b/scripts/templates/ContractBoundary.kt index 8f32bde..452a83d 100644 --- a/scripts/templates/ContractBoundary.kt +++ b/scripts/templates/ContractBoundary.kt @@ -7,8 +7,8 @@ import kotlinx.serialization.json.Json interface ContractBoundary { val json: Json fun escape(value: String): String - fun request(method: String, path: String, body: ByteArray?, timeoutMs: Int): HttpRequestData - suspend fun send(method: String, path: String, body: ByteArray?, timeoutMs: Int): ByteArray + fun request(method: String, path: String, body: ByteArray?, timeoutMs: Int, headers: Map = emptyMap()): HttpRequestData + suspend fun send(method: String, path: String, body: ByteArray?, timeoutMs: Int, headers: Map = emptyMap()): ByteArray } @Serializable(with = OptionalFieldCodec::class) diff --git a/scripts/test_contract.py b/scripts/test_contract.py index fad3bc2..d78132a 100644 --- a/scripts/test_contract.py +++ b/scripts/test_contract.py @@ -1,4 +1,5 @@ import importlib.util +import json import pathlib import shutil import tempfile @@ -40,6 +41,93 @@ def test_rejects_manual_edits_and_unexpected_files(self): finally: contract.GENERATED = original + def test_event_definitions_reuse_canonical_schemas(self): + canonical = {"type": "object", "properties": {"text": {"type": "string"}}} + document = {"components": {"schemas": {"TranscriptBlock": canonical}}} + event = {"$defs": {"TranscriptBlock": canonical, "Local": {"$ref": "#/$defs/TranscriptBlock"}}, "properties": {"block": {"$ref": "#/$defs/TranscriptBlock"}, "local": {"$ref": "#/$defs/Local"}}} + projected = generator.project(document, {"Snapshot": event})["components"]["schemas"] + self.assertEqual(canonical, projected["TranscriptBlock"]) + self.assertEqual("#/components/schemas/TranscriptBlock", projected["Snapshot"]["properties"]["block"]["$ref"]) + self.assertEqual("#/components/schemas/SnapshotLocal", projected["Snapshot"]["properties"]["local"]["$ref"]) + self.assertEqual("#/components/schemas/TranscriptBlock", projected["SnapshotLocal"]["$ref"]) + self.assertNotIn("SnapshotTranscriptBlock", projected) + conflicting = {"$defs": {"TranscriptBlock": {"type": "string"}}} + with self.assertRaisesRegex(ValueError, "event definition conflicts with HTTP schema: TranscriptBlock"): + generator.project(document, {"Snapshot": conflicting}) + nested = generator.project(document, {"Snapshot": {"$defs": {"TranscriptBlock": canonical}, "properties": {"text": {"$ref": "#/$defs/TranscriptBlock/properties/text"}}}}) + self.assertEqual("#/components/schemas/TranscriptBlock/properties/text", nested["components"]["schemas"]["Snapshot"]["properties"]["text"]["$ref"]) + + def test_snapshot_reuses_generated_transcript_block(self): + source = (contract.GENERATED / "ContractModels.kt").read_text() + snapshot_message = source.split("data class SnapshotEventPayloadMessagesItem(", 1)[1].split("\n)", 1)[0] + self.assertIn("val `blocks`: List? = null", snapshot_message) + self.assertNotIn("SnapshotEventPayloadTranscriptBlock", source) + self.assertIn("data class Variant3(val value: JobStepItem) : JobHistoryItem()", source) + + def test_group_snapshot_is_copied_and_projected(self): + self.assertIn("group-chat-snapshot.schema.json", contract.ASSETS) + event = json.loads((ROOT / "contract/assets/group-chat-snapshot.schema.json").read_text()) + projection = json.loads((contract.GENERATED / "event-projection.json").read_text())["components"]["schemas"] + snapshot = projection["GroupSnapshotEventPayload"] + self.assertEqual(event["required"], snapshot["required"]) + self.assertEqual("#/components/schemas/TranscriptBlock", snapshot["properties"]["messages"]["items"]["properties"]["blocks"]["items"]["$ref"]) + source = (contract.GENERATED / "ContractModels.kt").read_text() + message = source.split("data class GroupSnapshotEventPayloadMessagesItem(", 1)[1].split("\n)", 1)[0] + self.assertIn("val `blocks`: List? = null", message) + self.assertIn("val `files`: List? = null", message) + self.assertNotIn("GroupSnapshotEventPayloadTranscriptBlock", source) + for name in ("TranscriptMessageFilesItem", "SnapshotEventPayloadMessagesItemFilesItem", "GroupSnapshotEventPayloadMessagesItemFilesItem"): + with self.subTest(name=name): + self.assertIn("sealed class " + name, source) + deleted = source.split("data class " + name + "Variant2(", 1)[1].split("\n)", 1)[0] + self.assertIn("val `id`: String", deleted) + self.assertIn("val `deleted`: Boolean", deleted) + + def operation_source(self, operation): + document = {"components": {"schemas": {}}, "paths": {"/files": {"post": dict(operationId="uploadFile", **operation)}}} + return generator.Generator(document).operations() + + def test_header_parameters_are_forwarded(self): + for media, boundary in ((None, "send"), ("text/event-stream", "request")): + with self.subTest(media=media): + response = {} if media is None else {"content": {media: {}}} + source = self.operation_source({ + "parameters": [ + {"in": "header", "name": "Content-Type", "required": True, "schema": {"type": "string"}}, + {"in": "header", "name": "X-File-Name", "schema": {"type": "string"}}, + {"in": "header", "name": "X-Count", "schema": {"type": "integer"}}, + ], + "responses": {"200": response}, + }) + self.assertIn('`Content-Type`: String', source) + self.assertIn('`X-File-Name`: String? = null', source) + self.assertIn('`Content-Type`.let { headers["Content-Type"] = it }', source) + self.assertIn('`X-File-Name`?.let { headers["X-File-Name"] = it }', source) + self.assertIn('`X-Count`?.let { headers["X-Count"] = it.toString() }', source) + self.assertIn('boundary.' + boundary + '("POST", path, null, timeoutMs, headers)', source) + + def test_raw_binary_request_preserves_bytes(self): + source = self.operation_source({ + "requestBody": {"required": True, "content": {"*/*": {"schema": {"type": "string", "format": "binary"}}}}, + "responses": {"204": {}}, + }) + self.assertIn('suspend fun uploadFile(body: ByteArray, timeoutMs: Int = 20_000): Unit', source) + self.assertIn('boundary.send("POST", path, body, timeoutMs)', source) + self.assertNotIn('encodeToString', source) + self.assertNotIn('headers', source) + + def test_binary_request_requires_binary_schema(self): + for media, schema in (("*/*", {"type": "string"}), ("application/octet-stream", {"type": "object"}), ("text/plain", {"type": "string"})): + with self.subTest(media=media, schema=schema), self.assertRaises(ValueError): + self.operation_source({"requestBody": {"content": {media: {"schema": schema}}}, "responses": {"204": {}}}) + + def test_octet_stream_download_returns_bytes(self): + source = self.operation_source({"responses": {"200": {"content": {"application/octet-stream": {"schema": {"type": "string", "format": "binary"}}}}}}) + self.assertIn('suspend fun uploadFile(timeoutMs: Int = 20_000): ByteArray', source) + self.assertIn('return boundary.send("POST", path, null, timeoutMs)', source) + self.assertNotIn('decodeFromString', source) + self.assertNotIn('headers', source) + def test_unsupported_schema_fails_closed(self): instance = generator.Generator({"components": {"schemas": {}}, "paths": {}}) for schema in ({"type": "object", "patternProperties": {}}, {"type": "object", "additionalProperties": False}, {"type": ["string", "number"]}):