Fan a chat session out to every client and share approvals exactly-once
A session was owned by one connection: the claim map in chat_claims.go let the
first client hold it, every other client saw the session Busy and read-only, and
a second client's prompt was rejected. Replace the claim with a per-session
"room" so the operator's phone, tablet and terminal all watch and write the same
conversation, and a pending approval is a shared, exactly-once object.
Server (internal/server, internal/protocol):
- New chat_room.go: one room per session holding the session's single broker
stream, its one bounded prompt queue (8) and the fan-out to every attached
client. A chat_subscribe frame attaches a connection to a session's shared
stream and replays the still-unresolved approval requests the room holds.
- chat_stream.go: handleChatPrompt accepts a prompt from any client. It attaches
the sender, either starts a turn or queues the prompt behind the in-flight turn
and acknowledges it with chat_queued:true ("queued" is the chosen behaviour,
stated on the wire and in docs/cli.md), and echoes the user turn to every other
client attributed to the sender's label. The prompt handler no longer owns the
stream; one turn runner per room drains the queue, so two turns never
interleave. Per-connection write serialisation is unchanged (each chatSub has
its own writer goroutine and bounded buffer).
- chat_permissions.go / chat_commands.go: an approval is reserved by the first
answer and confirmed once delivered; the first answer wins, is recorded with
the answering client's label, and the resolution is pushed to every watching
client as chat_permission with resolved/decision/resolved_by so their cards
clear. A later answer is refused with an error naming the client that answered,
and never reaches the agent twice; a reservation whose reply failed is
released.
- chat_hub.go / chat_sessions.go / chat.go: the hub now owns rooms and the
user-turn id sequence; the resulting user turns are retained (role and client
carried) so a reconnect re-syncs who said what. chat_sessions no longer marks a
session Busy and its clientID parameter is gone; the protocol keeps the Busy
field for wire compatibility only. websocket.go detaches a connection's chat
subscriptions when the read loop ends.
- chat_claims.go is removed, not left vestigial: the only exclusive thing left is
a turn, and the room's queue is that.
App (android):
- PipelinesRepository carries a stable per-device client label (Build.MODEL, with
a fallback) on prompts and replies, and adds chatSubscribe; AppViewModel
subscribes on opening a chat (best-effort, an older server's error frame does
not stop history loading) and records the queued ack.
- ChatStore folds a user frame from another client into the transcript once,
attributed by the sender's label, and never receives its own prompt back, so
the sender's own message is never duplicated. ChatThread.readOnly is gone:
canSend no longer depends on another client, the composer says "Queued - it
will send when the current turn finishes." instead of disabling input, and the
status label is Running/Idle only. Scroll/follow behaviour is untouched.
- Tests: ChatProtocolTest round-trips the new wire fields, ChatFormatTest asserts
the stale Busy flag cannot produce a read-only label, MultiChatStateTest asserts
a session another client watches stays writable.
Reflected where it belongs: no packaged template changes (no bundled starter
embeds the chat protocol). Checked the packaged authoring skill references: none
of them describes the chat wire beyond operations.md, and
internal/author/skill/references/operations.md is now stale - its "Brokered
OpenCode chat" section still says chat_sessions marks "busy" when another client
holds the session and that a second client's chat_prompt is rejected, and it does
not mention chat_subscribe, the per-session prompt queue/chat_queued, the
per-client label or the shared exactly-once approval (it also still describes the
per-subscription permission poller, which the room's single poller replaced). The
supported semantics are the ones in docs/cli.md, updated in this commit; the
operations.md section needs a rewrite to match. No README or other shared
document was edited here.
Checks run on the committed tree: gofmt -l internal cmd examples (nothing), go
build ./..., go vet ./internal/... ./cmd/..., go test ./internal/server
./internal/protocol ./internal/stage ./internal/pipeline.
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
package net.awan.pipelines.data
|
||||
|
||||
import android.os.Build
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import kotlinx.coroutines.flow.SharedFlow
|
||||
@@ -27,6 +28,17 @@ import net.awan.pipelines.data.transport.PipelinesClient
|
||||
import net.awan.pipelines.data.transport.ProtocolException
|
||||
import net.awan.pipelines.data.transport.ServerUrl
|
||||
|
||||
/**
|
||||
* The default label this device reports: its model name, so other clients can
|
||||
* attribute a message to "Pixel 9 Pro XL". A build without a usable model (or a
|
||||
* local unit test where the framework stub has none) falls back to a generic
|
||||
* label rather than sending a blank one.
|
||||
*/
|
||||
private fun defaultClientLabel(): String {
|
||||
val model = runCatching { Build.MODEL }.getOrNull()?.trim().orEmpty()
|
||||
return model.ifBlank { "Android device" }
|
||||
}
|
||||
|
||||
/** Run history plus the server's aggregate usage statistics. */
|
||||
data class RunHistory(val runs: List<RunSummary>, val usage: UsageStats?)
|
||||
|
||||
@@ -38,6 +50,13 @@ data class RunHistory(val runs: List<RunSummary>, val usage: UsageStats?)
|
||||
class PipelinesRepository(
|
||||
private val client: PipelinesClient,
|
||||
private val settings: SettingsRepository,
|
||||
/**
|
||||
* The label this device sends with its prompts and approval answers, so every
|
||||
* other client can attribute a user message to the device that sent it and see
|
||||
* which device answered an approval. Defaults to the device model; injectable
|
||||
* so a unit test does not depend on the build.
|
||||
*/
|
||||
val clientLabel: String = defaultClientLabel(),
|
||||
) {
|
||||
val connectionState = client.state
|
||||
|
||||
@@ -241,9 +260,9 @@ class PipelinesRepository(
|
||||
// directly and never holds its credentials. ----
|
||||
|
||||
/**
|
||||
* Lists the sessions this server owns, with the `busy` flag the phone renders
|
||||
* read-only. The server already returns operator sessions only, so the app
|
||||
* never filters this list by ownership.
|
||||
* Lists the sessions this server owns. The server already returns operator
|
||||
* sessions only, so the app never filters this list by ownership; a session is
|
||||
* never marked read-only.
|
||||
*/
|
||||
suspend fun chatSessions(): List<ChatSession> =
|
||||
client.call(Message(type = Protocol.CHAT_SESSIONS)).chatSessions ?: emptyList()
|
||||
@@ -284,15 +303,29 @@ class PipelinesRepository(
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends one prompt with its attached file URIs; the server echoes an ack and
|
||||
* then pushes chat_event frames. The attachments travel only here, with the
|
||||
* prompt the operator actually sent — never on their own.
|
||||
* Attaches this connection to [sessionId]'s shared live stream, so it sees
|
||||
* every frame any client's turn produces — the other devices' prompts and the
|
||||
* turn's streaming output — and can answer a shared approval. Best-effort: an
|
||||
* older server that does not know `chat_subscribe` simply answers an error
|
||||
* frame, which the caller ignores while history still loads.
|
||||
*/
|
||||
suspend fun chatPrompt(sessionId: String, text: String, files: List<String> = emptyList()) {
|
||||
suspend fun chatSubscribe(sessionId: String) {
|
||||
if (sessionId.isBlank()) return
|
||||
client.call(ChatProtocol.subscribeRequest(sessionId))
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends one prompt with its attached file URIs; the server echoes an ack and
|
||||
* then pushes chat_event frames. The prompt carries this device's label so the
|
||||
* other clients can attribute it. The attachments travel only here, with the
|
||||
* prompt the operator actually sent — never on their own. Returns true when the
|
||||
* server queued the prompt behind an in-flight turn.
|
||||
*/
|
||||
suspend fun chatPrompt(sessionId: String, text: String, files: List<String> = emptyList()): Boolean {
|
||||
if (sessionId.isBlank()) throw ProtocolException("Select a chat session first.")
|
||||
val trimmed = text.trim()
|
||||
if (trimmed.isEmpty()) throw ProtocolException("Enter a message before sending.")
|
||||
client.call(ChatProtocol.promptRequest(sessionId, trimmed, files))
|
||||
return client.call(ChatProtocol.promptRequest(sessionId, trimmed, files, clientLabel)).chatQueued
|
||||
}
|
||||
|
||||
suspend fun chatInterrupt(sessionId: String) {
|
||||
@@ -304,7 +337,7 @@ class PipelinesRepository(
|
||||
if (sessionId.isBlank() || requestId.isBlank()) {
|
||||
throw ProtocolException("A pending permission request is required.")
|
||||
}
|
||||
client.call(ChatProtocol.replyRequest(sessionId, requestId, decision, message))
|
||||
client.call(ChatProtocol.replyRequest(sessionId, requestId, decision, message, clientLabel))
|
||||
}
|
||||
|
||||
private fun requireConfigured() {
|
||||
|
||||
@@ -30,8 +30,8 @@ data class ChatSession(
|
||||
@SerialName("created_at") val createdAt: Long = 0,
|
||||
@SerialName("updated_at") val updatedAt: Long = 0,
|
||||
// Another client holds the session, or the server itself owns it as an active
|
||||
// run: the phone shows it read-only instead of letting two clients write the
|
||||
// same conversation.
|
||||
// run. Kept for wire compatibility; the server no longer sets it, and a
|
||||
// session is never read-only for a client.
|
||||
val busy: Boolean = false,
|
||||
)
|
||||
|
||||
@@ -55,6 +55,10 @@ data class ChatPromptRequest(
|
||||
val model: String = "",
|
||||
val agent: String = "",
|
||||
val files: List<String> = emptyList(),
|
||||
// The sending device's human-readable label (a device name), so every other
|
||||
// client can attribute the message; the server sanitises it and falls back to
|
||||
// a generic label when it is blank.
|
||||
val client: String = "",
|
||||
)
|
||||
|
||||
/** One stored turn: a user turn is a single text part, an assistant turn holds text/reasoning/tool parts. */
|
||||
@@ -66,6 +70,9 @@ data class ChatMessage(
|
||||
val model: String = "",
|
||||
val agent: String = "",
|
||||
@SerialName("created_at") val createdAt: Long = 0,
|
||||
// The sending device's label on a user turn the server echoed, so a resumed
|
||||
// transcript still says who sent the message. Empty on an assistant turn.
|
||||
val client: String = "",
|
||||
val parts: List<ChatPart> = emptyList(),
|
||||
)
|
||||
|
||||
@@ -138,6 +145,9 @@ data class ChatEventFrame(
|
||||
val part: ChatPart? = null,
|
||||
val step: ChatStep? = null,
|
||||
val usage: ChatUsage? = null,
|
||||
// The sending device's label on a `user` frame (another client's prompt), so
|
||||
// the transcript can say who sent it. Empty on the agent's own frames.
|
||||
val client: String = "",
|
||||
)
|
||||
|
||||
@Serializable
|
||||
@@ -174,6 +184,9 @@ data class ChatPermissionFrame(
|
||||
val message: String = "",
|
||||
val resolved: Boolean = false,
|
||||
val decision: String = "",
|
||||
// The label of the client whose answer resolved the request, so every other
|
||||
// client can show which device answered.
|
||||
@SerialName("resolved_by") val resolvedBy: String = "",
|
||||
)
|
||||
|
||||
@Serializable
|
||||
@@ -189,6 +202,8 @@ data class ChatReplyRequest(
|
||||
@SerialName("request_id") val requestId: String = "",
|
||||
val decision: String = "",
|
||||
val message: String = "",
|
||||
// The answering device's label, recorded with the resolution.
|
||||
val client: String = "",
|
||||
)
|
||||
|
||||
/** Chat part/kind/state/reply constants, mirroring `internal/protocol/chat.go`. */
|
||||
@@ -207,6 +222,13 @@ object ChatProtocol {
|
||||
const val EVENT_STEP = "step"
|
||||
const val EVENT_USAGE = "usage"
|
||||
|
||||
/**
|
||||
* A prompt another client sent, echoed live to this client so it appears in
|
||||
* the transcript attributed to the sending device. The sender never receives
|
||||
* its own frame (it already has the message locally).
|
||||
*/
|
||||
const val EVENT_USER = "user"
|
||||
|
||||
const val STEP_STARTED = "started"
|
||||
const val STEP_ENDED = "ended"
|
||||
|
||||
@@ -241,10 +263,21 @@ object ChatProtocol {
|
||||
* shape a text-only prompt has always sent). Built here (not inline in the
|
||||
* repository) so production and its unit test share the one wire shape.
|
||||
*/
|
||||
fun promptRequest(sessionId: String, text: String, files: List<String> = emptyList()): Message =
|
||||
fun promptRequest(sessionId: String, text: String, files: List<String> = emptyList(), client: String = ""): Message =
|
||||
Message(
|
||||
type = Protocol.CHAT_PROMPT,
|
||||
chatPrompt = ChatPromptRequest(sessionId = sessionId, text = text, files = files),
|
||||
chatPrompt = ChatPromptRequest(sessionId = sessionId, text = text, files = files, client = client),
|
||||
)
|
||||
|
||||
/**
|
||||
* The `chat_subscribe` frame that attaches this connection to [sessionId]'s
|
||||
* shared live stream, so the client sees every frame any client's turn
|
||||
* produces. Built here so production and its unit test share the one shape.
|
||||
*/
|
||||
fun subscribeRequest(sessionId: String): Message =
|
||||
Message(
|
||||
type = Protocol.CHAT_SUBSCRIBE,
|
||||
chatSubscribe = ChatQuery(sessionId = sessionId),
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -261,7 +294,7 @@ object ChatProtocol {
|
||||
* inline in the repository) so the approval card's actions and their unit
|
||||
* test share the one wire shape.
|
||||
*/
|
||||
fun replyRequest(sessionId: String, requestId: String, decision: String, message: String = ""): Message =
|
||||
fun replyRequest(sessionId: String, requestId: String, decision: String, message: String = "", client: String = ""): Message =
|
||||
Message(
|
||||
type = Protocol.CHAT_REPLY,
|
||||
chatReply = ChatReplyRequest(
|
||||
@@ -269,6 +302,7 @@ object ChatProtocol {
|
||||
requestId = requestId,
|
||||
decision = decision,
|
||||
message = message,
|
||||
client = client,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -68,6 +68,9 @@ object Protocol {
|
||||
const val CHAT_MESSAGES = "chat_messages"
|
||||
const val CHAT_INTERRUPT = "chat_interrupt"
|
||||
const val CHAT_REPLY = "chat_reply"
|
||||
// Attaches this connection to one session's shared live stream, so every
|
||||
// client watching a session receives every frame any client's turn produces.
|
||||
const val CHAT_SUBSCRIBE = "chat_subscribe"
|
||||
// The operator's directory choices for a new chat (home first, then the
|
||||
// directories of previous operator sessions, most recently used first).
|
||||
const val CHAT_DIRECTORIES = "chat_directories"
|
||||
@@ -676,6 +679,11 @@ data class Message(
|
||||
@SerialName("chat_create") val chatCreate: ChatCreateRequest? = null,
|
||||
@SerialName("chat_query") val chatQuery: ChatQuery? = null,
|
||||
@SerialName("chat_prompt") val chatPrompt: ChatPromptRequest? = null,
|
||||
// A chat_prompt response with this set was accepted into the session's queue
|
||||
// because a turn is already in flight; the composer shows queued/steering
|
||||
// instead of blocking input.
|
||||
@SerialName("chat_queued") val chatQueued: Boolean = false,
|
||||
@SerialName("chat_subscribe") val chatSubscribe: ChatQuery? = null,
|
||||
@SerialName("chat_messages") val chatMessages: List<ChatMessage>? = null,
|
||||
@SerialName("chat_event") val chatEvent: ChatEventFrame? = null,
|
||||
@SerialName("chat_permission") val chatPermission: ChatPermissionFrame? = null,
|
||||
|
||||
@@ -1025,6 +1025,10 @@ class AppViewModel(
|
||||
|
||||
fun loadChatHistory(sessionId: String) {
|
||||
viewModelScope.launch {
|
||||
// Watch the session's shared stream so frames from any client's turn
|
||||
// arrive live. Best-effort: an older server answers an error frame,
|
||||
// which must not stop the history from loading.
|
||||
runCatching { repository.chatSubscribe(sessionId) }
|
||||
chatStore.historyLoading(sessionId)
|
||||
try {
|
||||
chatStore.history(sessionId, repository.chatMessages(sessionId, CHAT_HISTORY_LIMIT))
|
||||
@@ -1054,7 +1058,11 @@ class AppViewModel(
|
||||
chatStore.running(sessionId, true)
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
repository.chatPrompt(sessionId, text, attachmentFiles(attachments))
|
||||
val queued = repository.chatPrompt(sessionId, text, attachmentFiles(attachments))
|
||||
// The server accepted the prompt (queued or sent); a queued prompt
|
||||
// is one waiting behind an in-flight turn, and the composer says so
|
||||
// instead of blocking input.
|
||||
chatStore.setQueued(sessionId, queued)
|
||||
} catch (t: Throwable) {
|
||||
if (t is CancellationException) throw t
|
||||
val message = ErrorMessages.describe(t)
|
||||
@@ -1062,6 +1070,7 @@ class AppViewModel(
|
||||
chatStore.failed(sessionId, message)
|
||||
chatStore.restoreAttachments(sessionId, attachments, message)
|
||||
chatStore.running(sessionId, false)
|
||||
chatStore.setQueued(sessionId, false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,9 +51,9 @@ internal fun ChatComposer(
|
||||
}
|
||||
Surface(color = MaterialTheme.colorScheme.surfaceContainer) {
|
||||
Column(Modifier.fillMaxWidth().padding(CHAT_GUTTER)) {
|
||||
if (thread.readOnly) {
|
||||
if (thread.queued) {
|
||||
Text(
|
||||
text = "Another client holds this session; it is read-only here.",
|
||||
text = "Queued — it will send when the current turn finishes.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(bottom = CHAT_ITEM_GAP),
|
||||
@@ -65,14 +65,12 @@ internal fun ChatComposer(
|
||||
Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(CHAT_COMPOSER_GAP)) {
|
||||
IconButton(
|
||||
onClick = { picker.launch(arrayOf("*/*")) },
|
||||
enabled = !thread.readOnly,
|
||||
) {
|
||||
Icon(Icons.Default.AttachFile, contentDescription = "Attach file")
|
||||
}
|
||||
OutlinedTextField(
|
||||
value = thread.draft,
|
||||
onValueChange = onDraft,
|
||||
enabled = !thread.readOnly,
|
||||
placeholder = { Text("Message the agent…") },
|
||||
minLines = 1,
|
||||
maxLines = 6,
|
||||
|
||||
@@ -213,11 +213,7 @@ internal fun ChatConversationPane(
|
||||
onRetry = { vm.loadChatHistory(thread.sessionId) },
|
||||
)
|
||||
thread.messages.isEmpty() && !thread.running && approval == null -> EmptyState(
|
||||
message = if (thread.readOnly) {
|
||||
"This chat is read-only while another client holds the session."
|
||||
} else {
|
||||
"This chat has no messages yet. Ask something below."
|
||||
},
|
||||
message = "This chat has no messages yet. Ask something below.",
|
||||
)
|
||||
else -> ChatTranscript(
|
||||
thread = thread,
|
||||
|
||||
@@ -125,23 +125,17 @@ internal fun chatHeaderMeta(thread: ChatThread): String = listOfNotNull(
|
||||
private const val OPERATOR_TAG_LABEL = "Operator"
|
||||
|
||||
/**
|
||||
* The status a session row shows. A locally-running turn is reported as
|
||||
* `Running`; otherwise the server's `busy` flag is `Busy · read-only` (another
|
||||
* client holds it, so the composer is disabled), else `Idle`.
|
||||
*
|
||||
* This is the same precedence [ChatThread.readOnly] applies: a turn we started is
|
||||
* `Running` and writable, never the read-only the server's own `busy` flag alone
|
||||
* would imply.
|
||||
* The status a session row shows: `Running` while this client has a turn in
|
||||
* flight, else `Idle`. A session is never reported `Busy` or read-only because
|
||||
* another client is watching it — the server fans the stream out and accepts a
|
||||
* prompt from any client, so the session stays writable everywhere.
|
||||
*/
|
||||
internal fun sessionStatusLabel(session: ChatSession, runningLocally: Boolean): String =
|
||||
sessionStatusLabel(session.busy, runningLocally)
|
||||
sessionStatusLabel(runningLocally)
|
||||
|
||||
/** The status of a conversation from its own model flags (see [sessionStatusLabel]). */
|
||||
internal fun sessionStatusLabel(busy: Boolean, runningLocally: Boolean): String = when {
|
||||
runningLocally -> "Running"
|
||||
busy -> "Busy · read-only"
|
||||
else -> "Idle"
|
||||
}
|
||||
/** The status of a conversation from its own running flag (see [sessionStatusLabel]). */
|
||||
internal fun sessionStatusLabel(runningLocally: Boolean): String =
|
||||
if (runningLocally) "Running" else "Idle"
|
||||
|
||||
/**
|
||||
* The activity a session row signals beyond its open/tag/directory state. An
|
||||
@@ -183,7 +177,7 @@ internal data class ConversationHeader(
|
||||
internal fun conversationHeader(thread: ChatThread): ConversationHeader = ConversationHeader(
|
||||
title = sessionTitle(ChatSession(id = thread.sessionId, title = thread.title)),
|
||||
kind = sessionTagLabel(thread.tag),
|
||||
activity = sessionStatusLabel(thread.busy, thread.running),
|
||||
activity = sessionStatusLabel(thread.running),
|
||||
directory = thread.directory,
|
||||
model = thread.model,
|
||||
)
|
||||
|
||||
@@ -94,24 +94,26 @@ data class ChatThread(
|
||||
* settle in place optimistically and survives a chat switch.
|
||||
*/
|
||||
val permissionAnswer: String = "",
|
||||
/**
|
||||
* The last prompt this client sent was accepted into the session's queue
|
||||
* behind an in-flight turn (the server acknowledged it as queued), so the
|
||||
* composer can say so instead of blocking. Cleared as soon as the turn's
|
||||
* frames arrive or the thread settles.
|
||||
*/
|
||||
val queued: Boolean = false,
|
||||
) {
|
||||
/**
|
||||
* Read-only while another client holds the session: the composer must never
|
||||
* write to it. A turn we started ourselves keeps the session writable even
|
||||
* though the server reports it busy (the server owns it as our active run),
|
||||
* so the one rule here agrees with [sessionStatusLabel]'s `Running` case.
|
||||
* At least one attachment is flagged; the prompt must not be sent with it.
|
||||
*/
|
||||
val readOnly: Boolean get() = busy && !running
|
||||
|
||||
/** At least one attachment is flagged; the prompt must not be sent with it. */
|
||||
val hasAttachmentErrors: Boolean get() = attachments.any { it.error != null }
|
||||
|
||||
/**
|
||||
* Whether the composer's send action is allowed. A message with a flagged
|
||||
* attachment is never sent: the operator must remove or re-attach it first,
|
||||
* so the file is never silently dropped.
|
||||
* Whether the composer's send action is allowed. A session is never read-only:
|
||||
* another client may watch the same conversation without blocking this one. A
|
||||
* message with a flagged attachment is never sent, so the file is never
|
||||
* silently dropped.
|
||||
*/
|
||||
val canSend: Boolean get() = !readOnly && draft.isNotBlank() && !hasAttachmentErrors
|
||||
val canSend: Boolean get() = draft.isNotBlank() && !hasAttachmentErrors
|
||||
|
||||
/**
|
||||
* Non-negative elapsed time of an in-flight turn at [nowMillis], or 0 once it
|
||||
@@ -593,6 +595,13 @@ class ChatStore(
|
||||
|
||||
fun running(sessionId: String, running: Boolean) = update(sessionId) { setRunning(it, running) }
|
||||
|
||||
/**
|
||||
* Records that the operator's last prompt was accepted into the session's
|
||||
* queue (true) or sent immediately (false), so the composer can say "Queued"
|
||||
* while it waits for the in-flight turn without blocking input.
|
||||
*/
|
||||
fun setQueued(sessionId: String, queued: Boolean) = update(sessionId) { it.copy(queued = queued) }
|
||||
|
||||
/**
|
||||
* The stream resumed (the socket reconnected): every frame that was feeding an
|
||||
* in-flight turn is gone, so no thread keeps claiming to run until a fresh
|
||||
@@ -707,7 +716,11 @@ class ChatStore(
|
||||
if (frame.sessionId.isBlank()) return
|
||||
ensureThread(frame.sessionId)
|
||||
markUnread(frame.sessionId)
|
||||
// Any frame for the session means the turn has moved on, so a prompt we
|
||||
// had queued is no longer waiting.
|
||||
update(frame.sessionId) { if (it.queued) it.copy(queued = false) else it }
|
||||
when (frame.kind) {
|
||||
ChatProtocol.EVENT_USER -> applyRemoteUser(frame)
|
||||
ChatProtocol.PART_TEXT, ChatProtocol.PART_REASONING -> applyDelta(frame)
|
||||
ChatProtocol.PART_TOOL -> applyTool(frame)
|
||||
ChatProtocol.EVENT_STEP -> {
|
||||
@@ -718,6 +731,28 @@ class ChatStore(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Folds a user turn another client sent into the transcript, in place, once.
|
||||
* The server never echoes this client's own prompts, so the sender's own
|
||||
* message is never duplicated; the [ChatMessage.client] label says which
|
||||
* device sent it.
|
||||
*/
|
||||
private fun applyRemoteUser(frame: ChatEventFrame) {
|
||||
val text = frame.part?.text.orEmpty()
|
||||
if (frame.messageId.isEmpty() || text.isEmpty()) return
|
||||
update(frame.sessionId) { thread ->
|
||||
if (thread.messages.any { it.id == frame.messageId }) return@update thread
|
||||
val message = ChatMessage(
|
||||
id = frame.messageId,
|
||||
sessionId = frame.sessionId,
|
||||
role = ChatProtocol.ROLE_USER,
|
||||
client = frame.client,
|
||||
parts = listOf(ChatPart(type = ChatProtocol.PART_TEXT, text = text)),
|
||||
)
|
||||
thread.copy(messages = thread.messages + message)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a placeholder thread for a session that is not open, so a frame for
|
||||
* a background chat is kept instead of dropped. A no-op when it already exists.
|
||||
|
||||
@@ -352,6 +352,16 @@ private fun MessageItem(
|
||||
SelectionContainer {
|
||||
Column(Modifier.padding(CHAT_GUTTER)) {
|
||||
if (isUser) {
|
||||
// A user turn another device sent is attributed to it, so
|
||||
// the transcript says who sent the message. Our own
|
||||
// messages carry no label.
|
||||
if (message.client.isNotBlank()) {
|
||||
Text(
|
||||
text = message.client,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
UserParts(message.parts)
|
||||
} else {
|
||||
AssistantParts(
|
||||
|
||||
@@ -45,6 +45,45 @@ class ChatProtocolTest {
|
||||
assertTrue(!sessions[1].busy)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun chatMultiClientFieldsRoundTrip() {
|
||||
// The client label the prompt carries, the queued acknowledgement, the
|
||||
// subscribe request and the shared-answer fields of a permission frame.
|
||||
val prompt = PipelinesJson.decodeFromString(
|
||||
Message.serializer(),
|
||||
"""{"type":"chat_prompt","chat_prompt":{"session_id":"ses_1","text":"hi","client":"Pixel 9 Pro XL"}}""",
|
||||
)
|
||||
assertEquals("Pixel 9 Pro XL", prompt.chatPrompt!!.client)
|
||||
|
||||
val ack = PipelinesJson.decodeFromString(
|
||||
Message.serializer(),
|
||||
"""{"type":"chat_prompt","id":"a1","chat_queued":true}""",
|
||||
)
|
||||
assertTrue(ack.chatQueued)
|
||||
|
||||
val subscribe = PipelinesJson.decodeFromString(
|
||||
Message.serializer(),
|
||||
"""{"type":"chat_subscribe","chat_subscribe":{"session_id":"ses_1"}}""",
|
||||
)
|
||||
assertEquals(Protocol.CHAT_SUBSCRIBE, subscribe.type)
|
||||
assertEquals("ses_1", subscribe.chatSubscribe!!.sessionId)
|
||||
|
||||
val userFrame = PipelinesJson.decodeFromString(
|
||||
Message.serializer(),
|
||||
"""{"type":"chat_event","chat_event":{"session_id":"ses_1","message_id":"usr_1","kind":"user","client":"Pixel 10 Pro Fold","part":{"type":"text","text":"from the fold"}}}""",
|
||||
)
|
||||
assertEquals(ChatProtocol.EVENT_USER, userFrame.chatEvent!!.kind)
|
||||
assertEquals("Pixel 10 Pro Fold", userFrame.chatEvent!!.client)
|
||||
|
||||
val resolved = PipelinesJson.decodeFromString(
|
||||
Message.serializer(),
|
||||
"""{"type":"chat_permission","chat_permission":{"session_id":"ses_1","request_id":"req_1","resolved":true,"decision":"once","resolved_by":"Pixel 9"}}""",
|
||||
)
|
||||
assertTrue(resolved.chatPermission!!.resolved)
|
||||
assertEquals("once", resolved.chatPermission!!.decision)
|
||||
assertEquals("Pixel 9", resolved.chatPermission!!.resolvedBy)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun chatMessagesParseTextReasoningAndToolParts() {
|
||||
val json = """
|
||||
|
||||
@@ -65,12 +65,11 @@ class ChatFormatTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sessionStatusReportsRunningBusyAndIdle() {
|
||||
fun sessionStatusIsRunningOrIdleNeverReadOnly() {
|
||||
assertEquals("Running", sessionStatusLabel(ChatSession(id = "s"), runningLocally = true))
|
||||
assertEquals(
|
||||
"Busy · read-only",
|
||||
sessionStatusLabel(ChatSession(id = "s", busy = true), runningLocally = false),
|
||||
)
|
||||
// The server no longer marks a session Busy for another client, and a
|
||||
// session is never read-only: the stale flag cannot produce that label.
|
||||
assertEquals("Idle", sessionStatusLabel(ChatSession(id = "s", busy = true), runningLocally = false))
|
||||
assertEquals("Idle", sessionStatusLabel(ChatSession(id = "s"), runningLocally = false))
|
||||
}
|
||||
|
||||
|
||||
@@ -113,19 +113,15 @@ class MultiChatStateTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun busySessionIsReadOnlyAndCannotSend() {
|
||||
fun busySessionStaysWritable() {
|
||||
val store = ChatStore()
|
||||
// Another client watching the session never makes it read-only: the
|
||||
// server fans the stream out and accepts a prompt from any client.
|
||||
store.open(session("a", busy = true))
|
||||
store.draft("a", "unsent")
|
||||
val thread = store.value.thread("a")!!
|
||||
assertTrue(thread.readOnly)
|
||||
assertFalse(thread.canSend)
|
||||
|
||||
// The server can clear busy later; the chat then becomes writable again.
|
||||
store.sessionsLoaded(listOf(session("a", busy = false)))
|
||||
store.draft("a", "unsent")
|
||||
assertFalse(store.value.thread("a")!!.readOnly)
|
||||
assertTrue(store.value.thread("a")!!.canSend)
|
||||
assertTrue(thread.canSend)
|
||||
assertTrue(thread.busy)
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -192,10 +188,9 @@ class MultiChatStateTest {
|
||||
val store = ChatStore()
|
||||
store.open(session("a", busy = true))
|
||||
store.running("a", true)
|
||||
// Our own turn keeps the session writable even though the server reports it busy.
|
||||
// A turn in flight (ours or another client's) keeps the session writable.
|
||||
store.draft("a", "next prompt")
|
||||
val thread = store.value.thread("a")!!
|
||||
assertFalse(thread.readOnly)
|
||||
assertTrue(thread.canSend)
|
||||
}
|
||||
|
||||
@@ -229,4 +224,78 @@ class MultiChatStateTest {
|
||||
assertFalse(store.value.open.any { it.sessionId == "a" })
|
||||
assertTrue(store.value.open.any { it.sessionId == "b" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun remoteUserFrameIsFoldedOnceAndAttributed() {
|
||||
val store = ChatStore()
|
||||
store.open(session("a"))
|
||||
// The operator's own message, appended locally when sent.
|
||||
store.appendLocalUserMessage("a", "mine")
|
||||
// Another client's prompt arrives live, attributed to that device.
|
||||
val frame = ChatEventFrame(
|
||||
sessionId = "a",
|
||||
messageId = "usr_7",
|
||||
kind = ChatProtocol.EVENT_USER,
|
||||
client = "Pixel 10 Pro Fold",
|
||||
part = ChatPart(type = ChatProtocol.PART_TEXT, text = "from the fold"),
|
||||
)
|
||||
store.event(frame)
|
||||
val messages = store.value.thread("a")!!.messages
|
||||
assertEquals(2, messages.size)
|
||||
assertEquals("mine", messages[0].parts.single().text)
|
||||
assertEquals(ChatProtocol.ROLE_USER, messages[1].role)
|
||||
assertEquals("Pixel 10 Pro Fold", messages[1].client)
|
||||
assertEquals("from the fold", messages[1].parts.single().text)
|
||||
|
||||
// A replayed frame (e.g. after a reconnect) is folded once, not twice.
|
||||
store.event(frame)
|
||||
assertEquals(2, store.value.thread("a")!!.messages.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun remoteAnswerClearsTheApprovalCard() {
|
||||
val store = ChatStore()
|
||||
store.open(session("a"))
|
||||
store.permission(ChatPermissionFrame(sessionId = "a", requestId = "req_1", action = "bash"))
|
||||
val open = approvalCard(store.value.thread("a")!!.permission, store.value.thread("a")!!.permissionAnswer)!!
|
||||
assertTrue("the card is answerable while the request is open", open.actionable)
|
||||
|
||||
// Another client answered: the server pushes the resolved frame, which
|
||||
// clears this client's card and shows the outcome without ever disabling
|
||||
// it while the first answer was in flight.
|
||||
store.permission(
|
||||
ChatPermissionFrame(
|
||||
sessionId = "a",
|
||||
requestId = "req_1",
|
||||
action = "bash",
|
||||
resolved = true,
|
||||
decision = ChatProtocol.DECISION_ONCE,
|
||||
resolvedBy = "Pixel 9 Pro XL",
|
||||
),
|
||||
)
|
||||
val thread = store.value.thread("a")!!
|
||||
val cleared = approvalCard(thread.permission, thread.permissionAnswer)!!
|
||||
assertFalse("a resolved request offers no controls", cleared.actionable)
|
||||
assertEquals(ApprovalState.RESOLVED, cleared.state)
|
||||
assertEquals(ChatProtocol.DECISION_ONCE, cleared.decision)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun queuedPromptIsShownUntilTheTurnStreams() {
|
||||
val store = ChatStore()
|
||||
store.open(session("a"))
|
||||
store.setQueued("a", true)
|
||||
assertTrue(store.value.thread("a")!!.queued)
|
||||
// The queued turn's first frame means it is running, so the marker clears.
|
||||
store.event(
|
||||
ChatEventFrame(
|
||||
sessionId = "a",
|
||||
messageId = "m1",
|
||||
kind = ChatProtocol.PART_TEXT,
|
||||
delta = "hi",
|
||||
part = ChatPart(type = ChatProtocol.PART_TEXT, id = "m1#0"),
|
||||
),
|
||||
)
|
||||
assertFalse(store.value.thread("a")!!.queued)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user