From 378e0f78075830c1f38c9f802a9138adada59b75 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 12 Nov 2026 02:22:21 +0000 Subject: [PATCH 1/7] Group Android notifications by conversation Persist bounded chat and run message history so each server group renders as a stable MessagingStyle notification with shared summaries. Clear all entries in a thread on tap or dismissal and preserve existing alert channels and importance. --- app/android/app/build.gradle.kts | 2 + .../notify/NotificationDismissReceiver.kt | 14 +- .../notify/NotificationPresenter.kt | 190 ++++++++++++------ .../notify/NotificationThreads.kt | 167 +++++++++++++++ .../pipelines_app/notify/ThreadHistoryTest.kt | 118 +++++++++++ app/notes/notification-thread-grouping.md | 59 ++++++ 6 files changed, 485 insertions(+), 65 deletions(-) create mode 100644 app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationThreads.kt create mode 100644 app/android/app/src/test/kotlin/net/awan/pipelines_app/notify/ThreadHistoryTest.kt create mode 100644 app/notes/notification-thread-grouping.md diff --git a/app/android/app/build.gradle.kts b/app/android/app/build.gradle.kts index 5a16f7f3..054302b1 100644 --- a/app/android/app/build.gradle.kts +++ b/app/android/app/build.gradle.kts @@ -55,6 +55,8 @@ dependencies { coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.4") // The background notification socket (notify/NotificationService). implementation("com.squareup.okhttp3:okhttp:4.12.0") + // NotificationCompat.MessagingStyle for the per-chat/run conversations (notify/NotificationPresenter). + implementation("androidx.core:core:1.15.0") // JVM tests for the notification protocol and ledger (`gradlew :app:testDebugUnitTest`). testImplementation("junit:junit:4.13.2") // Android's org.json is a stub on the JVM; tests use the real implementation. diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationDismissReceiver.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationDismissReceiver.kt index 1d223c4d..f5bd713c 100644 --- a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationDismissReceiver.kt +++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationDismissReceiver.kt @@ -11,16 +11,20 @@ import android.content.Intent class NotificationDismissReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (intent.action != ACTION) return - val id = intent.getStringExtra(NotificationPresenter.EXTRA_NOTIFICATION_ID) ?: return - queueClear(context, id) + val ids = intent.getStringExtra(NotificationPresenter.EXTRA_NOTIFICATION_ID) ?: return + queueClear(context, ids) } companion object { const val ACTION = "net.awan.pipelines.notify.DISMISSED" - /** Shared by dismissals and taps (see MainActivity). */ - fun queueClear(context: Context, id: String) { - DeliveryLedger(ServiceSettings(context)).queueClear(listOf(id)) + /** + * Shared by dismissals and taps (see MainActivity). [ids] is one server + * id or several separated by newlines, as a thread notification carries. + */ + fun queueClear(context: Context, ids: String) { + DeliveryLedger(ServiceSettings(context)) + .queueClear(ids.split('\n').filter { it.isNotEmpty() }) // Only nudge a running service; a stopped one sends the queue on // its next connection. if (NotificationService.running != null) { diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationPresenter.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationPresenter.kt index 4db340a1..ae3f35e8 100644 --- a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationPresenter.kt +++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationPresenter.kt @@ -9,17 +9,22 @@ import android.content.Context import android.content.Intent import android.net.Uri import android.os.Build +import androidx.core.app.NotificationCompat +import androidx.core.app.Person import net.awan.pipelines_app.MainActivity import net.awan.pipelines_app.R /** - * Posts server notifications in the system tray: one channel per kind and - * priority (created lazily, grouped by kind), Android groups by the server's - * `group`, a tap opens the app at the `click` deep link, and a dismissal is - * reported back so the server clears it everywhere. + * Posts server notifications in the system tray. Each chat or run is one + * conversation notification (a MessagingStyle thread with the latest lines and + * the unread count), keyed by its server group. Thread notifications share a + * group per namespace, so Android bundles them under a summary ("N chats", + * "N runs"). A tap opens the app at the `click` deep link and clears the + * thread; a dismissal is reported back so the server clears it everywhere. */ class NotificationPresenter(private val context: Context) { private val manager = context.getSystemService(NotificationManager::class.java) + private val history = ThreadHistory(ServiceSettings(context)) fun connectionNotification(status: DeliveryStatus): Notification { ensureChannel(CONNECTION_CHANNEL, "Connection", NotificationManager.IMPORTANCE_MIN, null) @@ -42,7 +47,7 @@ class NotificationPresenter(private val context: Context) { .setOngoing(true) .setShowWhen(false) .setContentIntent(open) - .setCategory(Notification.CATEGORY_SERVICE) + .setCategory(NotificationCompat.CATEGORY_SERVICE) .build() } @@ -50,86 +55,143 @@ class NotificationPresenter(private val context: Context) { manager.notify(CONNECTION_ID, connectionNotification(status)) } + /** A notification without a group is posted on its own; otherwise it joins its thread. */ fun show(notification: ServerNotification) { - val id = DeliveryLedger.notificationId(notification.id) - val channel = channelFor(notification) - val title = notification.title.ifEmpty { "Pipelines" } - val builder = builder(channel) - .setSmallIcon(R.drawable.ic_stat_pipelines) - .setContentTitle(title) - .setContentText(notification.message) - .setStyle(Notification.BigTextStyle().bigText(notification.message)) - .setAutoCancel(true) - .setContentIntent(openIntent(notification, id)) - .setDeleteIntent(dismissIntent(notification.id, id)) - createdMillis(notification.createdAt)?.let { builder.setWhen(it).setShowWhen(true) } - if (notification.group.isNotEmpty()) builder.setGroup(notification.group) - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { - @Suppress("DEPRECATION") - builder.setPriority(effectivePriority(notification.kind, notification.priority) - 3) - } - manager.notify(id, builder.build()) - if (notification.group.isNotEmpty()) updateSummary(notification.group, channel) + if (notification.group.isEmpty()) return showAlone(notification) + val thread = notification.group + history.append(thread, NotificationThreads.entryOf(notification, System.currentTimeMillis())) + val channel = postThread(thread) ?: return + updateSummary(NotificationThreads.namespaceOf(thread), channel) } - /** Removes notifications cleared on this or another device. */ + /** Removes notifications cleared on this or another device, updating their threads. */ fun cancel(ids: Collection) { - val groups = mutableSetOf() - val active = manager.activeNotifications - for (id in ids) { - val notificationId = DeliveryLedger.notificationId(id) - active.firstOrNull { it.id == notificationId }?.notification?.group?.let(groups::add) - manager.cancel(notificationId) + for (id in ids) manager.cancel(DeliveryLedger.notificationId(id)) + val namespaces = mutableSetOf() + for (thread in history.remove(ids)) { + if (history.entries(thread).isEmpty()) manager.cancel(threadNotificationId(thread)) + else postThread(thread) + namespaces.add(NotificationThreads.namespaceOf(thread)) } - groups.forEach { updateSummary(it, null) } + namespaces.forEach { updateSummary(it, null) } } - /** Removes every server notification, keeping the connection one. */ + /** Removes every server notification and thread, keeping the connection one. */ fun cancelAll() { + history.clear() manager.activeNotifications .filter { it.id != CONNECTION_ID } .forEach { manager.cancel(it.tag, it.id) } } - private fun updateSummary(group: String, channel: String?) { - val summaryId = DeliveryLedger.notificationId("group:$group") - val members = manager.activeNotifications.count { - it.notification.group == group && it.id != summaryId + private fun showAlone(notification: ServerNotification) { + val id = DeliveryLedger.notificationId(notification.id) + val channel = channelFor(notification.kind, notification.priority) + val title = notification.title.ifEmpty { "Pipelines" } + val builder = builder(channel) + .setSmallIcon(R.drawable.ic_stat_pipelines) + .setContentTitle(title) + .setContentText(notification.message) + .setStyle(NotificationCompat.BigTextStyle().bigText(notification.message)) + .setAutoCancel(true) + .setContentIntent(openIntent(listOf(notification.id), notification.click, id)) + .setDeleteIntent(dismissIntent(listOf(notification.id), id)) + createdMillis(notification.createdAt)?.let { builder.setWhen(it).setShowWhen(true) } + applyLegacyPriority(builder, notification.kind, notification.priority) + manager.notify(id, builder.build()) + } + + /** + * Posts the thread's notification from its stored entries, so a restart or + * a partial clear rebuilds the same conversation. Returns the channel it + * used, or null when the thread has no entries left. + */ + private fun postThread(thread: String): String? { + val entries = history.entries(thread) + val latest = entries.lastOrNull() ?: return null + val channel = channelFor(latest.kind, latest.priority) + val id = threadNotificationId(thread) + val ids = entries.map { it.id } + val builder = builder(channel) + .setSmallIcon(R.drawable.ic_stat_pipelines) + .setNumber(entries.size) + .setGroup(NotificationThreads.groupKey(NotificationThreads.namespaceOf(thread))) + .setAutoCancel(true) + .setWhen(latest.whenMillis) + .setShowWhen(true) + .setContentIntent(openIntent(ids, latest.click, id)) + .setDeleteIntent(dismissIntent(ids, id)) + builder.setStyle(conversationStyle(entries)) + applyLegacyPriority(builder, latest.kind, latest.priority) + manager.notify(id, builder.build()) + return channel + } + + /** + * The shown lines of a thread, most recent last, as a messaging conversation. + * NotificationCompat renders it on every API level the app supports. + */ + private fun conversationStyle(entries: List): NotificationCompat.MessagingStyle { + val style = NotificationCompat.MessagingStyle(Person.Builder().setName("You").build()) + .setConversationTitle(entries.last().sender) + .setGroupConversation(false) + for (entry in entries.takeLast(SHOWN_LINES)) { + val sender = Person.Builder().setName(entry.sender).build() + style.addMessage(NotificationCompat.MessagingStyle.Message(entry.text, entry.whenMillis, sender)) } + return style + } + + /** + * Posts the namespace's group summary when two or more of its threads are + * shown, and removes it otherwise. A null [channel] reuses the summary's own. + */ + private fun updateSummary(namespace: String, channel: String?) { + val group = NotificationThreads.groupKey(namespace) + val summaryId = DeliveryLedger.notificationId("group:$group") + val active = manager.activeNotifications + val members = active.count { it.notification.group == group && it.id != summaryId } if (members < 2) { - if (members == 0) manager.cancel(summaryId) + manager.cancel(summaryId) return } - val existing = manager.activeNotifications.firstOrNull { it.id == summaryId } - val summaryChannel = channel ?: existing?.notification?.channelIdCompat() ?: return + val summaryChannel = channel + ?: active.firstOrNull { it.id == summaryId }?.notification?.channelIdCompat() + ?: return manager.notify( summaryId, builder(summaryChannel) .setSmallIcon(R.drawable.ic_stat_pipelines) .setContentTitle("Pipelines") - .setContentText("$members notifications") + .setContentText("$members $namespace") .setGroup(group) .setGroupSummary(true) - .setGroupAlertBehavior(Notification.GROUP_ALERT_CHILDREN) + .setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN) .setAutoCancel(true) .build(), ) } + private fun threadNotificationId(thread: String): Int = DeliveryLedger.notificationId("thread:$thread") + private fun Notification.channelIdCompat(): String? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) channelId else CONNECTION_CHANNEL - private fun openIntent(notification: ServerNotification, requestCode: Int): PendingIntent { + /** + * A tap opens the deep link and clears every id in [ids] (newline-separated + * in the extra), so the server marks the whole thread seen. + */ + private fun openIntent(ids: List, click: String, requestCode: Int): PendingIntent { val intent = Intent(context, MainActivity::class.java) .addFlags( Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP, ) - .putExtra(EXTRA_NOTIFICATION_ID, notification.id) + .putExtra(EXTRA_NOTIFICATION_ID, ids.joinToString("\n")) // Only the app's own links are routed; Flutter's deep-link handling // turns pipelines://run/ and pipelines://chat/ into a route. - val click = Uri.parse(notification.click) - if (click.scheme == "pipelines") intent.setAction(Intent.ACTION_VIEW).setData(click) + val link = Uri.parse(click) + if (link.scheme == "pipelines") intent.setAction(Intent.ACTION_VIEW).setData(link) return PendingIntent.getActivity( context, requestCode, @@ -138,25 +200,31 @@ class NotificationPresenter(private val context: Context) { ) } - private fun dismissIntent(serverId: String, requestCode: Int): PendingIntent = + private fun dismissIntent(serverIds: List, requestCode: Int): PendingIntent = PendingIntent.getBroadcast( context, requestCode, Intent(context, NotificationDismissReceiver::class.java) .setAction(NotificationDismissReceiver.ACTION) - .putExtra(EXTRA_NOTIFICATION_ID, serverId), + .putExtra(EXTRA_NOTIFICATION_ID, serverIds.joinToString("\n")), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, ) - private fun channelFor(notification: ServerNotification): String { - val kind = notification.kind.replace(Regex("[^A-Za-z0-9_.-]"), "_") - val priority = effectivePriority(kind, notification.priority) - val id = "pipelines.$kind.p$priority" + private fun applyLegacyPriority(builder: NotificationCompat.Builder, kind: String, priority: Int) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { + builder.setPriority(effectivePriority(kind, priority) - 3) + } + } + + private fun channelFor(kind: String, priorityValue: Int): String { + val kindName = kind.replace(Regex("[^A-Za-z0-9_.-]"), "_") + val priority = effectivePriority(kindName, priorityValue) + val id = "pipelines.$kindName.p$priority" if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - val groupId = "pipelines.kind.$kind" - manager.createNotificationChannelGroup(NotificationChannelGroup(groupId, kindLabel(kind))) - val name = if (priority == kindPriority(kind)) kindLabel(kind) - else "${kindLabel(kind)} (${priorityLabel(priority)})" + val groupId = "pipelines.kind.$kindName" + manager.createNotificationChannelGroup(NotificationChannelGroup(groupId, kindLabel(kindName))) + val name = if (priority == kindPriority(kindName)) kindLabel(kindName) + else "${kindLabel(kindName)} (${priorityLabel(priority)})" ensureChannel(id, name, importance(priority), groupId) } return id @@ -174,15 +242,17 @@ class NotificationPresenter(private val context: Context) { manager.createNotificationChannel(channel) } - @Suppress("DEPRECATION") - private fun builder(channel: String): Notification.Builder = - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) Notification.Builder(context, channel) - else Notification.Builder(context) + /** NotificationCompat ignores the channel below API 26, so one builder serves every level. */ + private fun builder(channel: String): NotificationCompat.Builder = + NotificationCompat.Builder(context, channel) companion object { const val CONNECTION_ID = 1 const val CONNECTION_CHANNEL = "pipelines.connection" + /** Holds the server id(s) a tap or dismissal clears, newline-separated. */ const val EXTRA_NOTIFICATION_ID = "net.awan.pipelines.notification_id" + /** Lines of a thread shown in its conversation; the unread count still counts all. */ + const val SHOWN_LINES = 5 private val KIND_LABELS = mapOf( "run_waiting" to "Run waiting for you", diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationThreads.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationThreads.kt new file mode 100644 index 00000000..dcbab0b5 --- /dev/null +++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationThreads.kt @@ -0,0 +1,167 @@ +package net.awan.pipelines_app.notify + +import org.json.JSONArray +import org.json.JSONObject + +/** + * One server notification kept as a message line in its thread (a chat or a + * run). [sender] names the line in the conversation view; [whenMillis] is the + * server's creation time, or the arrival time when the server sent none. + */ +data class ThreadEntry( + val id: String, + val kind: String, + val priority: Int, + val sender: String, + val text: String, + val click: String, + val whenMillis: Long, +) + +/** + * The per-thread message history that rebuilds a thread's notification after a + * service restart. Keyed by the server's `group` (`chat:` or `run:`); + * the count of entries is the unread count. Both the entries per thread and + * the threads kept are bounded, oldest first, so the store cannot grow without + * limit. Threads are kept in most-recently-active order. + */ +class ThreadHistory( + private val store: LedgerStore, + private val maxEntries: Int = MAX_ENTRIES, + private val maxThreads: Int = MAX_THREADS, +) { + /** The entries of [thread], oldest first; empty when the thread is unknown. */ + fun entries(thread: String): List = load()[thread].orEmpty() + + /** The thread holding [id], if any. */ + fun threadOf(id: String): String? = load().entries.firstOrNull { (_, list) -> + list.any { it.id == id } + }?.key + + /** Adds [entry] to the end of [thread], which becomes the most recent thread. */ + fun append(thread: String, entry: ThreadEntry) { + val threads = load() + val list = threads.remove(thread).orEmpty().toMutableList() + list.add(entry) + while (list.size > maxEntries) list.removeAt(0) + threads[thread] = list + while (threads.size > maxThreads) threads.remove(threads.keys.first()) + save(threads) + } + + /** + * Removes the entries with [ids]. Returns the threads whose entries changed; + * a thread left empty is dropped from the store. + */ + fun remove(ids: Collection): Set { + val wanted = ids.toSet() + val threads = load() + val touched = mutableSetOf() + for ((thread, list) in threads) { + if (list.removeAll { it.id in wanted }) touched.add(thread) + } + threads.entries.removeAll { it.value.isEmpty() } + if (touched.isNotEmpty()) save(threads) + return touched + } + + /** Forgets every thread, for example when the server changes. */ + fun clear() = store.putString(KEY, null) + + private fun load(): LinkedHashMap> { + val threads = LinkedHashMap>() + val raw = store.getString(KEY) ?: return threads + try { + val array = JSONArray(raw) + for (index in 0 until array.length()) { + val thread = array.getJSONObject(index) + val entries = thread.getJSONArray("entries") + threads[thread.getString("thread")] = (0 until entries.length()) + .map { entryFrom(entries.getJSONObject(it)) } + .toMutableList() + } + } catch (_: Exception) { + // A corrupt store starts again empty rather than failing every post. + threads.clear() + } + return threads + } + + private fun save(threads: Map>) { + if (threads.isEmpty()) return store.putString(KEY, null) + val array = JSONArray() + for ((thread, list) in threads) { + array.put( + JSONObject() + .put("thread", thread) + .put("entries", JSONArray(list.map(::entryJson))), + ) + } + store.putString(KEY, array.toString()) + } + + private fun entryJson(entry: ThreadEntry): JSONObject = JSONObject() + .put("id", entry.id) + .put("kind", entry.kind) + .put("priority", entry.priority) + .put("sender", entry.sender) + .put("text", entry.text) + .put("click", entry.click) + .put("whenMillis", entry.whenMillis) + + private fun entryFrom(json: JSONObject) = ThreadEntry( + id = json.optString("id"), + kind = json.optString("kind"), + priority = json.optInt("priority", 3), + sender = json.optString("sender"), + text = json.optString("text"), + click = json.optString("click"), + whenMillis = json.optLong("whenMillis"), + ) + + companion object { + const val KEY = "threads.history" + /** Unread entries kept per thread; the count shown is at most this. */ + const val MAX_ENTRIES = 100 + /** Threads kept; the oldest thread is forgotten first. */ + const val MAX_THREADS = 50 + } +} + +/** Naming rules for threads, shared by the presenter and its tests. */ +object NotificationThreads { + /** `chat:` and `run:` map to their own group; any other group is generic. */ + fun namespaceOf(group: String): String = when (group.substringBefore(':')) { + "chat" -> "chats" + "run" -> "runs" + else -> "notifications" + } + + /** The Android group key that bundles one namespace's thread notifications. */ + fun groupKey(namespace: String): String = "pipelines.$namespace" + + /** + * The chat's own title. The server titles a chat question or approval + * " needs your answer" (or "... needs your approval"); the chat title + * is what names the message. Run titles are used as they are. + */ + fun senderOf(kind: String, title: String): String { + val plain = title.trim() + if (!kind.startsWith("chat_")) return plain.ifEmpty { "Pipelines" } + return plain.removeSuffix(" needs your answer") + .removeSuffix(" needs your approval") + .trim() + .ifEmpty { "Chat" } + } + + /** Builds the entry for a server notification that arrived at [receivedMillis]. */ + fun entryOf(notification: ServerNotification, receivedMillis: Long): ThreadEntry = ThreadEntry( + id = notification.id, + kind = notification.kind, + priority = notification.priority, + sender = senderOf(notification.kind, notification.title), + text = notification.message.ifEmpty { notification.title }, + click = notification.click, + whenMillis = NotificationPresenter.createdMillis(notification.createdAt) ?: receivedMillis, + ) +} diff --git a/app/android/app/src/test/kotlin/net/awan/pipelines_app/notify/ThreadHistoryTest.kt b/app/android/app/src/test/kotlin/net/awan/pipelines_app/notify/ThreadHistoryTest.kt new file mode 100644 index 00000000..a487acb0 --- /dev/null +++ b/app/android/app/src/test/kotlin/net/awan/pipelines_app/notify/ThreadHistoryTest.kt @@ -0,0 +1,118 @@ +package net.awan.pipelines_app.notify + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class ThreadHistoryTest { + private class MemoryStore : LedgerStore { + val values = mutableMapOf() + override fun getString(key: String) = values[key] + override fun putString(key: String, value: String?) { + if (value == null) values.remove(key) else values[key] = value + } + } + + private fun entry(id: String, sender: String = "Chat A", text: String = "text $id") = ThreadEntry( + id = id, + kind = "chat_reply", + priority = 3, + sender = sender, + text = text, + click = "pipelines://chat/a", + whenMillis = 1_000L, + ) + + @Test + fun entriesAreKeptPerThreadInArrivalOrder() { + val history = ThreadHistory(MemoryStore()) + history.append("chat:a", entry("1")) + history.append("run:7", entry("2")) + history.append("chat:a", entry("3")) + assertEquals(listOf("1", "3"), history.entries("chat:a").map { it.id }) + assertEquals(listOf("2"), history.entries("run:7").map { it.id }) + assertEquals("chat:a", history.threadOf("3")) + assertNull(history.threadOf("missing")) + } + + @Test + fun entriesPerThreadAreBoundedOldestFirst() { + val history = ThreadHistory(MemoryStore(), maxEntries = 3) + (1..5).forEach { history.append("chat:a", entry("$it")) } + assertEquals(listOf("3", "4", "5"), history.entries("chat:a").map { it.id }) + } + + @Test + fun threadsAreBoundedAndTheOldestIsForgottenFirst() { + val history = ThreadHistory(MemoryStore(), maxThreads = 2) + history.append("chat:a", entry("1")) + history.append("chat:b", entry("2")) + history.append("chat:a", entry("3")) + history.append("chat:c", entry("4")) + assertTrue(history.entries("chat:b").isEmpty()) + assertEquals(listOf("1", "3"), history.entries("chat:a").map { it.id }) + assertEquals(listOf("4"), history.entries("chat:c").map { it.id }) + } + + @Test + fun historySurvivesANewInstanceOnTheSameStore() { + val store = MemoryStore() + ThreadHistory(store).append("chat:a", entry("1", sender = "Build bot", text = "done")) + val reopened = ThreadHistory(store).entries("chat:a") + assertEquals(1, reopened.size) + assertEquals("Build bot", reopened[0].sender) + assertEquals("done", reopened[0].text) + assertEquals("pipelines://chat/a", reopened[0].click) + assertEquals(1_000L, reopened[0].whenMillis) + } + + @Test + fun corruptStoreStartsEmpty() { + val store = MemoryStore().apply { values[ThreadHistory.KEY] = "not json" } + val history = ThreadHistory(store) + assertTrue(history.entries("chat:a").isEmpty()) + history.append("chat:a", entry("1")) + assertEquals(listOf("1"), history.entries("chat:a").map { it.id }) + } + + @Test + fun removeReturnsTouchedThreadsAndDropsEmptyOnes() { + val history = ThreadHistory(MemoryStore()) + history.append("chat:a", entry("1")) + history.append("chat:a", entry("2")) + history.append("run:7", entry("3")) + val touched = history.remove(listOf("1", "3", "unknown")) + assertEquals(setOf("chat:a", "run:7"), touched) + assertEquals(listOf("2"), history.entries("chat:a").map { it.id }) + assertTrue(history.entries("run:7").isEmpty()) + assertEquals(emptySet(), history.remove(listOf("unknown"))) + } + + @Test + fun clearForgetsEveryThread() { + val store = MemoryStore() + val history = ThreadHistory(store) + history.append("chat:a", entry("1")) + history.clear() + assertTrue(history.entries("chat:a").isEmpty()) + assertNull(store.getString(ThreadHistory.KEY)) + } + + @Test + fun chatTitlesDropTheQuestionSuffix() { + assertEquals("Deploy review", NotificationThreads.senderOf("chat_question", "Deploy review needs your answer")) + assertEquals("Deploy review", NotificationThreads.senderOf("chat_approval", "Deploy review needs your approval")) + assertEquals("Chat", NotificationThreads.senderOf("chat_question", "Chat needs your answer")) + assertEquals("Pipelines", NotificationThreads.senderOf("run_failed", " ")) + assertEquals("Run needs your decision", NotificationThreads.senderOf("run_waiting", "Run needs your decision")) + } + + @Test + fun namespacesSeparateChatsFromRuns() { + assertEquals("chats", NotificationThreads.namespaceOf("chat:s1")) + assertEquals("runs", NotificationThreads.namespaceOf("run:7")) + assertEquals("pipelines.chats", NotificationThreads.groupKey("chats")) + assertEquals("pipelines.runs", NotificationThreads.groupKey("runs")) + } +} diff --git a/app/notes/notification-thread-grouping.md b/app/notes/notification-thread-grouping.md new file mode 100644 index 00000000..04e39acf --- /dev/null +++ b/app/notes/notification-thread-grouping.md @@ -0,0 +1,59 @@ +# Android notifications grouped per chat and run + +## What changed (native service only; Flutter unchanged) + +- `android/.../notify/NotificationThreads.kt` (new): `ThreadEntry`, `ThreadHistory` + (bounded per-thread entries, bounded thread count, persisted through the + ledger's `LedgerStore` under `threads.history`), and naming helpers. Threads are + keyed by the server `group` (`chat:` or `run:`, per `docs/ntfy.md`). +- `NotificationPresenter.kt`: a grouped notification posts one conversation + notification per thread with a stable id (`thread:`), the latest 5 lines + (sender = chat title, run title for runs), the unread count (`setNumber`), and a + shared group per namespace (`pipelines.chats`, `pipelines.runs`). The group + summary reads "N chats" / "N runs" and is removed when fewer than two are shown. + Empty-group notifications keep the old standalone path. Channels and importance + are unchanged (`channelFor` takes kind and priority, same rules). +- `cancel(ids)` removes the cleared entries from history, drops a thread whose + entries are all gone, and reposts a partially cleared thread with its new count. + `cancelAll()` also clears the history. +- `NotificationDismissReceiver.kt`: `EXTRA_NOTIFICATION_ID` may carry several + newline-separated ids, so a tap or swipe on a thread clears every entry it shows. +- `NotificationService.kt`, the ledger and the protocol are untouched, so run 405's + reconnect/wakelock work is not affected. + +## Review fix (visit 2) + +- The thread notification now uses `androidx.core.app.NotificationCompat.MessagingStyle` + with `androidx.core.app.Person`, built by `NotificationCompat.Builder` (the presenter's + builder is compat throughout). Platform `Notification.MessagingStyle` and its API 28 + BigTextStyle fallback are gone; the compat style renders on every supported API level. +- `app/android/app/build.gradle.kts` adds `implementation("androidx.core:core:1.15.0")` + (already in the offline Gradle cache). + +## Focused results + +- Gradle 9.1.0 (cached), `--offline`, JDK 17 (`/opt/homebrew/opt/openjdk@17`): + `:app:testDebugUnitTest --tests 'net.awan.pipelines_app.notify.*'` → BUILD SUCCESSFUL. + JUnit XML: ThreadHistoryTest 9 tests / 0 failures, DeliveryLedgerTest 8 / 0, + NotificationProtocolTest 12 / 0. +- `tool/analyze.sh` (run from `app/`, after the Kotlin tests): clean, exit 0. +- No Flutter test was run: no Dart source changed. +- JDK 27 fails the Android JDK image transform (`jlink`) in a plugin, so builds here + need JDK 17 (environment issue, unrelated to this change). + +## Affected states + +- No Flutter UI changed. Native states not exercised on a device: a second chat + appearing as a thread, a summary at 2 and 1 chats, tap/swipe on a multi-line + thread, and the restart rebuild from persisted history. + +## Limitations + +- Android posting (MessagingStyle, summary, PendingIntent extras) is not covered by + JVM tests and has not been run on a device. Mobile behaviour is unverified. +- The new androidx.core dependency is compiled offline but not run through a full + APK build or on a device in this stage. +- History is capped: 100 unread entries per thread (count is capped there) and 50 + threads; the oldest thread is forgotten first when the cap is hit. +- Swipe-dismissal of a thread clears its ids on the server, but the local history + is trimmed only when the server confirms (`notifications_cleared`). From f3a469c356ff31d5b52c8bb239461c3fdb805228 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 12 Nov 2026 02:24:46 +0000 Subject: [PATCH 2/7] Animate chat composer while turns run Replace the running Stop button with an animated composer border and task spinner. Add Escape, slash-command, and touch-menu stopping paths with focused widget coverage, including reduced-motion behavior. --- .../conversation/chat_background_tasks.dart | 12 +- .../chat/conversation/chat_composer_bar.dart | 123 +++++++------ .../chat/conversation/chat_escape_stop.dart | 119 ++++++++++++ .../chat/conversation/chat_stop_icon.dart | 48 ----- .../chat/conversation/chat_task_spinner.dart | 71 +++++++ .../chat/conversation/chat_thread_view.dart | 21 ++- .../conversation/composer_running_border.dart | 146 +++++++++++++++ app/notes/composer-running-border.md | 60 ++++++ .../chat_composer_bar_state_test.dart | 25 +-- .../chat_composer_running_test.dart | 161 ++++++++++++++++ .../conversation/chat_escape_stop_test.dart | 169 +++++++++++++++++ .../conversation/chat_stop_icon_test.dart | 174 ------------------ .../conversation/chat_task_spinner_test.dart | 122 ++++++++++++ .../chat_thread_stop_menu_test.dart | 46 +++++ 14 files changed, 997 insertions(+), 300 deletions(-) create mode 100644 app/lib/features/chat/conversation/chat_escape_stop.dart delete mode 100644 app/lib/features/chat/conversation/chat_stop_icon.dart create mode 100644 app/lib/features/chat/conversation/chat_task_spinner.dart create mode 100644 app/lib/features/chat/conversation/composer_running_border.dart create mode 100644 app/notes/composer-running-border.md create mode 100644 app/test/features/chat/conversation/chat_composer_running_test.dart create mode 100644 app/test/features/chat/conversation/chat_escape_stop_test.dart delete mode 100644 app/test/features/chat/conversation/chat_stop_icon_test.dart create mode 100644 app/test/features/chat/conversation/chat_task_spinner_test.dart create mode 100644 app/test/features/chat/conversation/chat_thread_stop_menu_test.dart diff --git a/app/lib/features/chat/conversation/chat_background_tasks.dart b/app/lib/features/chat/conversation/chat_background_tasks.dart index 26e7e06b..e89fca54 100644 --- a/app/lib/features/chat/conversation/chat_background_tasks.dart +++ b/app/lib/features/chat/conversation/chat_background_tasks.dart @@ -5,6 +5,7 @@ import 'package:flutter/material.dart'; import '../../../core/api_gateway.dart'; import 'chat_background_tasks_controller.dart'; import 'chat_background_tasks_dialog.dart'; +import 'chat_task_spinner.dart'; /// Compact live task count: a quiet control inside the composer beside Send, /// shown only while tasks run. Details live only in its modal. @@ -146,10 +147,13 @@ class _ChatBackgroundTasksState extends State { visualDensity: VisualDensity.compact, ), onPressed: _open, - icon: Icon( - automationOnly ? Icons.schedule : Icons.layers_outlined, - size: 16, - ), + // The layers turn only while a task runs; automations stay still. + icon: automationOnly + ? const Icon(Icons.schedule, size: 16) + : ChatTaskSpinner( + spinning: count > 0, + child: const Icon(Icons.layers_outlined, size: 16), + ), label: caption(), ); return Padding( diff --git a/app/lib/features/chat/conversation/chat_composer_bar.dart b/app/lib/features/chat/conversation/chat_composer_bar.dart index 20510b4e..4dd8281a 100644 --- a/app/lib/features/chat/conversation/chat_composer_bar.dart +++ b/app/lib/features/chat/conversation/chat_composer_bar.dart @@ -5,7 +5,6 @@ import 'package:flutter/material.dart'; import '../../../ui/scale/ui_scale.dart'; import '../../../ui/motion/surface_visibility.dart'; -import 'chat_stop_icon.dart'; import 'package:flutter/services.dart'; import '../../../core/api_gateway.dart'; @@ -30,6 +29,7 @@ import 'composer_focus_request.dart'; import 'composer_focus_restore.dart'; import 'chat_bar_tint.dart'; import 'composer_focus_ring.dart'; +import 'composer_running_border.dart'; import '../shell/chat_shell_command.dart'; import '../shell/chat_shell_mode_indicator.dart'; @@ -70,8 +70,10 @@ double chatComposerBottomMargin([TargetPlatform? platform]) => ? kChatComposerDesktopBottomMargin : kChatComposerBottomMargin; -/// The single primary control's words while a turn is and is not running. +/// The single primary control's words. const String chatSendLabel = 'Send'; + +/// The chat's More-menu word for stopping a running turn. const String chatStopLabel = 'Stop'; /// The primary control's words while the draft is a `!` shell command. @@ -95,7 +97,8 @@ const String chatQueuedNotice = 'Queued — it will send when the current turn finishes.'; /// The foot of one conversation: a native multiline field and Send control, -/// with a separate Stop while a turn runs, driven by [ChatComposerController]. +/// driven by [ChatComposerController]. A running turn shows a travelling +/// border, not a stop control. /// /// The field owns only its [TextEditingController] and focus; the durable draft /// text lives in the composer controller, so a live transcript rebuild never @@ -153,7 +156,7 @@ class ChatComposerBar extends StatefulWidget { /// session (null) keeps those commands on the unavailable report. final ChatCommandActions? commands; - /// The thread controller's running bit; shows Stop without hiding Send. + /// The thread controller's running bit; shows the running border. final bool running; /// The host picker seam; production uses [hostChatAttachmentPicker]. @@ -400,6 +403,13 @@ class _ChatComposerBarState extends State { ); } + /// Whether a send completes the palette's highlighted row instead of running + /// the draft. A draft that already names a whole command (`/stop`) runs on + /// the first send; only a partial word is completed first. + bool _paletteCompletes() => + _paletteCommands().isNotEmpty && + chatCommandNamed(widget.composer.draft) == null; + /// The recorded commands matching the current draft while the palette is /// open. A dismissed or completed draft keeps its palette closed until the /// operator types something newer. @@ -512,8 +522,8 @@ class _ChatComposerBarState extends State { (keyboard.isShiftPressed || keyboard.isAltPressed)) { return; } - final commands = _paletteCommands(); - if (commands.isNotEmpty) { + if (_paletteCompletes()) { + final commands = _paletteCommands(); _completeCommand(commands[_selectedCommand % commands.length]); return; } @@ -943,10 +953,6 @@ class _ChatComposerBarState extends State { ), child: widget.backgroundTasks!, ), - if (widget.running) ...[ - _primary(context, stop: true), - const SizedBox(width: 4), - ], _primary(context), ], ), @@ -973,21 +979,41 @@ class _ChatComposerBarState extends State { /// the transcript, so the composer reads as a single input rather than a /// row of separate controls, and the conversation shows through it. While /// the field has focus a ring in the chat's colour runs along its edge. - Widget _pill(BuildContext context, Widget child) => ComposerFocusRing( - focus: _focus, - accent: chatFocusRingColor(context, widget.chatColor), - shape: _pillShape, - child: GlassPill( - key: const Key('chat-composer-pill'), - shape: _pillShape, - // The end controls keep the same gap from the pill's sides as from - // its bottom (and its top while the field is one line). - child: Padding( - padding: const EdgeInsets.all(GlassBarMetrics.fieldEdgeGap), - child: child, - ), - ), - ); + /// + /// While a turn runs a highlight travels around the same edge + /// ([ComposerRunningBorder]); it is mounted only for that time. + Widget _pill(BuildContext context, Widget child) { + final accent = chatFocusRingColor(context, widget.chatColor); + return Stack( + children: [ + ComposerFocusRing( + focus: _focus, + accent: accent, + shape: _pillShape, + child: GlassPill( + key: const Key('chat-composer-pill'), + shape: _pillShape, + // The end controls keep the same gap from the pill's sides as from + // its bottom (and its top while the field is one line). + child: Padding( + padding: const EdgeInsets.all(GlassBarMetrics.fieldEdgeGap), + child: child, + ), + ), + ), + if (widget.running) + Positioned.fill( + child: IgnorePointer( + child: ComposerRunningBorder( + shape: _pillShape, + primary: accent, + tertiary: Theme.of(context).colorScheme.tertiary, + ), + ), + ), + ], + ); + } /// The attach control: a host button that opens the picker, disabled when the /// host has no picker or one prompt is already awaiting its reply. @@ -1167,21 +1193,19 @@ class _ChatComposerBarState extends State { ); } - Widget _primary(BuildContext context, {bool stop = false}) { + /// The single primary control: Send (or Run command for a `!` draft). A + /// prompt sent while a turn runs takes the server's queued-prompt path; the + /// running turn is stopped by Escape twice, `/stop`, or the More menu. + Widget _primary(BuildContext context) { final composer = widget.composer; - final enabled = stop - ? !composer.stopping - : !_uploading && - !_shellStarting && - !composer.sending && - composer.draft.trim().isNotEmpty; + final enabled = + !_uploading && + !_shellStarting && + !composer.sending && + composer.draft.trim().isNotEmpty; void press() { - if (stop) { - unawaited(composer.stop()); - return; - } - final commands = _paletteCommands(); - if (commands.isNotEmpty) { + if (_paletteCompletes()) { + final commands = _paletteCommands(); _completeCommand(commands[_selectedCommand % commands.length]); } else if (chatDraftIsShell(composer.draft)) { unawaited(_runShellDraft()); @@ -1192,36 +1216,23 @@ class _ChatComposerBarState extends State { } } - // Sending while the turn runs uses the server's existing queued-prompt path. - // Stopping is always a separate, explicitly named action. - final label = stop - ? chatStopLabel - : chatDraftIsShell(composer.draft) + final label = chatDraftIsShell(composer.draft) ? chatRunShellLabel : chatSendLabel; - final key = Key(stop ? 'chat-composer-stop' : 'chat-composer-primary'); // A coloured chat's send button takes the chat's colour (its seeded - // primary, like the focus ring); stop stays the host's error red. + // primary, like the focus ring). final tinted = chatSchemeOf(context, widget.chatColor); - final scheme = Theme.of(context).colorScheme; return IconButton.filled( - key: key, + key: const Key('chat-composer-primary'), tooltip: label, - style: stop - ? IconButton.styleFrom( - backgroundColor: scheme.error, - foregroundColor: scheme.onError, - ) - : tinted == null + style: tinted == null ? null : IconButton.styleFrom( backgroundColor: tinted.primary, foregroundColor: tinted.onPrimary, ), onPressed: enabled ? press : null, - icon: stop - ? const ChatStopIcon(child: Icon(Icons.stop)) - : const Icon(Icons.arrow_upward), + icon: const Icon(Icons.arrow_upward), ); } diff --git a/app/lib/features/chat/conversation/chat_escape_stop.dart b/app/lib/features/chat/conversation/chat_escape_stop.dart new file mode 100644 index 00000000..ac9c0819 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_escape_stop.dart @@ -0,0 +1,119 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +/// The longest gap between two Escape presses that still stops a running turn. +const Duration chatEscapeStopWindow = Duration(seconds: 1); + +/// The hint shown after the first Escape while a turn runs. +const String chatEscapeStopHint = 'Press Esc again to stop'; + +/// Two presses of Escape stop a running turn: the first shows [chatEscapeStopHint] +/// and the second, inside [chatEscapeStopWindow], stops it. Pure timing, so the +/// clock is the caller's. +class ChatEscapeStopTracker { + DateTime? _firstAt; + + /// Records one plain Escape press at [now]. Returns true when it completes a + /// pair; a press that completes nothing starts a new pair. + bool press(DateTime now) { + final first = _firstAt; + if (first != null && now.difference(first) <= chatEscapeStopWindow) { + _firstAt = null; + return true; + } + _firstAt = now; + return false; + } + + /// Forgets a pending first press, for example once the turn has ended. + void reset() => _firstAt = null; +} + +/// Lets two presses of Escape stop the turn while focus is anywhere inside +/// [child] (the composer or the transcript). It only consumes Escape while +/// [running]; an idle chat, and any Escape a descendant already handled (a +/// command palette, a notice), pass through untouched. +class ChatEscapeStop extends StatefulWidget { + const ChatEscapeStop({ + super.key, + required this.running, + required this.onStop, + required this.child, + this.clock = DateTime.now, + }); + + final bool running; + + /// Stops the running turn; called on the second press. + final VoidCallback onStop; + + /// Injected time source, so tests control the window. + final DateTime Function() clock; + + final Widget child; + + @override + State createState() => _ChatEscapeStopState(); +} + +class _ChatEscapeStopState extends State { + final ChatEscapeStopTracker _tracker = ChatEscapeStopTracker(); + + @override + void didUpdateWidget(covariant ChatEscapeStop oldWidget) { + super.didUpdateWidget(oldWidget); + if (!widget.running) _tracker.reset(); + } + + KeyEventResult _onKeyEvent(FocusNode node, KeyEvent event) { + if (event.logicalKey != LogicalKeyboardKey.escape || !widget.running) { + return KeyEventResult.ignored; + } + final keyboard = HardwareKeyboard.instance; + if (keyboard.isControlPressed || + keyboard.isMetaPressed || + keyboard.isShiftPressed || + keyboard.isAltPressed) { + return KeyEventResult.ignored; + } + // Holding Escape is one press, and releasing it is not a press at all. + if (event is! KeyDownEvent) { + return event is KeyRepeatEvent + ? KeyEventResult.handled + : KeyEventResult.ignored; + } + if (_tracker.press(widget.clock())) { + _tracker.reset(); + _hideHint(); + widget.onStop(); + } else { + _showHint(); + } + return KeyEventResult.handled; + } + + void _showHint() { + final messenger = ScaffoldMessenger.maybeOf(context); + if (messenger == null) return; + messenger + ..hideCurrentSnackBar() + ..showSnackBar( + const SnackBar( + key: Key('chat-escape-stop-hint'), + content: Text(chatEscapeStopHint), + duration: chatEscapeStopWindow, + behavior: SnackBarBehavior.floating, + ), + ); + } + + void _hideHint() => ScaffoldMessenger.maybeOf(context)?.hideCurrentSnackBar(); + + @override + Widget build(BuildContext context) => Focus( + canRequestFocus: false, + skipTraversal: true, + onKeyEvent: _onKeyEvent, + child: widget.child, + ); +} diff --git a/app/lib/features/chat/conversation/chat_stop_icon.dart b/app/lib/features/chat/conversation/chat_stop_icon.dart deleted file mode 100644 index 1b17adf8..00000000 --- a/app/lib/features/chat/conversation/chat_stop_icon.dart +++ /dev/null @@ -1,48 +0,0 @@ -import 'package:flutter/widgets.dart'; - -/// Slow, continuous progress motion confined to the Stop glyph. The native -/// button, hit target and semantics never rotate. TickerMode pauses hidden UI. -class ChatStopIcon extends StatefulWidget { - const ChatStopIcon({super.key, required this.child}); - - final Widget child; - static const period = Duration(seconds: 8); - - @override - State createState() => _ChatStopIconState(); -} - -class _ChatStopIconState extends State - with SingleTickerProviderStateMixin { - late final _rotation = AnimationController( - vsync: this, - duration: ChatStopIcon.period, - ); - - @override - void didChangeDependencies() { - super.didChangeDependencies(); - if (MediaQuery.maybeDisableAnimationsOf(context) ?? false) { - _rotation.stop(); - _rotation.value = 0; - } else if (!_rotation.isAnimating) { - _rotation.repeat(); - } - } - - @override - void dispose() { - _rotation.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) => RepaintBoundary( - key: const Key('chat-stop-paint-boundary'), - child: RotationTransition( - key: const Key('chat-stop-rotation'), - turns: _rotation, - child: widget.child, - ), - ); -} diff --git a/app/lib/features/chat/conversation/chat_task_spinner.dart b/app/lib/features/chat/conversation/chat_task_spinner.dart new file mode 100644 index 00000000..ab5daa28 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_task_spinner.dart @@ -0,0 +1,71 @@ +import 'package:flutter/widgets.dart'; + +/// Turns [child] once every [period] while [spinning]; static otherwise. With +/// reduced motion it never turns. Hidden UI is silenced by TickerMode. +class ChatTaskSpinner extends StatefulWidget { + const ChatTaskSpinner({ + super.key, + required this.spinning, + required this.child, + }); + + final bool spinning; + final Widget child; + + /// One full turn while tasks run. + static const Duration period = Duration(milliseconds: 2500); + + @override + State createState() => _ChatTaskSpinnerState(); +} + +class _ChatTaskSpinnerState extends State + with SingleTickerProviderStateMixin { + late final AnimationController _turns = AnimationController( + vsync: this, + duration: ChatTaskSpinner.period, + ); + bool _reduced = false; + + @override + void initState() { + super.initState(); + _sync(); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _reduced = MediaQuery.maybeDisableAnimationsOf(context) ?? false; + _sync(); + } + + @override + void didUpdateWidget(covariant ChatTaskSpinner oldWidget) { + super.didUpdateWidget(oldWidget); + _sync(); + } + + void _sync() { + if (widget.spinning && !_reduced) { + if (!_turns.isAnimating) _turns.repeat(); + } else { + _turns + ..stop() + ..value = 0; + } + } + + @override + void dispose() { + _turns.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => RotationTransition( + key: const Key('chat-background-tasks-spinner'), + turns: _turns, + child: widget.child, + ); +} diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index 463a7dc2..202c60f2 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -42,6 +42,7 @@ import 'chat_background_tasks.dart'; import 'chat_command_actions.dart'; import 'chat_composer_bar.dart'; import 'chat_composer_controller.dart'; +import 'chat_escape_stop.dart'; import 'chat_delivery_indicator.dart'; import 'chat_draft_store.dart'; import 'chat_effort_control.dart'; @@ -1383,7 +1384,13 @@ class _ChatThreadViewState extends State { // The bar and the jump control float over the transcript and the // composer sits below it; the wheel over them scrolls it, as a page // scrolls under fixed bars. - final column = VerticalWheelForwarder(controller: _scroll, child: page); + // Two Escape presses stop a running turn while the conversation has + // the keyboard; the wheel over the page still scrolls it. + final column = ChatEscapeStop( + running: _controller.running, + onStop: _stopTurn, + child: VerticalWheelForwarder(controller: _scroll, child: page), + ); final wideFiles = _filesVisible && MediaQuery.sizeOf(context).width >= 700; _reportCenterStageFilesWidth(); @@ -1479,6 +1486,15 @@ class _ChatThreadViewState extends State { ], moreActions: [ ?widget.sidebarControl, + // Touch devices have no Escape key; the menu is their way to stop. + if (_controller.running) + ChatBarAction( + key: const Key('chat-thread-stop-menu'), + label: chatStopLabel, + identifier: 'chat-thread-stop', + onPressed: _stopTurn, + materialIcon: Icons.stop, + ), // A window's own title bar names the chat, and its narrow action // bar has no room for the title that opens the details. if (WindowScope.maybeOf(context) != null) @@ -1534,6 +1550,9 @@ class _ChatThreadViewState extends State { onChanged: widget.onModeChanged, ); + /// Stops the running turn, as the composer's `/stop` does. + void _stopTurn() => unawaited(_composer.stop()); + void _runShellFromMenu() => unawaited( runChatShellFromMenu(context, _shellRuns, showNotice: _showCommandNotice), ); diff --git a/app/lib/features/chat/conversation/composer_running_border.dart b/app/lib/features/chat/conversation/composer_running_border.dart new file mode 100644 index 00000000..07ecd216 --- /dev/null +++ b/app/lib/features/chat/conversation/composer_running_border.dart @@ -0,0 +1,146 @@ +import 'dart:math' as math; + +import 'package:flutter/material.dart'; + +/// The composer's "agent is working" edge: a soft highlight that travels once +/// around the pill's rounded border in [primary] and [tertiary], with a faint +/// glow beneath it. Mount it only while a turn runs; disposing it stops the +/// animation, so the border ends cleanly with the turn. +/// +/// With reduced motion (the platform's disable-animations setting) it draws +/// a static, evenly highlighted border instead and never ticks. +class ComposerRunningBorder extends StatefulWidget { + const ComposerRunningBorder({ + super.key, + required this.shape, + required this.primary, + required this.tertiary, + }); + + /// The pill's shape, so the highlight follows its edge. + final OutlinedBorder shape; + final Color primary; + final Color tertiary; + + /// One lap of the highlight around the border. + static const Duration period = Duration(seconds: 4); + + /// The stroke drawn just inside the pill's edge. + static const double strokeWidth = 2; + + /// The static border's opacity under reduced motion. + static const double staticOpacity = 0.7; + + @override + State createState() => _ComposerRunningBorderState(); +} + +class _ComposerRunningBorderState extends State + with SingleTickerProviderStateMixin { + late final AnimationController _lap = AnimationController( + vsync: this, + duration: ComposerRunningBorder.period, + ); + bool _reduced = false; + + @override + void initState() { + super.initState(); + _lap.repeat(); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + final reduced = MediaQuery.maybeDisableAnimationsOf(context) ?? false; + if (reduced == _reduced) return; + _reduced = reduced; + if (reduced) { + _lap.stop(); + } else { + _lap.repeat(); + } + } + + @override + void dispose() { + _lap.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => RepaintBoundary( + key: const Key('chat-composer-running-border'), + child: CustomPaint( + painter: _RunningBorderPainter( + shape: widget.shape, + primary: widget.primary, + tertiary: widget.tertiary, + lap: _reduced ? null : _lap, + ), + ), + ); +} + +class _RunningBorderPainter extends CustomPainter { + _RunningBorderPainter({ + required this.shape, + required this.primary, + required this.tertiary, + required this.lap, + }) : super(repaint: lap); + + final OutlinedBorder shape; + final Color primary; + final Color tertiary; + + /// The lap's progress, or null for the static reduced-motion border. + final Animation? lap; + + @override + void paint(Canvas canvas, Size size) { + if (size.isEmpty) return; + const width = ComposerRunningBorder.strokeWidth; + final rect = Offset.zero & size; + final path = shape.getOuterPath(rect.deflate(width / 2)); + final glow = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = width * 3 + ..maskFilter = const MaskFilter.blur(BlurStyle.normal, 4); + final line = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = width; + final progress = lap?.value; + if (progress == null) { + final solid = primary.withValues( + alpha: ComposerRunningBorder.staticOpacity, + ); + glow.color = solid.withValues(alpha: solid.a * .4); + line.color = solid; + } else { + final shader = SweepGradient( + colors: [ + primary.withValues(alpha: 0), + primary, + tertiary, + tertiary.withValues(alpha: 0), + primary.withValues(alpha: 0), + ], + stops: const [0, .12, .24, .38, 1], + transform: GradientRotation(progress * 2 * math.pi), + ).createShader(rect); + glow.shader = shader; + line.shader = shader; + } + canvas + ..drawPath(path, glow) + ..drawPath(path, line); + } + + @override + bool shouldRepaint(_RunningBorderPainter oldDelegate) => + oldDelegate.shape != shape || + oldDelegate.primary != primary || + oldDelegate.tertiary != tertiary || + oldDelegate.lap != lap; +} diff --git a/app/notes/composer-running-border.md b/app/notes/composer-running-border.md new file mode 100644 index 00000000..e46c7762 --- /dev/null +++ b/app/notes/composer-running-border.md @@ -0,0 +1,60 @@ +# Composer running state: border, Escape stop, tasks spinner + +## Changes + +- **Stop button removed.** The composer no longer shows a Stop control while a + turn runs; Send stays as before (queued/steered prompts unchanged). + `chat_stop_icon.dart` and its test are deleted (their only user was the button). +- **Running border.** `composer_running_border.dart` draws a sweep highlight + (theme primary = chat focus accent, tertiary) once around the pill's rounded + edge, 4 s per lap, with a faint blur glow. Mounted only while `running`, so + disposal stops the ticker when the turn ends. Reduced motion + (`MediaQuery.disableAnimations`) draws a static highlighted border and never ticks. +- **Escape stop.** `chat_escape_stop.dart` wraps the conversation column in + `chat_thread_view.dart`. Two plain Escape presses within 1 s stop a running turn + (`composer.stop()`); the first shows the snackbar "Press Esc again to stop". + Escape is consumed only while running; a descendant that handles Escape first + (command palette, notice) never counts. Held Escape counts as one press. +- **`/stop`.** Already existed (`chat_commands.dart`); unchanged. Typing `/stop` + and sending runs it on the first send. A partial word (`/sto`) still + completes the palette row first (`_paletteCompletes`). +- **More menu Stop.** `chat_thread_view.dart` adds a `Stop` item to the header's + More menu while a turn runs (`key chat-thread-stop-menu`). It is shown on every + platform, so touch devices without a keyboard can stop. +- **Tasks spinner.** `chat_task_spinner.dart` turns the layers icon once per + 2.5 s while at least one background task runs; static otherwise and under + reduced motion. Automation-only state keeps its static schedule icon. + +## Focused tests (memwatch, from app/) + +| Run | Paths | Result | +|---|---|---| +| 1 | `chat_escape_stop_test`, `chat_task_spinner_test`, `chat_composer_running_test`, `chat_thread_stop_menu_test`, `chat_composer_bar_state_test`, `chat_command_palette_test` | PASS 46/46 | +| 2 | Affected users: `chat_background_tasks_*` (4), `chat_thread_view_test`, `chat_thread_header_test`, `chat_composer_*` (bar, focus ring, enter, paste, attachment send, bottom margin), `chat_busy_resume`, `chat_response_pending`, `chat_live_reasoning`, `chat_floating_chrome`, `chat_server_queue`, `chat_delivery`, `composer_focus_restore`, `chat_unfocused_paste_routing`, `chat_floating_pane`, `chat_next_chat`, `chat_shell_composer`, `glass_bar` | PASS 169/169 | + +`tool/analyze.sh` (whole app): clean, exit 0. + +## Affected states (widget tests) + +- Running: no `chat-composer-stop`; Send present; border present; no interrupt sent. +- Turn ended: border gone; no animation ticker left. +- Reduced motion while running: border present, zero tickers. +- `/stop` (one send) interrupts; the notice shows. +- Esc once: hint shown, no interrupt. Esc twice (within 1 s): one interrupt. + Esc idle: nothing. Esc with palette open: palette closes and does not count. +- Transcript-level focus: Esc twice stops (`ChatEscapeStop` unit test). A + descendant-handled Esc never counts. +- More menu: Stop present while running and triggers the interrupt; absent when idle. +- Tasks icon: spins while a task runs; static at rest; reduced motion never turns. + +## Limitations + +- Not captured or reviewed visually (ui-review owns that). The border's colours + and glow strength in light and dark are unverified by eye. +- Escape stop is verified with synthetic key events in widget tests, not on a + physical keyboard or a device. Touch devices are covered by the More menu item + only; no device was tested. +- The More menu Stop item is shown on every platform while running, not only on + touch devices. +- A partial command word (`/sto`) still needs two sends (palette completes, then + runs); a fully typed `/stop` runs on one send. diff --git a/app/test/features/chat/conversation/chat_composer_bar_state_test.dart b/app/test/features/chat/conversation/chat_composer_bar_state_test.dart index d46a4ab1..7672994e 100644 --- a/app/test/features/chat/conversation/chat_composer_bar_state_test.dart +++ b/app/test/features/chat/conversation/chat_composer_bar_state_test.dart @@ -22,7 +22,7 @@ void main() { tearDown(() => gateway.close()); testWidgets( - 'Stop stays beside Send while running and interrupts this session', + 'a running turn shows no stop button; Send stays and nothing interrupts', (tester) async { await tester.pumpWidget( composerThread(gateway, newOperationId: nextOperation), @@ -35,18 +35,9 @@ void main() { await tester.pump(); expect(find.byTooltip(chatSendLabel), findsOneWidget); - expect(find.byTooltip(chatStopLabel), findsOneWidget); - final button = tester.widget( - find.byKey(const Key('chat-composer-stop')), - ); - final scheme = Theme.of( - tester.element(find.byKey(const Key('chat-composer-stop'))), - ).colorScheme; - expect(button.style?.backgroundColor?.resolve({}), scheme.error); - - await tester.tap(find.byKey(const Key('chat-composer-stop'))); - await tester.pumpAndSettle(); - expect(gateway.interruptBodies.single, {'session_id': 's'}); + expect(find.byKey(const Key('chat-composer-stop')), findsNothing); + expect(find.byTooltip(chatStopLabel), findsNothing); + expect(gateway.interruptBodies, isEmpty); expect(gateway.promptBodies, isEmpty); }, ); @@ -190,7 +181,7 @@ void main() { reply.complete({'chat_queued': true}); await tester.pumpAndSettle(); expect(fieldText(tester), 'Newer draft'); - expect(find.byKey(const Key('chat-composer-stop')), findsOneWidget); + expect(find.byKey(const Key('chat-composer-stop')), findsNothing); expect(gateway.interruptBodies, isEmpty); }, ); @@ -213,7 +204,7 @@ void main() { text, ); await tester.pump(); - expect(find.byKey(const Key('chat-composer-stop')), findsOneWidget); + expect(find.byKey(const Key('chat-composer-stop')), findsNothing); await tester.tap(find.byKey(const Key('chat-composer-primary'))); await tester.pumpAndSettle(); expect(fieldText(tester), ''); @@ -228,7 +219,7 @@ void main() { 'op/2', ]); expect(gateway.interruptBodies, isEmpty); - expect(find.byKey(const Key('chat-composer-stop')), findsOneWidget); + expect(find.byKey(const Key('chat-composer-stop')), findsNothing); }); testWidgets('the composer wraps at 320 logical px with 2x text', ( @@ -267,6 +258,6 @@ void main() { expect(tester.takeException(), isNull); expect(find.byKey(const Key('chat-composer')), findsOneWidget); expect(find.byKey(const Key('chat-composer-primary')), findsOneWidget); - expect(find.byKey(const Key('chat-composer-stop')), findsOneWidget); + expect(find.byKey(const Key('chat-composer-stop')), findsNothing); }); } diff --git a/app/test/features/chat/conversation/chat_composer_running_test.dart b/app/test/features/chat/conversation/chat_composer_running_test.dart new file mode 100644 index 00000000..d4ecb483 --- /dev/null +++ b/app/test/features/chat/conversation/chat_composer_running_test.dart @@ -0,0 +1,161 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_command_palette.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_composer_bar.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_escape_stop.dart'; + +import 'chat_composer_bar_fixtures.dart'; +import 'chat_thread_fixtures.dart'; + +Finder get _border => find.byKey(const Key('chat-composer-running-border')); + +Future _pumpThread(WidgetTester tester) async { + final gateway = ComposerBarGateway()..page = fixtureTurn(); + addTearDown(gateway.close); + await tester.pumpWidget( + composerThread(gateway, newOperationId: () => 'op/1'), + ); + await tester.pumpAndSettle(); + return gateway; +} + +/// Starts a turn. The border repeats for as long as it runs, so the test +/// settles by pumping a frame, never by waiting for the tree to go quiet. +Future _startTurn(WidgetTester tester, ComposerBarGateway gateway) async { + gateway.emitEvent(chatStepFrame('running')); + await tester.pump(); + await tester.pump(); +} + +Future _endTurn(WidgetTester tester, ComposerBarGateway gateway) async { + gateway.emitEvent(chatStepFrame('ended')); + await tester.pump(); + await tester.pump(); +} + +void _reducedMotion(bool reduced) => + TestWidgetsFlutterBinding.ensureInitialized() + .platformDispatcher + .accessibilityFeaturesTestValue = FakeAccessibilityFeatures( + disableAnimations: reduced, + ); + +void main() { + tearDown(() => _reducedMotion(false)); + + testWidgets('the border travels while a turn runs and is gone after it', ( + tester, + ) async { + _reducedMotion(false); + final gateway = await _pumpThread(tester); + expect(_border, findsNothing); + + await _startTurn(tester, gateway); + expect(_border, findsOneWidget); + expect(tester.binding.transientCallbackCount, greaterThan(0)); + + await _endTurn(tester, gateway); + expect(_border, findsNothing); + expect(tester.binding.transientCallbackCount, 0); + }); + + testWidgets('reduced motion draws the static border and never ticks', ( + tester, + ) async { + _reducedMotion(true); + final gateway = await _pumpThread(tester); + await _startTurn(tester, gateway); + expect(_border, findsOneWidget); + expect(tester.binding.transientCallbackCount, 0); + await tester.pump(const Duration(seconds: 2)); + expect(tester.binding.transientCallbackCount, 0); + }); + + testWidgets('no stop button appears while a turn runs', (tester) async { + final gateway = await _pumpThread(tester); + await _startTurn(tester, gateway); + expect(find.byKey(const Key('chat-composer-stop')), findsNothing); + expect(find.byKey(const Key('chat-composer-primary')), findsOneWidget); + }); + + testWidgets('/stop sent in the composer stops the running turn', ( + tester, + ) async { + final gateway = await _pumpThread(tester); + await _startTurn(tester, gateway); + await tester.enterText( + find.byKey(const Key('chat-composer-field')), + '/stop', + ); + await tester.pump(); + // A draft that already names /stop runs on the first send. + await tester.tap(find.byKey(const Key('chat-composer-primary'))); + await tester.pump(); + await tester.pump(); + expect(gateway.interruptBodies, [ + {'session_id': 's'}, + ]); + expect(gateway.promptBodies, isEmpty); + expect(find.text(chatStopCommandNotice), findsOneWidget); + }); + + testWidgets('two Escapes from the composer stop the turn', (tester) async { + final gateway = await _pumpThread(tester); + await _startTurn(tester, gateway); + await tester.tap(find.byKey(const Key('chat-composer-field'))); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pump(); + expect(gateway.interruptBodies, isEmpty); + expect(find.text(chatEscapeStopHint), findsOneWidget); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pump(); + await tester.pump(); + expect(gateway.interruptBodies, [ + {'session_id': 's'}, + ]); + }); + + testWidgets('a single Escape does not stop the turn', (tester) async { + final gateway = await _pumpThread(tester); + await _startTurn(tester, gateway); + await tester.tap(find.byKey(const Key('chat-composer-field'))); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pump(); + await tester.pump(const Duration(seconds: 2)); + expect(gateway.interruptBodies, isEmpty); + }); + + testWidgets('Escape closes the command palette first and does not count', ( + tester, + ) async { + final gateway = await _pumpThread(tester); + await _startTurn(tester, gateway); + await tester.enterText(find.byKey(const Key('chat-composer-field')), '/'); + await tester.pump(); + expect(find.byType(ChatCommandPalette), findsOneWidget); + + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pump(); + expect(find.byType(ChatCommandPalette), findsNothing); + expect(gateway.interruptBodies, isEmpty); + + // The palette's Escape was not the first of a pair; this one is. + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pump(); + expect(gateway.interruptBodies, isEmpty); + }); + + testWidgets('Escape does nothing while no turn runs', (tester) async { + final gateway = await _pumpThread(tester); + await tester.tap(find.byKey(const Key('chat-composer-field'))); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pump(); + expect(gateway.interruptBodies, isEmpty); + expect(find.text(chatEscapeStopHint), findsNothing); + }); +} diff --git a/app/test/features/chat/conversation/chat_escape_stop_test.dart b/app/test/features/chat/conversation/chat_escape_stop_test.dart new file mode 100644 index 00000000..170ce561 --- /dev/null +++ b/app/test/features/chat/conversation/chat_escape_stop_test.dart @@ -0,0 +1,169 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_escape_stop.dart'; + +void main() { + group('ChatEscapeStopTracker', () { + test('a second press inside the window completes a pair', () { + final tracker = ChatEscapeStopTracker(); + final start = DateTime(2026, 11, 12, 10); + expect(tracker.press(start), isFalse); + expect( + tracker.press(start.add(const Duration(milliseconds: 900))), + isTrue, + ); + }); + + test('a press after the window starts a new pair', () { + final tracker = ChatEscapeStopTracker(); + final start = DateTime(2026, 11, 12, 10); + expect(tracker.press(start), isFalse); + expect(tracker.press(start.add(const Duration(seconds: 2))), isFalse); + expect( + tracker.press(start.add(const Duration(seconds: 2, milliseconds: 500))), + isTrue, + ); + }); + + test('reset forgets a pending first press', () { + final tracker = ChatEscapeStopTracker(); + final start = DateTime(2026, 11, 12, 10); + tracker.press(start); + tracker.reset(); + expect( + tracker.press(start.add(const Duration(milliseconds: 100))), + isFalse, + ); + }); + }); + + group('ChatEscapeStop', () { + late DateTime now; + late int stops; + + setUp(() { + now = DateTime(2026, 11, 12, 10); + stops = 0; + }); + + Widget host({required bool running, Widget? child}) => MaterialApp( + home: Scaffold( + body: ChatEscapeStop( + running: running, + onStop: () => stops++, + clock: () => now, + child: child ?? const TextField(key: Key('field')), + ), + ), + ); + + testWidgets('a single Escape shows the hint and does not stop', ( + tester, + ) async { + await tester.pumpWidget(host(running: true)); + await tester.tap(find.byKey(const Key('field'))); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pump(); + expect(stops, 0); + expect(find.text(chatEscapeStopHint), findsOneWidget); + }); + + testWidgets('two Escapes within a second stop the turn once', ( + tester, + ) async { + await tester.pumpWidget(host(running: true)); + await tester.tap(find.byKey(const Key('field'))); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + now = now.add(const Duration(milliseconds: 400)); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pump(); + expect(stops, 1); + expect(find.text(chatEscapeStopHint), findsNothing); + }); + + testWidgets('two Escapes more than a second apart do not stop', ( + tester, + ) async { + await tester.pumpWidget(host(running: true)); + await tester.tap(find.byKey(const Key('field'))); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + now = now.add(const Duration(milliseconds: 1500)); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pump(); + expect(stops, 0); + }); + + testWidgets('an idle chat ignores Escape', (tester) async { + await tester.pumpWidget(host(running: false)); + await tester.tap(find.byKey(const Key('field'))); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pump(); + expect(stops, 0); + expect(find.text(chatEscapeStopHint), findsNothing); + }); + + testWidgets('focus on the transcript counts the same as the composer', ( + tester, + ) async { + await tester.pumpWidget( + host( + running: true, + child: const Focus( + autofocus: true, + child: SizedBox(width: 10, height: 10), + ), + ), + ); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pump(); + expect(stops, 1); + }); + + testWidgets('an Escape a descendant already handled never counts', ( + tester, + ) async { + await tester.pumpWidget( + host( + running: true, + child: Focus( + autofocus: true, + onKeyEvent: (_, event) => + event.logicalKey == LogicalKeyboardKey.escape + ? KeyEventResult.handled + : KeyEventResult.ignored, + child: const SizedBox(width: 10, height: 10), + ), + ), + ); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pump(); + expect(stops, 0); + expect(find.text(chatEscapeStopHint), findsNothing); + }); + + testWidgets('a held Escape is one press, not a pair', (tester) async { + await tester.pumpWidget( + host( + running: true, + child: const Focus( + autofocus: true, + child: SizedBox(width: 10, height: 10), + ), + ), + ); + await tester.pump(); + await tester.sendKeyDownEvent(LogicalKeyboardKey.escape); + await tester.sendKeyRepeatEvent(LogicalKeyboardKey.escape); + await tester.sendKeyRepeatEvent(LogicalKeyboardKey.escape); + await tester.sendKeyUpEvent(LogicalKeyboardKey.escape); + await tester.pump(); + expect(stops, 0); + }); + }); +} diff --git a/app/test/features/chat/conversation/chat_stop_icon_test.dart b/app/test/features/chat/conversation/chat_stop_icon_test.dart deleted file mode 100644 index fdd467f0..00000000 --- a/app/test/features/chat/conversation/chat_stop_icon_test.dart +++ /dev/null @@ -1,174 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:pipelines_app/features/chat/conversation/chat_stop_icon.dart'; -import 'package:pipelines_app/features/chat/conversation/chat_composer_bar.dart'; -import 'package:pipelines_app/features/chat/conversation/chat_composer_controller.dart'; -import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart'; -import 'package:pipelines_app/ui/motion/motion.dart'; - -import 'chat_composer_bar_fixtures.dart'; - -class _CountPaint extends CustomPainter { - _CountPaint(this.onPaint); - final VoidCallback onPaint; - @override - void paint(Canvas canvas, Size size) => onPaint(); - @override - bool shouldRepaint(_CountPaint oldDelegate) => false; -} - -void main() { - setUp(() { - TestWidgetsFlutterBinding.ensureInitialized() - .platformDispatcher - .accessibilityFeaturesTestValue = const FakeAccessibilityFeatures( - disableAnimations: false, - ); - }); - tearDown(() { - TestWidgetsFlutterBinding.ensureInitialized() - .platformDispatcher - .accessibilityFeaturesTestValue = const FakeAccessibilityFeatures( - disableAnimations: true, - ); - }); - - testWidgets('rotation repaints only the icon, not the surrounding chat', ( - tester, - ) async { - var paints = 0; - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: CustomPaint( - painter: _CountPaint(() => paints++), - child: const ChatStopIcon(child: Icon(Icons.stop)), - ), - ), - ), - ); - final before = paints; - await tester.pump(const Duration(seconds: 1)); - await tester.pump(const Duration(seconds: 1)); - expect(paints, before); - await tester.pumpWidget(const SizedBox.shrink()); - }); - - testWidgets( - 'Stop rotates linearly and continuously once every eight seconds', - (tester) async { - await tester.pumpWidget( - const MaterialApp( - home: Scaffold(body: ChatStopIcon(child: Icon(Icons.stop))), - ), - ); - RotationTransition rotation() => - tester.widget(find.byKey(const Key('chat-stop-rotation'))); - await tester.pump(const Duration(seconds: 2)); - expect(rotation().turns.value, closeTo(0.25, 0.001)); - await tester.pump(const Duration(seconds: 2)); - expect(rotation().turns.value, closeTo(0.5, 0.001)); - await tester.pump(const Duration(seconds: 8)); - expect(rotation().turns.value, closeTo(0.5, 0.001)); - await tester.pumpWidget(const SizedBox.shrink()); - expect(tester.binding.transientCallbackCount, 0); - }, - ); - - testWidgets('reduced motion stops/reset rotation and resumes when enabled', ( - tester, - ) async { - final reduce = ValueNotifier(true); - addTearDown(reduce.dispose); - await tester.pumpWidget( - MaterialApp( - home: ValueListenableBuilder( - valueListenable: reduce, - builder: (context, value, _) => MediaQuery( - data: MediaQuery.of(context).copyWith(disableAnimations: value), - child: const ChatStopIcon(child: Icon(Icons.stop)), - ), - ), - ), - ); - RotationTransition rotation() => - tester.widget(find.byKey(const Key('chat-stop-rotation'))); - await tester.pumpAndSettle(); - expect(rotation().turns.value, 0); - expect(tester.binding.transientCallbackCount, 0); - reduce.value = false; - await tester.pump(); - await tester.pump(const Duration(seconds: 1)); - expect(rotation().turns.value, closeTo(0.125, 0.001)); - reduce.value = true; - await tester.pumpAndSettle(); - expect(rotation().turns.value, 0); - expect(tester.binding.transientCallbackCount, 0); - }); - - testWidgets('TickerMode silences hidden Stop animation', (tester) async { - await tester.pumpWidget( - const MaterialApp( - home: TickerMode( - enabled: false, - child: ChatStopIcon(child: Icon(Icons.stop)), - ), - ), - ); - await tester.pumpAndSettle(); - expect(tester.binding.transientCallbackCount, 0); - await tester.pumpWidget(const SizedBox.shrink()); - }); - - testWidgets( - 'rotating Stop keeps its target and interrupt action; Send stays available', - (tester) async { - final gateway = ComposerBarGateway(); - addTearDown(gateway.close); - final composer = ChatComposerController( - gateway, - 's', - drafts: MemoryChatDraftStore(), - ); - addTearDown(composer.dispose); - final running = ValueNotifier(true); - addTearDown(running.dispose); - final bar = ValueListenableBuilder( - valueListenable: running, - builder: (_, value, _) => - ChatComposerBar(composer: composer, running: value), - ); - await tester.pumpWidget( - MaterialApp( - home: Scaffold(body: Center(child: bar)), - ), - ); - // The composer pops in first; Stop's target is measured once it has. - await tester.pump(Motion.tabEntranceDuration); - final stop = find.byKey(const Key('chat-composer-stop')); - final target = tester.getRect(stop); - await tester.pump(const Duration(seconds: 3)); - expect(tester.getRect(stop), target); - expect(find.byKey(const Key('chat-composer-primary')), findsOneWidget); - expect( - tester - .widget( - find.byKey(const Key('chat-stop-rotation')), - ) - .turns - .value, - greaterThan(0), - ); - await tester.tap(stop); - await tester.pump(); - await tester.pump(); - expect(gateway.interruptBodies, [ - {'session_id': 's'}, - ]); - running.value = false; - await tester.pumpAndSettle(); - expect(find.byType(ChatStopIcon), findsNothing); - expect(tester.binding.transientCallbackCount, 0); - }, - ); -} diff --git a/app/test/features/chat/conversation/chat_task_spinner_test.dart b/app/test/features/chat/conversation/chat_task_spinner_test.dart new file mode 100644 index 00000000..3a10dcb1 --- /dev/null +++ b/app/test/features/chat/conversation/chat_task_spinner_test.dart @@ -0,0 +1,122 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_background_tasks.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_task_spinner.dart'; + +RotationTransition _rotation(WidgetTester tester) => + tester.widget( + find.byKey(const Key('chat-background-tasks-spinner')), + ); + +Widget _spinner(bool spinning) => MaterialApp( + home: Scaffold( + body: ChatTaskSpinner( + spinning: spinning, + child: const Icon(Icons.layers_outlined, size: 16), + ), + ), +); + +void _reducedMotion(bool reduced) => + TestWidgetsFlutterBinding.ensureInitialized() + .platformDispatcher + .accessibilityFeaturesTestValue = FakeAccessibilityFeatures( + disableAnimations: reduced, + ); + +class _TasksGateway implements ApiGateway { + final _frames = StreamController.broadcast(); + List running = const []; + + @override + Stream get frames => _frames.stream; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + if (type == 'chat_shells') return {'chat_shells': running}; + if (type == 'chat_automations') { + return { + 'chat_automations': {'status': 'unavailable'}, + }; + } + return {}; + } + + void close() => _frames.close(); +} + +void main() { + tearDown(() => _reducedMotion(false)); + + testWidgets('turns once every period while spinning', (tester) async { + _reducedMotion(false); + await tester.pumpWidget(_spinner(true)); + expect(_rotation(tester).turns.value, 0); + await tester.pump(ChatTaskSpinner.period ~/ 4); + expect(_rotation(tester).turns.value, closeTo(0.25, 0.01)); + // Past one full lap the turn starts again from the top. + await tester.pump( + ChatTaskSpinner.period ~/ 4 * 3 + const Duration(milliseconds: 100), + ); + expect(_rotation(tester).turns.value, closeTo(0.04, 0.01)); + await tester.pumpWidget(const SizedBox.shrink()); + expect(tester.binding.transientCallbackCount, 0); + }); + + testWidgets('stays still when not spinning, and stops when it stops', ( + tester, + ) async { + _reducedMotion(false); + await tester.pumpWidget(_spinner(false)); + await tester.pump(const Duration(seconds: 2)); + expect(_rotation(tester).turns.value, 0); + expect(tester.binding.transientCallbackCount, 0); + + await tester.pumpWidget(_spinner(true)); + await tester.pump(const Duration(milliseconds: 625)); + expect(_rotation(tester).turns.value, greaterThan(0)); + + await tester.pumpWidget(_spinner(false)); + await tester.pump(); + expect(_rotation(tester).turns.value, 0); + await tester.pump(const Duration(seconds: 2)); + expect(_rotation(tester).turns.value, 0); + expect(tester.binding.transientCallbackCount, 0); + }); + + testWidgets('reduced motion keeps the icon static even while spinning', ( + tester, + ) async { + _reducedMotion(true); + await tester.pumpWidget(_spinner(true)); + await tester.pump(const Duration(seconds: 1)); + expect(_rotation(tester).turns.value, 0); + expect(tester.binding.transientCallbackCount, 0); + }); + + testWidgets('the tasks icon rotates only while a task runs', (tester) async { + _reducedMotion(false); + final gateway = _TasksGateway(); + addTearDown(gateway.close); + gateway.running = const [ + {'id': 'sh1', 'status': 'running', 'command': 'go test ./...'}, + ]; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ChatBackgroundTasks(gateway: gateway, sessionId: 's'), + ), + ), + ); + // The spinning icon repeats forever, so settle by pumping, never by waiting. + await tester.pump(); + await tester.pump(); + expect(find.text('1 task'), findsOneWidget); + final before = _rotation(tester).turns.value; + await tester.pump(const Duration(milliseconds: 300)); + expect(_rotation(tester).turns.value, greaterThan(before)); + }); +} diff --git a/app/test/features/chat/conversation/chat_thread_stop_menu_test.dart b/app/test/features/chat/conversation/chat_thread_stop_menu_test.dart new file mode 100644 index 00000000..b8128505 --- /dev/null +++ b/app/test/features/chat/conversation/chat_thread_stop_menu_test.dart @@ -0,0 +1,46 @@ +import 'package:flutter_test/flutter_test.dart'; + +import 'chat_composer_bar_fixtures.dart'; +import 'chat_thread_fixtures.dart'; + +void main() { + Future pumpThread(WidgetTester tester) async { + final gateway = ComposerBarGateway()..page = fixtureTurn(); + addTearDown(gateway.close); + await tester.pumpWidget( + composerThread(gateway, newOperationId: () => 'op/1'), + ); + await tester.pumpAndSettle(); + return gateway; + } + + testWidgets('the More menu offers Stop while a turn runs, for touch use', ( + tester, + ) async { + final gateway = await pumpThread(tester); + gateway.emitEvent(chatStepFrame('running')); + await tester.pump(); + await tester.pump(); + + await tester.tap(find.byTooltip('More actions').hitTestable().first); + await tester.pumpAndSettle(); + await tester.tap(find.text('Stop')); + await tester.pump(); + await tester.pump(); + + expect(gateway.interruptBodies, [ + {'session_id': 's'}, + ]); + expect(gateway.promptBodies, isEmpty); + }); + + testWidgets('the More menu has no Stop once the turn has ended', ( + tester, + ) async { + final gateway = await pumpThread(tester); + await tester.tap(find.byTooltip('More actions').hitTestable().first); + await tester.pumpAndSettle(); + expect(find.text('Stop'), findsNothing); + expect(gateway.interruptBodies, isEmpty); + }); +} From 746e23788d03e6b50a9ded2a68b465ec4702f5fd Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 12 Nov 2026 02:25:09 +0000 Subject: [PATCH 3/7] Mark chats seen after user interaction Prevent passive open, restored, or unfocused chats from clearing notifications. Track qualifying focused interactions and cover passive and active seen-watermark behavior with tests and notes. --- app/lib/application/pipelines_app.dart | 4 +- app/lib/features/chat/chat_pane_content.dart | 65 +-- .../conversation/chat_seen_interaction.dart | 128 ++++++ .../chat/ui/sessions/chat_seen_focus.dart | 46 +++ .../ui/sessions/chat_sessions_controller.dart | 98 ++++- .../ui/sessions/chat_sessions_screen.dart | 26 +- .../features/settings/server_connections.dart | 17 + app/notes/chat-seen-only-after-interaction.md | 98 +++++ .../chat_seen_interaction_test.dart | 220 ++++++++++ .../sessions/chat_seen_interaction_test.dart | 376 ++++++++++++++++++ 10 files changed, 1013 insertions(+), 65 deletions(-) create mode 100644 app/lib/features/chat/conversation/chat_seen_interaction.dart create mode 100644 app/lib/features/chat/ui/sessions/chat_seen_focus.dart create mode 100644 app/notes/chat-seen-only-after-interaction.md create mode 100644 app/test/features/chat/conversation/chat_seen_interaction_test.dart create mode 100644 app/test/features/chat/ui/sessions/chat_seen_interaction_test.dart diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart index f3a52b45..88fbd3ef 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -374,7 +374,9 @@ class _PipelinesAppState extends State }, sessionTitle: _chatSessionTitle, openChat: (id) { - if (mounted) _delegate.goTo(AppRoute.chatSession(id)); + if (!mounted) return; + widget.servers?.requestChatOpen(id); + _delegate.goTo(AppRoute.chatSession(id)); }, bridge: _notifications.bridge, ); diff --git a/app/lib/features/chat/chat_pane_content.dart b/app/lib/features/chat/chat_pane_content.dart index 247dce96..b8d92bb8 100644 --- a/app/lib/features/chat/chat_pane_content.dart +++ b/app/lib/features/chat/chat_pane_content.dart @@ -5,6 +5,7 @@ import '../../core/servers/server_context.dart'; import '../../shell/destination.dart'; import '../../shell/detail_page.dart'; import 'chat_runtime.dart'; +import 'conversation/chat_seen_interaction.dart'; import 'conversation/chat_thread_view.dart'; import 'conversation/composer_focus_request.dart'; import 'workspace/chat_pane_commands.dart'; @@ -79,36 +80,42 @@ Widget buildChatPaneContent({ child: ServerContext.forServer( context, runtime.serverIdFor(sessionId), - ChatThreadView( - key: ValueKey('chat-session-$sessionId'), - gateway: runtime.gatewayFor(sessionId), + ChatSeenInteraction( sessionId: sessionId, - title: '${row?['title'] ?? ''}'.trim(), - session: row, - syncToken: placement.syncToken, - scrollPositions: runtime.scrollPositions, - transcripts: runtime.transcripts, - initialNotice: start != null && start.id == sessionId - ? start.notice - : null, - onBack: placement.onBack, - onModelChanged: (applied) => - runtime.modelChanged(sessionId, applied), - onModeChanged: (mode, name) => - runtime.acceptMode(sessionId, mode, name), - onEffortChanged: (state) => runtime.acceptEffort(sessionId, state), - onNewSession: placement.onNewSession, - onSessionRenamed: (title) => runtime.acceptRename(sessionId, title), - onSessionClosed: placement.onSessionClosed, - onColorSelected: (color) => - runtime.sessions.setColor(sessionId, color), - onNextChat: placement.onNextChat, - useNativeBack: placement.useNativeBack, - pasteTarget: placement.pasteTarget, - ownsPasteWhenFocused: placement.ownsPasteWhenFocused, - showBackButton: placement.showBackButton, - paneControls: placement.paneControls?.call(context) ?? const [], - paneCommands: placement.paneCommands, + onInteract: () => runtime.sessions.reportInteraction(sessionId), + child: ChatThreadView( + key: ValueKey('chat-session-$sessionId'), + gateway: runtime.gatewayFor(sessionId), + sessionId: sessionId, + title: '${row?['title'] ?? ''}'.trim(), + session: row, + syncToken: placement.syncToken, + scrollPositions: runtime.scrollPositions, + transcripts: runtime.transcripts, + initialNotice: start != null && start.id == sessionId + ? start.notice + : null, + onBack: placement.onBack, + onModelChanged: (applied) => + runtime.modelChanged(sessionId, applied), + onModeChanged: (mode, name) => + runtime.acceptMode(sessionId, mode, name), + onEffortChanged: (state) => + runtime.acceptEffort(sessionId, state), + onNewSession: placement.onNewSession, + onSessionRenamed: (title) => + runtime.acceptRename(sessionId, title), + onSessionClosed: placement.onSessionClosed, + onColorSelected: (color) => + runtime.sessions.setColor(sessionId, color), + onNextChat: placement.onNextChat, + useNativeBack: placement.useNativeBack, + pasteTarget: placement.pasteTarget, + ownsPasteWhenFocused: placement.ownsPasteWhenFocused, + showBackButton: placement.showBackButton, + paneControls: placement.paneControls?.call(context) ?? const [], + paneCommands: placement.paneCommands, + ), ), ), ); diff --git a/app/lib/features/chat/conversation/chat_seen_interaction.dart b/app/lib/features/chat/conversation/chat_seen_interaction.dart new file mode 100644 index 00000000..c8c340c3 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_seen_interaction.dart @@ -0,0 +1,128 @@ +import 'package:flutter/rendering.dart' show ScrollDirection; +import 'package:flutter/services.dart' + show HardwareKeyboard, KeyDownEvent, KeyEvent; +import 'package:flutter/widgets.dart'; + +import '../../../core/servers/server_context.dart'; +import '../../settings/server_connections.dart'; + +/// Reports the user's own actions in one open chat, so the chat can be read. +/// +/// Counted: a pointer press anywhere in the pane (click or tap, which also +/// makes it the active pane), a user-driven scroll of its transcript, a key +/// press while focus is inside it (typing, Tab), focus arriving in it from a +/// key press outside it (Tab into the pane), and a notification tap that +/// opened it. Showing the pane, rebuilding it, receiving content, or focus +/// moved in code with no key press does not report anything. [onInteract] +/// decides whether the window is focused. +class ChatSeenInteraction extends StatefulWidget { + const ChatSeenInteraction({ + super.key, + required this.sessionId, + required this.onInteract, + required this.child, + }); + + final String sessionId; + final VoidCallback onInteract; + final Widget child; + + @override + State createState() => _ChatSeenInteractionState(); +} + +class _ChatSeenInteractionState extends State { + ServerConnections? _connections; + + /// True from a key-down until the next frame. Focus changes are applied in a + /// microtask queued by the key dispatch, which runs before that frame, so a + /// focus change caused by the key sees the flag. A focus change with no key + /// press (restoration, code-driven focus) never does. + bool _keyDownInProgress = false; + + @override + void initState() { + super.initState(); + HardwareKeyboard.instance.addHandler(_onKeyEvent); + } + + bool _onKeyEvent(KeyEvent event) { + if (event is KeyDownEvent && !_keyDownInProgress) { + _keyDownInProgress = true; + WidgetsBinding.instance.addPostFrameCallback((_) { + _keyDownInProgress = false; + }); + WidgetsBinding.instance.scheduleFrame(); + } + return false; + } + + void _onFocusChange(bool hasFocus) { + if (hasFocus && _keyDownInProgress) widget.onInteract(); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + final connections = ServerContext.maybeOf(context)?.notifier; + if (identical(connections, _connections)) return; + _connections?.removeListener(_takeNotificationOpen); + _connections = connections; + connections?.addListener(_takeNotificationOpen); + _takeNotificationOpen(); + } + + @override + void didUpdateWidget(covariant ChatSeenInteraction oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.sessionId != widget.sessionId) _takeNotificationOpen(); + } + + @override + void dispose() { + HardwareKeyboard.instance.removeHandler(_onKeyEvent); + _connections?.removeListener(_takeNotificationOpen); + super.dispose(); + } + + /// A notification tap that named this chat is the user opening it. It is + /// reported after the frame, so the list has taken the chat as active first. + void _takeNotificationOpen() { + final connections = _connections; + if (connections == null || + !connections.takeChatOpenIntent(widget.sessionId)) { + return; + } + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) widget.onInteract(); + }); + } + + static bool _userScrolled(ScrollNotification notification) => + (notification is UserScrollNotification && + notification.direction != ScrollDirection.idle) || + (notification is ScrollStartNotification && + notification.dragDetails != null); + + @override + Widget build(BuildContext context) => Listener( + behavior: HitTestBehavior.translucent, + onPointerDown: (_) => widget.onInteract(), + child: NotificationListener( + onNotification: (notification) { + if (_userScrolled(notification)) widget.onInteract(); + return false; + }, + child: Focus( + canRequestFocus: false, + skipTraversal: true, + onFocusChange: _onFocusChange, + onKeyEvent: (node, event) { + if (event is KeyDownEvent) widget.onInteract(); + return KeyEventResult.ignored; + }, + child: widget.child, + ), + ), + ); +} diff --git a/app/lib/features/chat/ui/sessions/chat_seen_focus.dart b/app/lib/features/chat/ui/sessions/chat_seen_focus.dart new file mode 100644 index 00000000..76c5b52f --- /dev/null +++ b/app/lib/features/chat/ui/sessions/chat_seen_focus.dart @@ -0,0 +1,46 @@ +import 'package:flutter/widgets.dart'; + +/// Whether the app window is focused and visible: the only state in which a +/// chat can be read. A backgrounded or unfocused window never marks a chat +/// seen, so a reply that arrives there stays New until the user interacts. +class ChatSeenFocus extends ChangeNotifier { + ChatSeenFocus({bool focused = true}) { + _focused = focused; + } + + /// The app's own focus, driven by the framework's lifecycle state. A null + /// lifecycle state (before the first report) counts as focused, so a window + /// that starts visible is not stuck unread. + static final ChatSeenFocus app = ChatSeenFocus._observingApp(); + + factory ChatSeenFocus._observingApp() { + final focus = ChatSeenFocus( + focused: _isFocusedState(WidgetsBinding.instance.lifecycleState), + ); + WidgetsBinding.instance.addObserver(_LifecycleFocus(focus)); + return focus; + } + + late bool _focused; + bool get focused => _focused; + + set focused(bool value) { + if (value == _focused) return; + _focused = value; + notifyListeners(); + } + + static bool _isFocusedState(AppLifecycleState? state) => + state == null || state == AppLifecycleState.resumed; +} + +class _LifecycleFocus with WidgetsBindingObserver { + _LifecycleFocus(this._focus); + + final ChatSeenFocus _focus; + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + _focus.focused = ChatSeenFocus._isFocusedState(state); + } +} diff --git a/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart b/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart index 831bbb18..41c4366d 100644 --- a/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart +++ b/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart @@ -12,6 +12,7 @@ import '../../../attention/runtime/attention_ack_sync.dart'; import '../../data/chat_repository.dart'; import '../../domain/chat_list_activity.dart'; import '../../domain/chat_sessions.dart'; +import 'chat_seen_focus.dart'; import 'chat_session_local.dart'; import 'session_attention.dart'; @@ -23,8 +24,10 @@ import 'session_attention.dart'; /// read watermark are local. /// /// With an [AttentionAckSync] (bound to the gateway by the app, or passed in), -/// reading is shared: opening a chat acknowledges a `chat_seen` watermark to -/// every device, and a watermark acknowledged elsewhere that is newer than this +/// reading is shared: a user interaction with a chat (opening it, or acting in +/// its pane while the window is focused, see [reportInteraction]) acknowledges +/// a `chat_seen` watermark to every device. Being visible, restored or +/// receiving a reply never does. A watermark acknowledged elsewhere that is newer than this /// device's own clears the chat's New badge here. The local store remains the /// offline cache of both. class ChatSessionsController extends ChangeNotifier { @@ -33,8 +36,10 @@ class ChatSessionsController extends ChangeNotifier { ChatSessionLocalStore? localStore, AttentionAckSync? ackSync, int Function()? nowMillis, + ChatSeenFocus? seenFocus, this.activeAckDelay = const Duration(milliseconds: 1500), - }) : _localStore = + }) : _focus = seenFocus ?? ChatSeenFocus.app, + _localStore = localStore ?? (repository.gateway is FederatedChatGateway ? FederatedChatSessionLocalStore( @@ -46,12 +51,27 @@ class ChatSessionsController extends ChangeNotifier { ), )), _nowMillis = nowMillis ?? _wallClockMillis { + _focus.addListener(_focusChanged); _listenFrames(); _bindAckSync(ackSync ?? attentionAckSyncOf(repository.gateway)); } static int _wallClockMillis() => DateTime.now().millisecondsSinceEpoch; + final ChatSeenFocus _focus; + + /// The open chat the user has interacted with while the window was focused. + /// Only such a chat acknowledges new content as it arrives; any other reply + /// in the open chat stays New until the next interaction. Cleared when the + /// window loses focus or another chat becomes the open one. + final Set _engaged = {}; + + void _focusChanged() { + if (_focus.focused) return; + _engaged.clear(); + _cancelPendingActiveAck(); + } + /// How long the open chat stays quiet before its new content is /// acknowledged to the other devices; streaming text arrives in many frames. final Duration activeAckDelay; @@ -61,6 +81,8 @@ class ChatSessionsController extends ChangeNotifier { final int Function() _nowMillis; AttentionAckSync? _ackSync; Timer? _activeAck; + // The chat whose quiet-period acknowledgement [_activeAck] is waiting on. + String? _pendingAckId; ChatSessionLocal _local = const ChatSessionLocal(); final Map _actionErrors = {}; List _sessions = const []; @@ -78,7 +100,17 @@ class ChatSessionsController extends ChangeNotifier { // older snapshot that arrives later never replaces it. final Map _activity = {}; StreamSubscription? _frameSubscription; - String? activeSessionId; + String? _activeSessionId; + + /// The chat open above the list. Opening another chat ends the engagement + /// with the previous one; setting the same id changes nothing. + String? get activeSessionId => _activeSessionId; + set activeSessionId(String? id) { + if (id == _activeSessionId) return; + _activeSessionId = id; + _engaged.clear(); + _cancelPendingActiveAck(); + } void _listenFrames() { _frameSubscription?.cancel(); @@ -98,8 +130,14 @@ class ChatSessionsController extends ChangeNotifier { final row = session.first; if (row['closed_at'] != null || row['closed'] == true) return; if (effect.running != null) _setRunning(id, effect.running!); - if (effect.attention && id != activeSessionId) unawaited(_markUnseen(id)); - if (effect.attention && id == activeSessionId) _scheduleActiveAck(id); + if (!effect.attention) return; + if (id == activeSessionId && _focus.focused && _engaged.contains(id)) { + _scheduleActiveAck(id); + } else { + // Passive: the window is unfocused, or the chat was open with no + // interaction since, so the reply is New until the user acts. + unawaited(_markUnseen(id)); + } } /// Another device changed a chat's shared colour, star or title: the row @@ -210,12 +248,45 @@ class ChatSessionsController extends ChangeNotifier { void _scheduleActiveAck(String id) { if (_ackSync == null) return; _activeAck?.cancel(); + _pendingAckId = id; _activeAck = Timer(activeAckDelay, () { - if (_disposed || id != activeSessionId) return; + _activeAck = null; + _pendingAckId = null; + // Losing focus or the chat during the quiet period ends the engagement; + // [_cancelPendingActiveAck] has already marked the reply New by then. + if (_disposed || id != activeSessionId || !_engaged.contains(id)) return; unawaited(_acknowledgeSeen(id, 0)); }); } + /// Ends a quiet period that has not fired yet. The reply it was waiting on + /// arrived while the user was engaged, but the engagement ends before the + /// quiet period does, so that reply is marked New here rather than dropped. + void _cancelPendingActiveAck() { + final pending = _pendingAckId; + if (pending == null) return; + _activeAck?.cancel(); + _activeAck = null; + _pendingAckId = null; + unawaited(_markUnseen(pending)); + } + + /// The user acted in [id]: a click, tap, scroll, key press in its pane, or + /// opening it. Only while the window is focused; a passive state is ignored. + /// Everything up to the latest message is marked seen and acknowledged to + /// every device. Repeated interactions (every scroll tick) send nothing once + /// the chat is engaged and has no unread content. + void reportInteraction(String id) { + if (_disposed || id.isEmpty || !_focus.focused) return; + final firstInChat = id == activeSessionId && _engaged.add(id); + if (!firstInChat && !_local.isUnseen(id)) return; + final row = _sessions.where((row) => '${row['id'] ?? ''}' == id); + final updatedAt = row.isEmpty + ? 0 + : chatSessionMillis(row.first['updated_at']); + unawaited(_acknowledgeSeen(id, updatedAt)); + } + /// Applies watermarks acknowledged on any device: one newer than this /// device's own marks the chat read here (clearing its New badge) and raises /// the local watermark, so a later badge is not cleared by the same ack. @@ -265,9 +336,9 @@ class ChatSessionsController extends ChangeNotifier { Future _markUnseen(String id) async { await _ensureLocal(); - // Loading device preferences may race an operator opening this chat. The - // open is authoritative even when the triggering frame arrived first. - if (_disposed || id == activeSessionId) return; + // Loading device preferences may race an operator engaging this chat. The + // interaction is authoritative even when the triggering frame arrived first. + if (_disposed || (id == activeSessionId && _engaged.contains(id))) return; final next = _local.markUnseen(id); if (identical(next, _local)) return; _local = next; @@ -443,11 +514,15 @@ class ChatSessionsController extends ChangeNotifier { _notify(); } - /// Records that this device has read [session]'s current recency. + /// Records that this device has read [session]'s current recency. Called + /// only for the user's own open (a list row, a shortcut, a notification), so + /// it also engages the chat. Showing a chat that was already open, such as a + /// restored layout, never calls this. Future markOpened(JsonMap session) async { final id = '${session['id'] ?? ''}'; if (id.isEmpty) return; activeSessionId = id; + if (_focus.focused) _engaged.add(id); await _ensureLocal(); if (_disposed) return; final updatedAt = chatSessionMillis(session['updated_at']); @@ -564,6 +639,7 @@ class ChatSessionsController extends ChangeNotifier { unawaited(_frameSubscription?.cancel()); _activeAck?.cancel(); _ackSync?.removeListener(_ackChanged); + _focus.removeListener(_focusChanged); super.dispose(); } } diff --git a/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart b/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart index d74c905d..7f3c192e 100644 --- a/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart +++ b/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart @@ -112,7 +112,6 @@ class _ChatSessionsScreenState extends State { final _search = TextEditingController(); late final ChatSectionFolds _folds = widget.folds ?? ChatSectionFolds(); Timer? _undoTimer; - String? _markedActiveSessionId; @override void initState() { @@ -123,7 +122,6 @@ class _ChatSessionsScreenState extends State { /// Reports the loaded rows at the end of the frame: the destination learns a /// routed row without this screen calling back inside its own build. void _reportSessions() { - _markActiveSessionRead(); if (widget.onSessions == null) return; WidgetsBinding.instance.addPostFrameCallback((_) { if (!mounted) return; @@ -131,28 +129,10 @@ class _ChatSessionsScreenState extends State { }); } - void _markActiveSessionRead() { - final id = widget.activeSessionId; - if (id == null) { - _markedActiveSessionId = null; - return; - } - if (id == _markedActiveSessionId) return; - for (final session in _controller.sessions) { - if (_sessionId(session) != id) continue; - // Mark synchronously so row activation and subsequent list notifications - // cannot write the same read watermark twice. - _markedActiveSessionId = id; - unawaited(_controller.markOpened(session)); - return; - } - } - @override void didUpdateWidget(covariant ChatSessionsScreen oldWidget) { super.didUpdateWidget(oldWidget); _controller.activeSessionId = widget.activeSessionId; - _markActiveSessionRead(); if (oldWidget.gateway != widget.gateway) { _controller.replaceRepository(ChatRepository(widget.gateway)); } else if (oldWidget.syncToken != widget.syncToken) { @@ -252,10 +232,8 @@ class _ChatSessionsScreenState extends State { if (session != null && mounted) widget.onOpen(session); } - void _markOpened(JsonMap session) { - _markedActiveSessionId = _sessionId(session); - unawaited(_controller.markOpened(session)); - } + void _markOpened(JsonMap session) => + unawaited(_controller.markOpened(session)); void _openBeside(JsonMap session) { _markOpened(session); diff --git a/app/lib/features/settings/server_connections.dart b/app/lib/features/settings/server_connections.dart index 4160e915..ef485709 100644 --- a/app/lib/features/settings/server_connections.dart +++ b/app/lib/features/settings/server_connections.dart @@ -46,6 +46,23 @@ class ServerConnections extends ChangeNotifier { return true; } + String? _chatOpenId; + + /// A chat the user opened from a notification. The tap is the user's own + /// interaction, so the chat it opens is read; a route restored without a tap + /// never sets this. + void requestChatOpen(String sessionId) { + _chatOpenId = sessionId; + notifyListeners(); + } + + /// Consumes the notification open of [sessionId], once. + bool takeChatOpenIntent(String sessionId) { + if (sessionId.isEmpty || sessionId != _chatOpenId) return false; + _chatOpenId = null; + return true; + } + /// Keep the intent outside the app that selecting another machine disposes. Future requestNewChat(String id) async { if (_busy || _disposed) return false; diff --git a/app/notes/chat-seen-only-after-interaction.md b/app/notes/chat-seen-only-after-interaction.md new file mode 100644 index 00000000..1a046f83 --- /dev/null +++ b/app/notes/chat-seen-only-after-interaction.md @@ -0,0 +1,98 @@ +# Chat seen only after a real interaction + +A chat's `chat_seen` watermark (which clears its phone notifications on every +device) is now sent only after the user acts in that chat while the app window +is focused. Showing, restoring or receiving a reply in an open chat is no +longer enough. + +## Before + +- `ChatSessionsScreen` called `markOpened` for the open chat on every list + update and widget change, so a chat left open on one device (the Mac) was + marked seen within about a second. +- Any reply in the open chat scheduled an acknowledgement after a 1.5 s quiet + period, whether or not the user was there. + +## After + +| State | Seen sent? | Why | +| --- | --- | --- | +| Reply while the window is unfocused / backgrounded | no | `ChatSeenFocus` is not `resumed`; the chat is marked locally unread. | +| Layout restored on start with a chat open | no | The screen only sets the open id; it no longer calls `markOpened`. | +| Open chat, no interaction since, reply arrives | no | Not engaged; reply is marked locally unread. | +| Open chat idle for minutes | no | Same as above; nothing schedules an acknowledgement. | +| Engaged chat, window then unfocused, refocused without input, reply | no | Losing focus clears the engagement. | +| Engaged chat, reply still in its quiet period, then focus lost | no | The pending acknowledgement is cancelled and the reply is marked locally unread at once. | +| Engaged chat, reply still in its quiet period, then another chat opened | no | Same cancel path; the reply stays New. | +| Reply in a chat that is not open | no (New badge) | Unchanged behaviour. | +| Click / tap in the pane | yes | `ChatSeenInteraction` pointer listener. | +| User scroll (drag, wheel) of the transcript | yes | Scroll notifications. Programmatic scroll is ignored. | +| Key press with focus in the pane (typing, Tab) | yes | `Focus.onKeyEvent` on the pane. | +| Keyboard focus moved into the pane by a key press outside it (Tab) | yes | `HardwareKeyboard` flags the key-down; the pane's `Focus.onFocusChange` reports when focus arrives during it. | +| Focus moved into the pane in code, no key press (restore, autofocus) | no | No key-down in progress, so nothing is reported. | +| Opening from the list / shortcut | yes | `markOpened` (unchanged call site, now the only open path). | +| Notification tap that opened the chat | yes | `ServerConnections.requestChatOpen` / `takeChatOpenIntent`. | +| Engaged chat, reply arrives | yes, after 1.5 s quiet | Existing quiet-period ack, now gated on engagement. | + +Once the user interacts, the chat is marked seen up to now (the server lifts +it to the registry recency). Repeated interactions in an already-engaged, read +chat send nothing further. + +## Where + +- `lib/features/chat/ui/sessions/chat_seen_focus.dart`: window focus from the + framework lifecycle (`resumed` = focused). +- `lib/features/chat/ui/sessions/chat_sessions_controller.dart`: + `reportInteraction`, the engagement set (cleared on focus loss or when the + open chat changes), and the passive/active split in the frame path. A reply + waiting in its quiet period is tracked (`_pendingAckId`); focus loss or a + chat change cancels that wait and marks the reply New (`_cancelPendingActiveAck`) + instead of letting the timer drop it silently. +- `lib/features/chat/conversation/chat_seen_interaction.dart`: the region + wrapped around each open conversation pane. +- `lib/features/chat/chat_pane_content.dart`: wraps the pane. +- `lib/features/chat/ui/sessions/chat_sessions_screen.dart`: removed the + passive mark-read on rebuild and restore. +- `lib/features/settings/server_connections.dart` and + `lib/application/pipelines_app.dart`: the notification-open intent. + +No server or web change: the server is untouched and still clears app +notifications on the watermark. + +## Tests (focused) + +- `test/features/chat/ui/sessions/chat_seen_interaction_test.dart` (15 tests): + passive cases (unfocused reply, restored layout, idle open chat, + background then refocus, reply in another chat, reply after leaving an + engaged chat, interaction while unfocused, a reply still in its quiet period + when focus is lost or another chat is opened, and the restored layout through + `ChatSessionsScreen`) and interaction cases (interaction in an unread open + chat, opening from the list, reply after an interaction, repeated + interactions, interaction in a non-open chat). +- `test/features/chat/conversation/chat_seen_interaction_test.dart` (9 tests): + showing the pane, programmatic scroll, and code-driven focus into the pane + report nothing; click, user drag, mouse wheel, key press, Tab from outside + into the pane, and notification open each report. +- Last run: the two focused files above, 24 passed, 0 failed (memwatch PASS, + peak 943 MB, names only the two intended paths). `tool/analyze.sh`: clean. +- Existing suites that touch the list, controller or server connections + (`chat_seen_sync_test`, `chat_active_session_test`, `chat_active_selection_test`, + `chat_sessions_screen_test`, `chat_sessions_lifecycle_test`, + `chat_sessions_activity_test`, `chat_new_session_controller_test`, + `chat_runtime_test`, `chat_floating_pane_test`, `chat_windows_test`, + `chat_color_test`, `chat_star_optimistic_test`, `chat_state_legibility_test`, + `chat_visibility_marker_test`, `chat_add_pane_picker_test`, + `chat_session_local_state_test`, `server_connections_recovery_test`) pass + unchanged. No expectation was edited. + +## Limitations + +- Focus is `resumed` only. On web a backgrounded tab reports `hidden` and + should count as unfocused; an unfocused window with no lifecycle change is + not detected there. Verify on the device or in the browser. +- Only the chat-question notification path (`ChatQuestionNotices`) is wired as + a notification open. Run-level notifications do not name a chat. +- Interactions are reported at the pane level. A chat in a floating window + uses the same pane content, so it is covered, but this was not exercised on + a device. +- No browser or device capture was taken (ui-review owns that). diff --git a/app/test/features/chat/conversation/chat_seen_interaction_test.dart b/app/test/features/chat/conversation/chat_seen_interaction_test.dart new file mode 100644 index 00000000..69410d10 --- /dev/null +++ b/app/test/features/chat/conversation/chat_seen_interaction_test.dart @@ -0,0 +1,220 @@ +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/servers/server_catalog.dart'; +import 'package:pipelines_app/core/servers/server_catalog_store.dart'; +import 'package:pipelines_app/core/servers/server_context.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_seen_interaction.dart'; +import 'package:pipelines_app/features/settings/server_connections.dart'; + +/// One open chat's pane: a field and a long transcript, both inside the region. +Widget _pane({ + required VoidCallback onInteract, + ScrollController? scroll, + FocusNode? focus, +}) => MaterialApp( + home: Scaffold( + body: ChatSeenInteraction( + sessionId: 'ses_a', + onInteract: onInteract, + child: Column( + children: [ + TextField(focusNode: focus), + Expanded( + child: ListView.builder( + controller: scroll, + itemCount: 200, + itemBuilder: (context, index) => + SizedBox(height: 40, child: Text('row $index')), + ), + ), + ], + ), + ), + ), +); + +void main() { + testWidgets('showing the pane reports nothing', (tester) async { + var count = 0; + await tester.pumpWidget(_pane(onInteract: () => count++)); + await tester.pump(); + await tester.pump(const Duration(seconds: 2)); + + expect(count, 0); + }); + + testWidgets('a programmatic scroll reports nothing', (tester) async { + var count = 0; + final scroll = ScrollController(); + addTearDown(scroll.dispose); + await tester.pumpWidget(_pane(onInteract: () => count++, scroll: scroll)); + + scroll.jumpTo(600); + await tester.pump(); + + expect(count, 0); + }); + + testWidgets('a click or tap in the pane reports once per press', ( + tester, + ) async { + var count = 0; + await tester.pumpWidget(_pane(onInteract: () => count++)); + + await tester.tap(find.text('row 3')); + await tester.pump(); + + expect(count, greaterThanOrEqualTo(1)); + }); + + testWidgets('a user drag of the transcript reports', (tester) async { + var count = 0; + await tester.pumpWidget(_pane(onInteract: () => count++)); + + await tester.drag(find.text('row 0'), const Offset(0, -300)); + await tester.pumpAndSettle(); + + expect(count, greaterThanOrEqualTo(1)); + }); + + testWidgets('a mouse-wheel scroll of the transcript reports', (tester) async { + var count = 0; + final scroll = ScrollController(); + addTearDown(scroll.dispose); + await tester.pumpWidget(_pane(onInteract: () => count++, scroll: scroll)); + + final pointer = TestPointer(1, PointerDeviceKind.mouse); + await tester.sendEventToBinding( + pointer.hover(tester.getCenter(find.text('row 0'))), + ); + await tester.sendEventToBinding(pointer.scroll(const Offset(0, 200))); + await tester.pumpAndSettle(); + + expect(scroll.offset, greaterThan(0)); + expect(count, greaterThanOrEqualTo(1)); + }); + + testWidgets('a key press while focus is in the pane reports, with no click', ( + tester, + ) async { + var count = 0; + final focus = FocusNode(); + addTearDown(focus.dispose); + await tester.pumpWidget(_pane(onInteract: () => count++, focus: focus)); + + await tester.sendKeyEvent(LogicalKeyboardKey.keyA); + await tester.pump(); + expect(count, 0, reason: 'a key with no focus in the pane is not its input'); + + focus.requestFocus(); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.keyA); + await tester.pump(); + + expect(count, 1); + }); + + testWidgets('code-driven focus into the pane reports nothing', (tester) async { + var count = 0; + final focus = FocusNode(); + addTearDown(focus.dispose); + await tester.pumpWidget(_pane(onInteract: () => count++, focus: focus)); + + focus.requestFocus(); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + + expect(focus.hasFocus, isTrue); + expect(count, 0, reason: 'focus moved in code, with no key press, is passive'); + }); + + testWidgets('Tab from outside the pane into it reports once', (tester) async { + var count = 0; + final outside = FocusNode(); + final focus = FocusNode(); + addTearDown(outside.dispose); + addTearDown(focus.dispose); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Column( + children: [ + TextField(focusNode: outside), + Expanded( + child: ChatSeenInteraction( + sessionId: 'ses_a', + onInteract: () => count++, + child: Column( + children: [ + TextField(focusNode: focus), + const Expanded(child: SizedBox()), + ], + ), + ), + ), + ], + ), + ), + ), + ); + outside.requestFocus(); + await tester.pump(); + + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.pump(); + + expect(focus.hasFocus, isTrue, reason: 'Tab moved focus into the pane'); + expect(count, 1); + }); + + testWidgets('a notification tap that opened this chat reports once', ( + tester, + ) async { + var count = 0; + final connections = ServerConnections( + store: MemoryServerCatalogStore( + catalog: ServerCatalog( + servers: [ + SavedServer.validated( + id: 'mac', + name: 'Mac', + endpoints: const ['ws://mac.test/connect'], + ), + ], + selectedId: 'mac', + ), + ), + onSelected: (_) async {}, + ); + addTearDown(connections.dispose); + await connections.load(); + await tester.pumpWidget( + ServerContext( + connections: connections, + serverId: 'mac', + child: _pane(onInteract: () => count++), + ), + ); + await tester.pump(); + expect(count, 0); + + // Another chat's notification is not this pane's open. + connections.requestChatOpen('ses_other'); + await tester.pump(); + await tester.pump(); + expect(count, 0); + + connections.requestChatOpen('ses_a'); + await tester.pump(); + await tester.pump(); + expect(count, 1); + + // The tap is consumed: a later rebuild does not report it again. + connections.requestChatOpen('ses_other'); + await tester.pump(); + await tester.pump(); + expect(count, 1); + }); +} diff --git a/app/test/features/chat/ui/sessions/chat_seen_interaction_test.dart b/app/test/features/chat/ui/sessions/chat_seen_interaction_test.dart new file mode 100644 index 00000000..e22ab491 --- /dev/null +++ b/app/test/features/chat/ui/sessions/chat_seen_interaction_test.dart @@ -0,0 +1,376 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/attention/runtime/attention_ack_queue.dart'; +import 'package:pipelines_app/features/attention/runtime/attention_ack_sync.dart'; +import 'package:pipelines_app/features/chat/data/chat_repository.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/chat_seen_focus.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_controller.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_screen.dart'; + +import '../../../attention/runtime/fake_ack_server.dart'; +import 'chat_test_harness.dart'; + +/// A chat reply in [id], as the server pushes it while the chat is live. +JsonMap _reply(String id) => { + 'type': 'chat_event', + 'chat_event': {'session_id': id, 'kind': 'text', 'delta': 'hello'}, +}; + +/// One device's chat list, its shared acknowledgements and its window focus. +class _Device { + _Device(this.server, {required this.clock, bool focused = true}) + : client = server.connect(), + local = MemoryChatSessionLocalStore(), + focus = ChatSeenFocus(focused: focused) { + sync = AttentionAckSync(gateway: client, queue: MemoryAttentionAckQueue()); + bindAttentionAckSync(client, sync); + list = ChatSessionsController( + ChatRepository(client), + localStore: local, + nowMillis: () => clock(), + seenFocus: focus, + // Short enough to test quiet periods, long enough to settle under load. + activeAckDelay: const Duration(milliseconds: 60), + ); + } + + final FakeAckServer server; + final FakeAckClient client; + final MemoryChatSessionLocalStore local; + final ChatSeenFocus focus; + final int Function() clock; + late final AttentionAckSync sync; + late final ChatSessionsController list; + + Future start() async { + await sync.connected(); + await list.refresh(); + await settle(); + } + + JsonMap row(String id) => list.sessions.firstWhere((row) => row['id'] == id); + + /// Whether [id] shows a New badge in the list (an open chat never does). + bool isNew(String id) => list.isUnseen(row(id)); + + /// Whether this device holds [id] as unread, whether or not it is open. + bool holdsUnread(String id) => local.state?.isUnseen(id) ?? false; + + void dispose() { + list.dispose(); + sync.dispose(); + focus.dispose(); + } +} + +/// Lets a pending quiet-period acknowledgement fire (60 ms here) and settle. +Future quietPeriod() async { + await Future.delayed(const Duration(milliseconds: 200)); + await settle(); +} + +void main() { + late FakeAckServer server; + var now = 5000; + + setUp(() { + now = 5000; + server = FakeAckServer() + ..chatSessions = [ + {'id': 'ses_a', 'title': 'A', 'directory': '/w', 'updated_at': 1000}, + {'id': 'ses_b', 'title': 'B', 'directory': '/w', 'updated_at': 1000}, + ]; + }); + + void pushToAll(JsonMap frame) { + for (final client in server.clients) { + client.pushed.add(frame); + } + } + + group('passive states never mark a chat seen', () { + test('a reply in an unfocused window stays New', () async { + final device = _Device(server, clock: () => now, focused: false); + addTearDown(device.dispose); + await device.start(); + // Restored as the open chat, then the window is in the background. + device.list.activeSessionId = 'ses_a'; + pushToAll(_reply('ses_a')); + await quietPeriod(); + + expect(server.state.chatSeen, isEmpty); + expect(device.holdsUnread('ses_a'), isTrue); + device.list.activeSessionId = null; + expect(device.isNew('ses_a'), isTrue); + }); + + test('a restored open chat with no interaction stays New', () async { + final device = _Device(server, clock: () => now); + addTearDown(device.dispose); + await device.start(); + // A layout restored on start sets the open chat without any open. + device.list.activeSessionId = 'ses_a'; + await settle(); + + pushToAll(_reply('ses_a')); + await quietPeriod(); + + expect(server.state.chatSeen, isEmpty); + expect(device.holdsUnread('ses_a'), isTrue); + }); + + testWidgets( + 'a layout restored with a chat open, then a reply, leaves it New', + (tester) async { + final device = _Device(server, clock: () => now); + addTearDown(device.dispose); + await tester.runAsync(device.start); + // The list screen is shown with the restored chat as its open conversation. + await tester.pumpWidget( + MaterialApp( + home: ChatSessionsScreen( + gateway: device.client, + onOpen: (_) {}, + controller: device.list, + activeSessionId: 'ses_a', + localStore: device.local, + ), + ), + ); + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 20)), + ); + await tester.pump(); + + await tester.runAsync(() async { + pushToAll(_reply('ses_a')); + await quietPeriod(); + }); + await tester.pump(); + + expect(server.state.chatSeen, isEmpty); + expect(device.holdsUnread('ses_a'), isTrue); + }, + ); + + test('an open chat left idle long after a reply stays New', () async { + final device = _Device(server, clock: () => now); + addTearDown(device.dispose); + await device.start(); + device.list.activeSessionId = 'ses_a'; + await settle(); + + pushToAll(_reply('ses_a')); + now += 600000; // Ten minutes later, nothing touched it. + await quietPeriod(); + + expect(server.state.chatSeen, isEmpty); + expect(device.holdsUnread('ses_a'), isTrue); + }); + + test('a reply after backgrounding an engaged chat stays New, even ' + 'once the window is focused again without interaction', () async { + final device = _Device(server, clock: () => now); + addTearDown(device.dispose); + await device.start(); + device.list.activeSessionId = 'ses_a'; + device.list.reportInteraction('ses_a'); + await settle(); + expect(server.state.chatSeen['ses_a'], 5000); + + device.focus.focused = false; + now = 6000; + pushToAll(_reply('ses_a')); + await quietPeriod(); + expect(server.state.chatSeen['ses_a'], 5000); + + device.focus.focused = true; + now = 7000; + pushToAll(_reply('ses_a')); + await quietPeriod(); + expect(server.state.chatSeen['ses_a'], 5000); + expect(device.holdsUnread('ses_a'), isTrue); + }); + + test('a reply in another chat while this one is open stays New', () async { + final device = _Device(server, clock: () => now); + addTearDown(device.dispose); + await device.start(); + device.list.activeSessionId = 'ses_a'; + device.list.reportInteraction('ses_a'); + await settle(); + + now = 6000; + pushToAll(_reply('ses_b')); + await quietPeriod(); + + expect(server.state.chatSeen.containsKey('ses_b'), isFalse); + expect(device.isNew('ses_b'), isTrue); + }); + + test('a reply after leaving an engaged chat stays New', () async { + final device = _Device(server, clock: () => now); + addTearDown(device.dispose); + await device.start(); + device.list.activeSessionId = 'ses_a'; + device.list.reportInteraction('ses_a'); + await settle(); + + device.list.activeSessionId = 'ses_b'; + now = 6000; + pushToAll(_reply('ses_a')); + await quietPeriod(); + + expect(server.state.chatSeen['ses_a'], 5000); + expect(device.isNew('ses_a'), isTrue); + }); + + test('a reply still in its quiet period when the window loses focus ' + 'stays New, not seen', () async { + final device = _Device(server, clock: () => now); + addTearDown(device.dispose); + await device.start(); + device.list.activeSessionId = 'ses_a'; + device.list.reportInteraction('ses_a'); + await settle(); + expect(server.state.chatSeen['ses_a'], 5000); + + now = 6000; + pushToAll(_reply('ses_a')); + await settle(); // The reply is held in its quiet period, not yet acked. + device.focus.focused = false; + await quietPeriod(); + + expect(server.state.chatSeen['ses_a'], 5000); + expect(device.holdsUnread('ses_a'), isTrue); + }); + + test('a reply still in its quiet period when the user opens another ' + 'chat stays New, not seen', () async { + final device = _Device(server, clock: () => now); + addTearDown(device.dispose); + await device.start(); + device.list.activeSessionId = 'ses_a'; + device.list.reportInteraction('ses_a'); + await settle(); + + now = 6000; + pushToAll(_reply('ses_a')); + await settle(); + device.list.activeSessionId = 'ses_b'; + await quietPeriod(); + + expect(server.state.chatSeen['ses_a'], 5000); + expect(device.isNew('ses_a'), isTrue); + }); + + test('an interaction while the window is unfocused is ignored', () async { + final device = _Device(server, clock: () => now, focused: false); + addTearDown(device.dispose); + await device.start(); + device.list.activeSessionId = 'ses_a'; + + device.list.reportInteraction('ses_a'); + await quietPeriod(); + + expect(server.state.chatSeen, isEmpty); + }); + }); + + group('user interactions mark the chat seen', () { + test( + 'an interaction in an unread open chat marks it seen up to now', + () async { + final device = _Device(server, clock: () => now); + addTearDown(device.dispose); + await device.start(); + device.list.activeSessionId = 'ses_a'; + pushToAll(_reply('ses_a')); + await settle(); + expect(device.holdsUnread('ses_a'), isTrue); + + now = 6000; + device.list.reportInteraction('ses_a'); + await settle(); + + expect(server.state.chatSeen['ses_a'], 6000); + expect(device.holdsUnread('ses_a'), isFalse); + expect(device.sync.pending.chatSeen, isEmpty); + }, + ); + + test('opening a chat from the list marks it seen', () async { + final device = _Device(server, clock: () => now); + addTearDown(device.dispose); + await device.start(); + pushToAll(_reply('ses_a')); + await settle(); + + now = 6000; + await device.list.markOpened(device.row('ses_a')); + await settle(); + + expect(server.state.chatSeen['ses_a'], 6000); + expect(device.holdsUnread('ses_a'), isFalse); + }); + + test( + 'a reply after an interaction is marked seen once the chat is quiet', + () async { + final device = _Device(server, clock: () => now); + addTearDown(device.dispose); + await device.start(); + device.list.activeSessionId = 'ses_a'; + device.list.reportInteraction('ses_a'); + await settle(); + + now = 6000; + pushToAll(_reply('ses_a')); + await quietPeriod(); + + expect(server.state.chatSeen['ses_a'], 6000); + expect(device.holdsUnread('ses_a'), isFalse); + }, + ); + + test( + 'repeated interactions in an engaged, read chat send nothing more', + () async { + final device = _Device(server, clock: () => now); + addTearDown(device.dispose); + await device.start(); + device.list.activeSessionId = 'ses_a'; + device.list.reportInteraction('ses_a'); + await settle(); + final sent = device.client.count('ack_attention'); + + // Scroll ticks and clicks after the first engagement. + for (var i = 0; i < 5; i++) { + device.list.reportInteraction('ses_a'); + } + await settle(); + + expect(device.client.count('ack_attention'), sent); + }, + ); + + test('an interaction in a visible chat that is not the open one marks it ' + 'seen', () async { + final device = _Device(server, clock: () => now); + addTearDown(device.dispose); + await device.start(); + device.list.activeSessionId = 'ses_a'; + pushToAll(_reply('ses_b')); + await settle(); + expect(device.holdsUnread('ses_b'), isTrue); + + now = 6000; + device.list.reportInteraction('ses_b'); + await settle(); + + expect(server.state.chatSeen['ses_b'], 6000); + expect(device.holdsUnread('ses_b'), isFalse); + }); + }); +} From c48a1559acb691828f9cdd8509c6a282e6c89de0 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 12 Nov 2026 02:59:34 +0000 Subject: [PATCH 4/7] Sync open chats across devices through the server (pipeline run work in progress) --- app/lib/features/chat/chat_screen_float.dart | 9 ++ app/lib/features/chat/chat_screen_keys.dart | 13 -- .../features/chat/chat_screen_workspace.dart | 69 +++++++++- app/lib/features/chat/screen.dart | 4 +- .../features/chat/windows/chat_windows.dart | 3 + .../chat_open_workspace_controller.dart | 43 ++++++ .../chat_open_workspace_gateway.dart | 70 ++++++++++ .../workspace/chat_workspace_controller.dart | 42 ++++++ app/notes/chat-open-workspace-sync.md | 34 +++++ .../chat_open_workspace_gateway_test.dart | 35 +++++ internal/pipeline/chat_open_workspace.go | 125 ++++++++++++++++++ internal/pipeline/chat_open_workspace_test.go | 59 +++++++++ internal/pipeline/store.go | 4 + internal/protocol/chat.go | 4 + internal/protocol/chat_open_workspace.go | 20 +++ internal/protocol/message.go | 24 ++-- internal/server/chat.go | 13 +- internal/server/chat_close.go | 18 ++- internal/server/chat_open_workspace.go | 118 +++++++++++++++++ internal/server/chat_session_changes.go | 16 +++ internal/server/websocket.go | 11 ++ 21 files changed, 703 insertions(+), 31 deletions(-) create mode 100644 app/lib/features/chat/workspace/chat_open_workspace_controller.dart create mode 100644 app/lib/features/chat/workspace/chat_open_workspace_gateway.dart create mode 100644 app/notes/chat-open-workspace-sync.md create mode 100644 app/test/features/chat/workspace/chat_open_workspace_gateway_test.dart create mode 100644 internal/pipeline/chat_open_workspace.go create mode 100644 internal/pipeline/chat_open_workspace_test.go create mode 100644 internal/protocol/chat_open_workspace.go create mode 100644 internal/server/chat_open_workspace.go diff --git a/app/lib/features/chat/chat_screen_float.dart b/app/lib/features/chat/chat_screen_float.dart index a138957b..40761a95 100644 --- a/app/lib/features/chat/chat_screen_float.dart +++ b/app/lib/features/chat/chat_screen_float.dart @@ -46,6 +46,9 @@ mixin _ChatScreenFloat on State, _ChatScreenWorkspace { final pane = _workspace.detach(paneId); if (pane == null) return; widget.windows?.float(pane.sessionId); + if (!_applyingServerWorkspace) { + unawaited(_openWorkspace?.replace(_serverWorkspaceEntries())); + } // Floating the last tiled chat leaves the list, as closing it does. if (_workspace.paneCount == 0) _back(); } @@ -61,6 +64,9 @@ mixin _ChatScreenFloat on State, _ChatScreenWorkspace { _floatPane(pane.id); } else { windows.float(id); + if (!_applyingServerWorkspace) { + unawaited(_openWorkspace?.replace(_serverWorkspaceEntries())); + } } } @@ -69,6 +75,9 @@ mixin _ChatScreenFloat on State, _ChatScreenWorkspace { _workspaceVisible = true; if (!_pageOpen && showsListBesideDetail(context)) _usedWorkspace = true; _workspace.dock(sessionId); + if (!_applyingServerWorkspace) { + unawaited(_openWorkspace?.replace(_serverWorkspaceEntries())); + } _composerFocus.request(sessionId); } diff --git a/app/lib/features/chat/chat_screen_keys.dart b/app/lib/features/chat/chat_screen_keys.dart index 7a3a51ca..7916d8f0 100644 --- a/app/lib/features/chat/chat_screen_keys.dart +++ b/app/lib/features/chat/chat_screen_keys.dart @@ -10,8 +10,6 @@ const chatRecentSessionLimit = 8; /// the workspace's pane cycling, and leave other destinations, popups, /// dialogs and any focused text field alone. mixin _ChatScreenKeys on State, _ChatScreenWorkspace { - void _open(JsonMap session, {bool focusComposer}); - /// The chats this visit has shown in the workspace, most recent first; the /// active one leads it. In memory only: a reopened app starts afresh. final List _recentSessions = []; @@ -38,17 +36,6 @@ mixin _ChatScreenKeys on State, _ChatScreenWorkspace { @override void _forgetRecentSessions() => _recentSessions.clear(); - /// Over a single pane, opens the chat shown before the active one with its - /// composer focused; false when this visit has shown no other chat. - @override - bool _toggleRecentChat() { - final current = _workspace.activePane?.sessionId; - final previous = _recentSessions.where((id) => id != current).firstOrNull; - if (previous == null) return false; - _open(_rowFor(previous) ?? {'id': previous}, focusComposer: true); - return true; - } - /// Whether the shown destination is Chat with no popup, dialog or other /// route over it, so a key pressed now is meant for the open chat. @override diff --git a/app/lib/features/chat/chat_screen_workspace.dart b/app/lib/features/chat/chat_screen_workspace.dart index edd24e01..a1ed5349 100644 --- a/app/lib/features/chat/chat_screen_workspace.dart +++ b/app/lib/features/chat/chat_screen_workspace.dart @@ -5,7 +5,6 @@ mixin _ChatScreenWorkspace on State { Map get _openedSessions; ChatComposerFocusRequests get _composerFocus; bool _chatOwnsKeyboard(); - bool _toggleRecentChat(); void _noteRecentSession(); void _forgetRecentSessions(); JsonMap? _rowFor(String id); @@ -83,13 +82,33 @@ mixin _ChatScreenWorkspace on State { void _openSidebarSession(JsonMap session); final ChatWorkspaceController _workspace = ChatWorkspaceController(); + ChatOpenWorkspaceController? _openWorkspace; + bool _applyingServerWorkspace = false; ChatWorkspaceBinding? _workspaceBinding; String? _workspaceScope; + Iterable _serverWorkspaceEntries() sync* { + final floating = + widget.windows?.floatingSessionIds.toSet() ?? const {}; + for (final pane in _workspace.panes) { + yield ChatOpenWorkspaceEntry( + pane.sessionId, + floating: floating.contains(pane.sessionId), + ); + } + for (final sessionId in floating) { + if (!_workspace.holdsSession(sessionId)) { + yield ChatOpenWorkspaceEntry(sessionId, floating: true); + } + } + } + void _bindWorkspacePersistence() { if (!widget.persistWorkspace) return; final scope = serverStorageScope(serverIdentity(widget.gateway)); _workspaceScope = scope; + _openWorkspace = ChatOpenWorkspaceController(gateway: widget.gateway) + ..onChanged = _applyOpenWorkspace; _workspaceBinding = ChatWorkspaceBinding( controller: _workspace, store: widget.gateway is FederatedChatGateway @@ -118,6 +137,47 @@ mixin _ChatScreenWorkspace on State { unawaited( _workspaceBinding!.start(initialSessionId: widget.initialSessionId), ); + unawaited(_openWorkspace!.start(legacy: _serverWorkspaceEntries())); + } + + void _applyOpenWorkspace(ChatOpenWorkspaceSnapshot snapshot) { + if (!mounted) return; + _applyingServerWorkspace = true; + try { + final windows = widget.windows; + if (windows != null) { + final entriesBySession = { + for (final entry in snapshot.entries) entry.sessionId: entry, + }; + for (final window in windows.windows.toList()) { + if (!entriesBySession.containsKey(window.contentId)) { + windows.manager.close(window.id); + } + } + for (final entry in snapshot.entries) { + final localWindow = windows.windows + .where((window) => window.contentId == entry.sessionId) + .firstOrNull; + if (entry.floating && localWindow == null) { + final pane = _workspace.panes + .where((pane) => pane.sessionId == entry.sessionId) + .firstOrNull; + if (pane != null) _workspace.close(pane.id); + windows.float(entry.sessionId); + } else if (!entry.floating && localWindow != null) { + windows.dock(localWindow); + } + } + } + _workspace.reconcileSessions( + snapshot.entries + .where((entry) => !entry.floating) + .map((entry) => entry.sessionId), + ); + if (_workspace.paneCount == 0 && _workspaceVisible) _back(); + } finally { + _applyingServerWorkspace = false; + } } bool _updateWorkspacePersistence(ChatScreen oldWidget) { @@ -153,8 +213,7 @@ mixin _ChatScreenWorkspace on State { String _workspaceSignature = ''; /// Ctrl+Tab cycles retained panes even when the sidebar or toolbar owns - /// focus. Over a single pane it swaps in the chat shown before this one - /// instead, and back again (see [_toggleRecentChat]). Command+Tab stays + /// focus. Command+Tab stays /// with the operating system's application switcher. While the app's /// terminal is shown, Ctrl+Tab moves between its tabs instead. While a /// floating chat window holds the keyboard, Ctrl+Tab cycles those windows @@ -174,7 +233,6 @@ mixin _ChatScreenWorkspace on State { return false; } final panes = _workspace.panes; - if (panes.length == 1 && _toggleRecentChat()) return true; final active = panes.indexWhere( (pane) => pane.id == _workspace.activePaneId, ); @@ -205,6 +263,9 @@ mixin _ChatScreenWorkspace on State { '${_workspace.activePaneId}:${_workspace.panes.map((p) => '${p.id}=${p.sessionId}').join(',')}'; if (_workspaceSignature == signature) return; _workspaceSignature = signature; + if (!_applyingServerWorkspace) { + unawaited(_openWorkspace?.replace(_serverWorkspaceEntries())); + } void update() { if (!mounted) return; setState(() {}); diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index 3d723db4..eacd2acd 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -31,6 +31,8 @@ import 'workspace/chat_float_shortcut.dart'; import 'workspace/chat_workspace_binding.dart'; import 'workspace/chat_workspace_snapshot.dart'; import 'workspace/chat_workspace_store.dart'; +import 'workspace/chat_open_workspace_controller.dart'; +import 'workspace/chat_open_workspace_gateway.dart'; import 'conversation/chat_bar_tint.dart'; import 'conversation/chat_pane_picker.dart'; import 'conversation/chat_add_pane_picker.dart'; @@ -238,7 +240,6 @@ class _ChatScreenState extends State void _openBySelection(JsonMap session) => _open(session, focusComposer: chatSelectionFocusesComposer(session)); - @override void _open(JsonMap session, {bool focusComposer = false}) { final id = '${session['id'] ?? ''}'; if (id.isEmpty) return; @@ -387,6 +388,7 @@ class _ChatScreenState extends State HardwareKeyboard.instance.removeHandler(_slashFocusKey); _page.dispose(); _workspaceBinding?.dispose(); + _openWorkspace?.dispose(); _unbindWindows(); _workspace.removeListener(_workspaceChanged); _workspace.dispose(); diff --git a/app/lib/features/chat/windows/chat_windows.dart b/app/lib/features/chat/windows/chat_windows.dart index c2c7fb59..99d6a1cc 100644 --- a/app/lib/features/chat/windows/chat_windows.dart +++ b/app/lib/features/chat/windows/chat_windows.dart @@ -75,6 +75,9 @@ class ChatWindows { Iterable get windows => manager.windows.where((w) => w.kind == chatWindowKind); + Iterable get floatingSessionIds => + windows.map((window) => window.contentId); + /// Registers the kind and starts answering the chord. Call before the /// manager restores, so saved chat windows are kept. void start() { diff --git a/app/lib/features/chat/workspace/chat_open_workspace_controller.dart b/app/lib/features/chat/workspace/chat_open_workspace_controller.dart new file mode 100644 index 00000000..e1ebaba8 --- /dev/null +++ b/app/lib/features/chat/workspace/chat_open_workspace_controller.dart @@ -0,0 +1,43 @@ +import 'dart:async'; +import '../../../../core/api_gateway.dart'; +import 'chat_open_workspace_gateway.dart'; + +class ChatOpenWorkspaceController { + ChatOpenWorkspaceController({required ApiGateway gateway}) + : _gateway = ChatOpenWorkspaceGateway(gateway); + final ChatOpenWorkspaceGateway _gateway; + StreamSubscription? _subscription; + int revision = 0; + bool _disposed = false; + void Function(ChatOpenWorkspaceSnapshot snapshot)? onChanged; + Future start({ + Iterable legacy = const [], + }) async { + if (_subscription != null || _disposed) return; + _subscription = _gateway.changes.listen((snapshot) { + if (_disposed || snapshot.revision < revision) return; + revision = snapshot.revision; + onChanged?.call(snapshot); + }); + if (legacy.isNotEmpty) { + final snapshot = await _gateway.replace(legacy, seed: true); + if (snapshot != null && snapshot.revision >= revision) { + revision = snapshot.revision; + onChanged?.call(snapshot); + } + } + } + + Future replace(Iterable entries) async { + if (_disposed) return; + final snapshot = await _gateway.replace(entries); + if (snapshot != null && snapshot.revision >= revision) { + revision = snapshot.revision; + } + } + + void dispose() { + _disposed = true; + unawaited(_subscription?.cancel()); + } +} diff --git a/app/lib/features/chat/workspace/chat_open_workspace_gateway.dart b/app/lib/features/chat/workspace/chat_open_workspace_gateway.dart new file mode 100644 index 00000000..95405440 --- /dev/null +++ b/app/lib/features/chat/workspace/chat_open_workspace_gateway.dart @@ -0,0 +1,70 @@ +import '../../../../core/api_gateway.dart'; + +class ChatOpenWorkspaceEntry { + const ChatOpenWorkspaceEntry(this.sessionId, {this.floating = false}); + final String sessionId; + final bool floating; + Map toJson() => { + 'session_id': sessionId, + if (floating) 'floating': true, + }; + static ChatOpenWorkspaceEntry? fromJson(Object? value) { + if (value is! Map) return null; + final id = '${value['session_id'] ?? ''}'.trim(); + return id.isEmpty + ? null + : ChatOpenWorkspaceEntry(id, floating: value['floating'] == true); + } +} + +class ChatOpenWorkspaceSnapshot { + const ChatOpenWorkspaceSnapshot(this.revision, this.entries); + final int revision; + final List entries; + static ChatOpenWorkspaceSnapshot? fromJson(Object? value) { + if (value is! Map || value['entries'] is! List) return null; + final entries = []; + for (final item in value['entries'] as List) { + final entry = ChatOpenWorkspaceEntry.fromJson(item); + if (entry == null || + entries.any((old) => old.sessionId == entry.sessionId)) { + return null; + } + entries.add(entry); + } + if (entries.length > 64) return null; + return ChatOpenWorkspaceSnapshot( + (value['revision'] as num?)?.toInt() ?? 0, + List.unmodifiable(entries), + ); + } +} + +class ChatOpenWorkspaceGateway { + ChatOpenWorkspaceGateway(this.gateway); + final ApiGateway gateway; + Future replace( + Iterable entries, { + bool seed = false, + }) async { + final response = await gateway.call('chat_open_workspace', { + 'chat_open_workspace_request': { + 'entries': entries + .map((entry) => entry.toJson()) + .toList(growable: false), + if (seed) 'seed': true, + }, + }); + return ChatOpenWorkspaceSnapshot.fromJson(response['chat_open_workspace']); + } + + Stream get changes async* { + await for (final frame in gateway.frames) { + if (frame['type'] != 'chat_open_workspace_changed') continue; + final snapshot = ChatOpenWorkspaceSnapshot.fromJson( + frame['chat_open_workspace'], + ); + if (snapshot != null) yield snapshot; + } + } +} diff --git a/app/lib/features/chat/workspace/chat_workspace_controller.dart b/app/lib/features/chat/workspace/chat_workspace_controller.dart index a3e5d7c8..0a7dc270 100644 --- a/app/lib/features/chat/workspace/chat_workspace_controller.dart +++ b/app/lib/features/chat/workspace/chat_workspace_controller.dart @@ -203,6 +203,48 @@ class ChatWorkspaceController extends ChangeNotifier { _changed(); } + /// Reconciles tiled membership and order without discarding the local split + /// geometry. Floating membership is handled by the window host. + void reconcileSessions(Iterable sessionIds) { + final wanted = []; + final seen = {}; + for (final id in sessionIds) { + if (id.isNotEmpty && seen.add(id)) wanted.add(id); + } + final current = panes; + if (wanted.isEmpty) { + if (_root == null) return; + _root = null; + _active = null; + _changed(); + return; + } + final retained = current.take(wanted.length).toList(); + for (var i = 0; i < retained.length; i++) { + final pane = retained[i]; + final id = wanted[i]; + if (pane.sessionId != id) { + _root = _replace(_root!, pane.id, ChatWorkspacePane(pane.id, id)); + } + } + for (final pane in current.skip(wanted.length).toList()) { + _root = _remove(_root!, pane.id); + } + if (retained.isEmpty) { + final pane = ChatWorkspacePane(_id('pane'), wanted.first); + _root = pane; + _active = pane.id; + } else { + for (final id in wanted.skip(retained.length)) { + splitActive(id, ChatSplitAxis.horizontal); + } + } + if (_active == null || !panes.any((pane) => pane.id == _active)) { + _active = panes.first.id; + } + _changed(); + } + void replaceSession(String oldId, String newId) { if (oldId == newId || newId.isEmpty || _replaceFloating(oldId, newId)) { return; diff --git a/app/notes/chat-open-workspace-sync.md b/app/notes/chat-open-workspace-sync.md new file mode 100644 index 00000000..a170cfcb --- /dev/null +++ b/app/notes/chat-open-workspace-sync.md @@ -0,0 +1,34 @@ +# Server-authoritative open chat workspace + +## Behaviour + +The authenticated `/connect` protocol now stores one bounded ordered workspace +per server scope. Entries contain only operator session ids and a floating bit. +Opening, closing, reordering, docking and floating publish a full authoritative +snapshot; other connections receive `chat_open_workspace_changed`. The first +client may seed an empty server snapshot from its legacy local layout. Split +ratios, pane ids, window rectangles and other presentation geometry remain local. + +The server drops closed, missing, unowned, or no-longer-live broker sessions +before saving. The store caps membership at 64 entries and rejects duplicates or +invalid ids. Protocol and application parsers apply the same bounds. + +## Security and limits + +Workspace writes use the existing authenticated websocket. The server requires +both an operator-session registry row and a live broker session, so pipeline-owned +or another user's ids cannot be retained. No credentials, transcripts, drafts, +tokens or geometry are persisted. The current scope is the authenticated local +server's single operator (`default`); multi-user identity is not yet modelled. + +## Verification + +* `go test ./internal/protocol -run 'Test.*Chat|Test.*Workspace'` — passed. +* `go test ./internal/pipeline -run 'TestChatOpenWorkspace'` — passed. +* `go test ./internal/server -run 'TestChat(Open|Close|NewSession)|TestEmbeddedSchedulesReadOnlyOverWebSocket|TestStorageWebsocketProtocolAndNoStartupCleanup|TestTemplatesDoNotSeedDatabaseAndCreateOnlyPreservesExisting'` — passed. +* `go build ./cmd/pipelines-server` — passed. +* `cd app && tool/memwatch/full.sh 'test/features/chat/workspace/chat_open_workspace_gateway_test.dart test/features/chat/workspace/chat_workspace_binding_test.dart'` — 7 passed, 0 failed, 0 skipped; peak 800 MB; exit 0. +* `cd app && tool/analyze.sh` — clean; 0 errors, 0 warnings, 2 infos before the brace cleanup; rerun after cleanup was not captured. + +Not tested: a live two-client scratch websocket/broker check and rendered UI +captures. The shared server was not restarted or contacted. diff --git a/app/test/features/chat/workspace/chat_open_workspace_gateway_test.dart b/app/test/features/chat/workspace/chat_open_workspace_gateway_test.dart new file mode 100644 index 00000000..f646d215 --- /dev/null +++ b/app/test/features/chat/workspace/chat_open_workspace_gateway_test.dart @@ -0,0 +1,35 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_open_workspace_gateway.dart'; + +void main() { + test('decodes bounded ordered membership and floating state', () { + final snapshot = ChatOpenWorkspaceSnapshot.fromJson({ + 'revision': 7, + 'entries': [ + {'session_id': 'ses_a', 'floating': true}, + {'session_id': 'ses_b'}, + ], + }); + expect(snapshot?.revision, 7); + expect(snapshot?.entries.map((entry) => entry.sessionId), ['ses_a', 'ses_b']); + expect(snapshot?.entries.first.floating, isTrue); + }); + + test('rejects duplicate and oversized snapshots', () { + expect( + ChatOpenWorkspaceSnapshot.fromJson({ + 'entries': [ + {'session_id': 'ses_a'}, + {'session_id': 'ses_a'}, + ], + }), + isNull, + ); + expect( + ChatOpenWorkspaceSnapshot.fromJson({ + 'entries': List.generate(65, (index) => {'session_id': 'ses_$index'}), + }), + isNull, + ); + }); +} diff --git a/internal/pipeline/chat_open_workspace.go b/internal/pipeline/chat_open_workspace.go new file mode 100644 index 00000000..71aac61f --- /dev/null +++ b/internal/pipeline/chat_open_workspace.go @@ -0,0 +1,125 @@ +package pipeline + +import ( + "context" + "database/sql" + "encoding/json" + "fmt" + "strings" + "time" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +const chatOpenWorkspaceLimit = 64 + +func (s *Store) initChatOpenWorkspace() error { + _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS chat_open_workspaces ( +scope TEXT PRIMARY KEY, entries_json TEXT NOT NULL, revision INTEGER NOT NULL DEFAULT 0, +updated_at INTEGER NOT NULL DEFAULT 0 +);`) + return err +} + +func validateOpenWorkspace(entries []protocol.ChatOpenWorkspaceEntry) error { + if len(entries) > chatOpenWorkspaceLimit { + return fmt.Errorf("too many open chats") + } + seen := make(map[string]struct{}, len(entries)) + for _, entry := range entries { + id := strings.TrimSpace(entry.SessionID) + if id == "" || len(id) > 200 { + return fmt.Errorf("invalid open chat session id") + } + if _, ok := seen[id]; ok { + return fmt.Errorf("duplicate open chat session id %q", id) + } + seen[id] = struct{}{} + } + return nil +} + +func decodeOpenWorkspace(raw string) ([]protocol.ChatOpenWorkspaceEntry, error) { + var entries []protocol.ChatOpenWorkspaceEntry + if err := json.Unmarshal([]byte(raw), &entries); err != nil { + return nil, err + } + if err := validateOpenWorkspace(entries); err != nil { + return nil, err + } + return entries, nil +} + +func (s *Store) ChatOpenWorkspace(ctx context.Context, scope string) (protocol.ChatOpenWorkspaceSnapshot, error) { + var raw string + var snapshot protocol.ChatOpenWorkspaceSnapshot + err := s.db.QueryRowContext(ctx, `SELECT entries_json,revision FROM chat_open_workspaces WHERE scope=?`, scope).Scan(&raw, &snapshot.Revision) + if err == sql.ErrNoRows { + return snapshot, nil + } + if err != nil { + return snapshot, err + } + snapshot.Entries, err = decodeOpenWorkspace(raw) + return snapshot, err +} + +// SaveChatOpenWorkspace atomically applies a full snapshot. Seed never replaces +// a workspace that another device has already created. +func (s *Store) SaveChatOpenWorkspace(ctx context.Context, scope string, entries []protocol.ChatOpenWorkspaceEntry, seed bool) (protocol.ChatOpenWorkspaceSnapshot, error) { + if strings.TrimSpace(scope) == "" { + return protocol.ChatOpenWorkspaceSnapshot{}, fmt.Errorf("workspace scope is required") + } + if err := validateOpenWorkspace(entries); err != nil { + return protocol.ChatOpenWorkspaceSnapshot{}, err + } + raw, err := json.Marshal(entries) + if err != nil { + return protocol.ChatOpenWorkspaceSnapshot{}, err + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return protocol.ChatOpenWorkspaceSnapshot{}, err + } + defer tx.Rollback() + var old string + var revision int64 + err = tx.QueryRowContext(ctx, `SELECT entries_json,revision FROM chat_open_workspaces WHERE scope=?`, scope).Scan(&old, &revision) + if err == sql.ErrNoRows { + revision = 1 + _, err = tx.ExecContext(ctx, `INSERT INTO chat_open_workspaces(scope,entries_json,revision,updated_at) VALUES(?,?,?,?)`, scope, string(raw), revision, time.Now().UnixMilli()) + } else if err == nil { + if seed { + current, decodeErr := decodeOpenWorkspace(old) + if decodeErr != nil { + return protocol.ChatOpenWorkspaceSnapshot{}, decodeErr + } + if len(current) != 0 { + entries = current + raw, _ = json.Marshal(entries) + } else { + revision++ + } + } else { + revision++ + } + if len(entries) == 0 && seed && old != "" { + // An explicitly empty seed is still a valid seed; only a non-empty + // existing list wins the race above. + var current []protocol.ChatOpenWorkspaceEntry + current, _ = decodeOpenWorkspace(old) + if len(current) != 0 { + entries = current + raw, _ = json.Marshal(entries) + } + } + _, err = tx.ExecContext(ctx, `UPDATE chat_open_workspaces SET entries_json=?,revision=?,updated_at=? WHERE scope=?`, string(raw), revision, time.Now().UnixMilli(), scope) + } + if err != nil { + return protocol.ChatOpenWorkspaceSnapshot{}, err + } + if err = tx.Commit(); err != nil { + return protocol.ChatOpenWorkspaceSnapshot{}, err + } + return protocol.ChatOpenWorkspaceSnapshot{Revision: revision, Entries: entries}, nil +} diff --git a/internal/pipeline/chat_open_workspace_test.go b/internal/pipeline/chat_open_workspace_test.go new file mode 100644 index 00000000..f183be96 --- /dev/null +++ b/internal/pipeline/chat_open_workspace_test.go @@ -0,0 +1,59 @@ +package pipeline + +import ( + "context" + "testing" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +func TestChatOpenWorkspacePersistsAndSeedsOnce(t *testing.T) { + path := t.TempDir() + "/workspace.db" + ctx := context.Background() + store, err := Open(path) + if err != nil { + t.Fatal(err) + } + first := []protocol.ChatOpenWorkspaceEntry{{SessionID: "ses_a", Floating: true}} + snapshot, err := store.SaveChatOpenWorkspace(ctx, "default", first, true) + if err != nil { + t.Fatal(err) + } + if snapshot.Revision != 1 || len(snapshot.Entries) != 1 || !snapshot.Entries[0].Floating { + t.Fatalf("unexpected snapshot: %+v", snapshot) + } + second, err := store.SaveChatOpenWorkspace(ctx, "default", []protocol.ChatOpenWorkspaceEntry{{SessionID: "ses_b"}}, true) + if err != nil { + t.Fatal(err) + } + if len(second.Entries) != 1 || second.Entries[0].SessionID != "ses_a" { + t.Fatalf("seed replaced existing workspace: %+v", second) + } + if err := store.Close(); err != nil { + t.Fatal(err) + } + store, err = Open(path) + if err != nil { + t.Fatal(err) + } + defer store.Close() + loaded, err := store.ChatOpenWorkspace(ctx, "default") + if err != nil { + t.Fatal(err) + } + if loaded.Revision != 1 || loaded.Entries[0].SessionID != "ses_a" { + t.Fatalf("workspace did not survive restart: %+v", loaded) + } +} + +func TestChatOpenWorkspaceRejectsDuplicatesAndBounds(t *testing.T) { + store, err := Open(t.TempDir() + "/workspace.db") + if err != nil { + t.Fatal(err) + } + defer store.Close() + entries := []protocol.ChatOpenWorkspaceEntry{{SessionID: "ses_a"}, {SessionID: "ses_a"}} + if _, err := store.SaveChatOpenWorkspace(context.Background(), "default", entries, false); err == nil { + t.Fatal("duplicate workspace entries accepted") + } +} diff --git a/internal/pipeline/store.go b/internal/pipeline/store.go index 75493470..ef977dce 100644 --- a/internal/pipeline/store.go +++ b/internal/pipeline/store.go @@ -85,6 +85,10 @@ CREATE TABLE IF NOT EXISTS submissions (id INTEGER PRIMARY KEY, name TEXT NOT NU db.Close() return nil, err } + if err := s.initChatOpenWorkspace(); err != nil { + db.Close() + return nil, err + } if err := s.initServerSettings(); err != nil { db.Close() return nil, err diff --git a/internal/protocol/chat.go b/internal/protocol/chat.go index 3218a75f..9bc30673 100644 --- a/internal/protocol/chat.go +++ b/internal/protocol/chat.go @@ -81,6 +81,10 @@ const ( // takes a ChatQuery with SessionID and Color (a ChatColors name; null or "" // clears it) and echoes the updated session like chat_star. ChatColor = "chat_color" + // ChatOpenWorkspace replaces the bounded, server-authoritative ordered set + // of open operator chats. The reply and push carry the complete snapshot. + ChatOpenWorkspace = "chat_open_workspace" + ChatOpenWorkspaceChanged = "chat_open_workspace_changed" // ChatSessionChanged is pushed to every other open connection when a chat's // shared list metadata (colour, star, title) changes, carrying the updated // registry row in ChatSession, so each device's list updates live. diff --git a/internal/protocol/chat_open_workspace.go b/internal/protocol/chat_open_workspace.go new file mode 100644 index 00000000..c16ea661 --- /dev/null +++ b/internal/protocol/chat_open_workspace.go @@ -0,0 +1,20 @@ +package protocol + +// ChatOpenWorkspaceEntry is the server-owned part of one workspace pane. Layout +// geometry and pane ids deliberately do not cross the wire. +type ChatOpenWorkspaceEntry struct { + SessionID string `json:"session_id"` + Floating bool `json:"floating,omitempty"` +} + +type ChatOpenWorkspaceRequest struct { + Entries []ChatOpenWorkspaceEntry `json:"entries"` + // Seed is honored only when the server has no saved workspace yet. It makes + // migration from the old device-local snapshot race-safe. + Seed bool `json:"seed,omitempty"` +} + +type ChatOpenWorkspaceSnapshot struct { + Revision int64 `json:"revision"` + Entries []ChatOpenWorkspaceEntry `json:"entries"` +} diff --git a/internal/protocol/message.go b/internal/protocol/message.go index 66c0920d..c5236536 100644 --- a/internal/protocol/message.go +++ b/internal/protocol/message.go @@ -200,17 +200,19 @@ type Message struct { SearchResults *SearchResponse `json:"search_results,omitempty"` // Chat is the brokered OpenCode chat traffic (route B). See chat.go for the // per-type payload structs and the wire shapes they mirror. - ChatSessions []ChatSession `json:"chat_sessions,omitempty"` - ChatSession *ChatSession `json:"chat_session,omitempty"` - ChatCreate *ChatCreateRequest `json:"chat_create,omitempty"` - ChatAdopt *ChatAdoptRequest `json:"chat_adopt,omitempty"` - ChatQuery *ChatQuery `json:"chat_query,omitempty"` - ChatPrompt *ChatPromptRequest `json:"chat_prompt,omitempty"` - ChatMessages []ChatMessage `json:"chat_messages,omitempty"` - ChatHistory *ChatHistoryPage `json:"chat_history,omitempty"` - ChatEvent *ChatEventFrame `json:"chat_event,omitempty"` - ChatPermission *ChatPermissionFrame `json:"chat_permission,omitempty"` - ChatReply *ChatReplyRequest `json:"chat_reply,omitempty"` + ChatSessions []ChatSession `json:"chat_sessions,omitempty"` + ChatSession *ChatSession `json:"chat_session,omitempty"` + ChatOpenWorkspaceRequest *ChatOpenWorkspaceRequest `json:"chat_open_workspace_request,omitempty"` + ChatOpenWorkspace *ChatOpenWorkspaceSnapshot `json:"chat_open_workspace,omitempty"` + ChatCreate *ChatCreateRequest `json:"chat_create,omitempty"` + ChatAdopt *ChatAdoptRequest `json:"chat_adopt,omitempty"` + ChatQuery *ChatQuery `json:"chat_query,omitempty"` + ChatPrompt *ChatPromptRequest `json:"chat_prompt,omitempty"` + ChatMessages []ChatMessage `json:"chat_messages,omitempty"` + ChatHistory *ChatHistoryPage `json:"chat_history,omitempty"` + ChatEvent *ChatEventFrame `json:"chat_event,omitempty"` + ChatPermission *ChatPermissionFrame `json:"chat_permission,omitempty"` + ChatReply *ChatReplyRequest `json:"chat_reply,omitempty"` // ChatClose carries the outcome of a chat_close; the close and reopen // requests themselves ride on ChatQuery (the session id), matching // chat_messages/chat_interrupt. diff --git a/internal/server/chat.go b/internal/server/chat.go index b3d9b528..82d3536e 100644 --- a/internal/server/chat.go +++ b/internal/server/chat.go @@ -214,7 +214,11 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker handleChatDirectories(ctx, request, registry, write) return true case protocol.ChatClose: - handleChatClose(ctx, request, broker, hub, registry, write) + var store chatOpenWorkspaceStore + if candidate, ok := registry.(chatOpenWorkspaceStore); ok { + store = candidate + } + handleChatClose(ctx, request, broker, hub, registry, store, write) return true case protocol.ChatReopen: handleChatReopen(ctx, request, registry, write) @@ -225,6 +229,13 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker case protocol.ChatColor: handleChatColor(ctx, request, registry, hub.changes(), clientID, write) return true + case protocol.ChatOpenWorkspace: + var store chatOpenWorkspaceStore + if candidate, ok := registry.(chatOpenWorkspaceStore); ok { + store = candidate + } + handleChatOpenWorkspace(ctx, request, broker, registry, store, hub.changes(), clientID, write) + return true case protocol.ChatRename: handleChatRename(ctx, request, broker, registry, hub.changes(), clientID, write) return true diff --git a/internal/server/chat_close.go b/internal/server/chat_close.go index f69dde2d..a5cab98d 100644 --- a/internal/server/chat_close.go +++ b/internal/server/chat_close.go @@ -17,7 +17,7 @@ import ( // registry, not on one device. A session id that is not a recorded operator // session is refused before anything is written, so a pipeline-owned run session // is never touched. -func handleChatClose(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, registry operatorRegistry, write func(protocol.Message) error) { +func handleChatClose(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, registry operatorRegistry, store chatOpenWorkspaceStore, write func(protocol.Message) error) { if broker == nil { _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"}) return @@ -92,6 +92,22 @@ func handleChatClose(ctx context.Context, request protocol.Message, broker chatB // chat_sessions without a re-list. response.ChatSessions = []protocol.ChatSession{wire} _ = write(response) + if store != nil { + workspace, workspaceErr := store.ChatOpenWorkspace(ctx, chatWorkspaceScope) + if workspaceErr == nil { + kept := workspace.Entries[:0] + for _, entry := range workspace.Entries { + if entry.SessionID != sessionID { + kept = append(kept, entry) + } + } + if len(kept) != len(workspace.Entries) { + if updated, saveErr := store.SaveChatOpenWorkspace(ctx, chatWorkspaceScope, kept, false); saveErr == nil && hub != nil { + hub.changes().broadcastWorkspace("", updated) + } + } + } + } } // handleChatReopen clears the closed state of an operator chat session so it diff --git a/internal/server/chat_open_workspace.go b/internal/server/chat_open_workspace.go new file mode 100644 index 00000000..d9752197 --- /dev/null +++ b/internal/server/chat_open_workspace.go @@ -0,0 +1,118 @@ +package server + +import ( + "context" + "fmt" + "strings" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +const chatWorkspaceScope = "default" + +type chatOpenWorkspaceStore interface { + ChatOpenWorkspace(context.Context, string) (protocol.ChatOpenWorkspaceSnapshot, error) + SaveChatOpenWorkspace(context.Context, string, []protocol.ChatOpenWorkspaceEntry, bool) (protocol.ChatOpenWorkspaceSnapshot, error) +} + +func reconcileChatWorkspace(ctx context.Context, snapshot protocol.ChatOpenWorkspaceSnapshot, broker chatBroker, registry operatorRegistry, store chatOpenWorkspaceStore) (protocol.ChatOpenWorkspaceSnapshot, error) { + if broker == nil || registry == nil || store == nil { + return snapshot, nil + } + valid := make([]protocol.ChatOpenWorkspaceEntry, 0, len(snapshot.Entries)) + for _, entry := range snapshot.Entries { + row, found, err := registry.OperatorSession(ctx, entry.SessionID) + if err != nil { + return snapshot, err + } + if !found || row.ClosedAt != 0 { + continue + } + if _, live, err := broker.Session(ctx, entry.SessionID); err != nil { + return snapshot, err + } else if live { + valid = append(valid, entry) + } + } + if len(valid) == len(snapshot.Entries) { + return snapshot, nil + } + return store.SaveChatOpenWorkspace(ctx, chatWorkspaceScope, valid, false) +} + +func validateChatWorkspace(ctx context.Context, request protocol.Message, broker chatBroker, registry operatorRegistry) ([]protocol.ChatOpenWorkspaceEntry, error) { + if request.ChatOpenWorkspaceRequest == nil { + return nil, fmt.Errorf("chat_open_workspace_request is required") + } + entries := request.ChatOpenWorkspaceRequest.Entries + if len(entries) > 64 { + return nil, fmt.Errorf("too many open chats") + } + seen := map[string]bool{} + for i := range entries { + id := strings.TrimSpace(entries[i].SessionID) + if !validChatSessionID(id) || seen[id] { + return nil, fmt.Errorf("invalid or duplicate open chat session %q", id) + } + entries[i].SessionID = id + seen[id] = true + if registry == nil || broker == nil { + return nil, fmt.Errorf("chat workspace validation unavailable") + } + row, found, err := registry.OperatorSession(ctx, id) + if err != nil { + return nil, err + } + if !found || row.ClosedAt != 0 { + continue + } + if _, live, err := broker.Session(ctx, id); err != nil { + return nil, err + } else if !live { + continue + } + } + return entries, nil +} + +func handleChatOpenWorkspace(ctx context.Context, request protocol.Message, broker chatBroker, registry operatorRegistry, store chatOpenWorkspaceStore, changes *chatSessionChanges, clientID string, write func(protocol.Message) error) { + if store == nil { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat workspace persistence unavailable"}) + return + } + entries, err := validateChatWorkspace(ctx, request, broker, registry) + if err != nil { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) + return + } + // Invalid, closed, deleted, and replaced sessions are dropped rather than + // returned as errors: clients can never restore them from a stale snapshot. + valid := entries[:0] + for _, entry := range entries { + row, found, rowErr := registry.OperatorSession(ctx, entry.SessionID) + if rowErr != nil { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: rowErr.Error()}) + return + } + if !found || row.ClosedAt != 0 { + continue + } + _, live, sessionErr := broker.Session(ctx, entry.SessionID) + if sessionErr != nil { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: sessionErr.Error()}) + return + } + if live { + valid = append(valid, entry) + } + } + snapshot, err := store.SaveChatOpenWorkspace(ctx, chatWorkspaceScope, valid, request.ChatOpenWorkspaceRequest.Seed) + if err != nil { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) + return + } + _ = write(protocol.Message{Type: protocol.ChatOpenWorkspace, ID: request.ID, ChatOpenWorkspace: &snapshot}) + if changes != nil { + changes.broadcastWorkspace(clientID, snapshot) + } +} diff --git a/internal/server/chat_session_changes.go b/internal/server/chat_session_changes.go index 114c7dcb..609a6e19 100644 --- a/internal/server/chat_session_changes.go +++ b/internal/server/chat_session_changes.go @@ -62,6 +62,22 @@ func (c *chatSessionChanges) broadcast(sender string, session protocol.ChatSessi } } +func (c *chatSessionChanges) broadcastWorkspace(sender string, snapshot protocol.ChatOpenWorkspaceSnapshot) { + c.mu.Lock() + targets := make([]func(protocol.Message) error, 0, len(c.clients)) + for id, write := range c.clients { + if id != sender { + targets = append(targets, write) + } + } + c.mu.Unlock() + for _, write := range targets { + copy := snapshot + copy.Entries = append([]protocol.ChatOpenWorkspaceEntry(nil), snapshot.Entries...) + go func() { _ = write(protocol.Message{Type: protocol.ChatOpenWorkspaceChanged, ChatOpenWorkspace: ©}) }() + } +} + // echoOperatorSession answers a metadata change with the updated registry row // and pushes the same row to every other connection. func echoOperatorSession(ctx context.Context, request protocol.Message, sessionID, reply string, registry operatorRegistry, changes *chatSessionChanges, clientID string, write func(protocol.Message) error) { diff --git a/internal/server/websocket.go b/internal/server/websocket.go index fe0ca6cc..71ed4ba0 100644 --- a/internal/server/websocket.go +++ b/internal/server/websocket.go @@ -261,6 +261,17 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin // connection the same way. hub.sessionChanges.attach(clientID, write) defer hub.sessionChanges.detach(clientID) + if workspaceStore, ok := registry.(chatOpenWorkspaceStore); ok { + if snapshot, err := workspaceStore.ChatOpenWorkspace(connCtx, chatWorkspaceScope); err == nil && snapshot.Revision > 0 { + snapshot, err = reconcileChatWorkspace(connCtx, snapshot, options.Chat, registry, workspaceStore) + if err != nil { + log.Printf("reconcile open chat workspace: %v", err) + } + if err == nil { + _ = write(protocol.Message{Type: protocol.ChatOpenWorkspaceChanged, ChatOpenWorkspace: &snapshot}) + } + } + } // Terminal lifecycle changes reach every connection; output only the // connections that opened or read that terminal. terminals.clients.attach(clientID, write) From b4701419d09023d40cf7712a805b754e79acec94 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 12 Nov 2026 03:11:02 +0000 Subject: [PATCH 5/7] Update permission card stop assertions Keep the permission-card regression aligned with the redesigned running composer. Verify that the composer stop control is absent and Stop remains available through the More menu while the turn runs. --- app/notes/composer-running-border.md | 15 +++++++++++++++ .../conversation/chat_permission_card_test.dart | 17 ++++++++++++++--- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/app/notes/composer-running-border.md b/app/notes/composer-running-border.md index e46c7762..7b5f934c 100644 --- a/app/notes/composer-running-border.md +++ b/app/notes/composer-running-border.md @@ -34,6 +34,21 @@ `tool/analyze.sh` (whole app): clean, exit 0. +## Land-gate fix (visit 2) + +`chat_permission_card_test.dart`: "a turn waiting on a pending card hides the +running indicator but keeps Stop" asserted a `Stop` tooltip on the composer, +which this change removes by design. It now asserts no `chat-composer-stop` +and that Stop is in the More menu, before and after the permission resolves. +Expectations for behaviour this change did not touch are unchanged. + +| Run | Paths | Result | +|---|---|---| +| 3 | `chat_permission_card_test`, `chat_thread_stop_menu_test` | PASS 15/15 | +| 4 | all six focused paths above (escape, spinner, running, stop menu, bar state, permission card) | PASS 44/44 | + +`tool/analyze.sh`: clean, exit 0. + ## Affected states (widget tests) - Running: no `chat-composer-stop`; Send present; border present; no interrupt sent. diff --git a/app/test/features/chat/conversation/chat_permission_card_test.dart b/app/test/features/chat/conversation/chat_permission_card_test.dart index feb04d37..969fa534 100644 --- a/app/test/features/chat/conversation/chat_permission_card_test.dart +++ b/app/test/features/chat/conversation/chat_permission_card_test.dart @@ -38,6 +38,15 @@ JsonMap permission({ if (decision.isNotEmpty) 'decision': decision, }; +Future expectStopInMoreMenu(WidgetTester tester) async { + await tester.tap(find.byTooltip('More actions').hitTestable().first); + await tester.pumpAndSettle(); + expect(find.text('Stop'), findsOneWidget); + await tester.tapAt(const Offset(1, 1)); + await tester.pumpAndSettle(); + expect(find.text('Stop'), findsNothing); +} + void main() { test('recorded action, risk and options survive the card model', () { final card = chatPermissionCard(permission(), '')!; @@ -331,7 +340,8 @@ void main() { await tester.pumpAndSettle(); expect(find.text('Approve bash'), findsOneWidget); - expect(find.byTooltip('Stop'), findsOneWidget); + expect(find.byKey(const Key('chat-composer-stop')), findsNothing); + await expectStopInMoreMenu(tester); gateway.emitRaw({ 'type': 'chat_permission', @@ -339,9 +349,10 @@ void main() { }); await tester.pumpAndSettle(); - // No filler line while the turn runs; Stop is the running signal. + // No filler line while the turn runs; the More menu keeps Stop reachable. expect(find.byKey(const Key('chat-running')), findsNothing); - expect(find.byTooltip('Stop'), findsOneWidget); + expect(find.byKey(const Key('chat-composer-stop')), findsNothing); + await expectStopInMoreMenu(tester); }); testWidgets('consecutive Material cards stay separate surfaces', ( From ae5e00326c8262934dcb9217f6b32f4d813c57a1 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 12 Nov 2026 03:21:38 +0000 Subject: [PATCH 6/7] Keep unengaged open chats unread Update the live-chat regression and note to reflect that replies received while a chat is merely open are not acknowledged as seen. This preserves phone notifications until the user actually interacts with the chat. --- app/notes/chat-seen-only-after-interaction.md | 14 +++++- .../sessions/chat_sessions_live_new_test.dart | 47 ++++++++++--------- 2 files changed, 38 insertions(+), 23 deletions(-) diff --git a/app/notes/chat-seen-only-after-interaction.md b/app/notes/chat-seen-only-after-interaction.md index 1a046f83..2bde5826 100644 --- a/app/notes/chat-seen-only-after-interaction.md +++ b/app/notes/chat-seen-only-after-interaction.md @@ -83,7 +83,19 @@ notifications on the watermark. `chat_color_test`, `chat_star_optimistic_test`, `chat_state_legibility_test`, `chat_visibility_marker_test`, `chat_add_pane_picker_test`, `chat_session_local_state_test`, `server_connections_recovery_test`) pass - unchanged. No expectation was edited. + unchanged, except one expectation (below). +- Land-gate fix: `test/features/chat/ui/sessions/chat_sessions_live_new_test.dart` + "a tool call and reply in the open chat stay read on leaving" failed in the + full `test/features test/shell test/ui test/core` run. The chat was open with + no user interaction, so under the new rule the reply is not seen. The test + was renamed to "...stay New on leaving without interaction" and now expects + the `chat-row-unread` dot and `isUnseen('s1')` after the chat is left. Its + open-chat assertion (no dot while open) is unchanged. This is the one + behaviour change the task asked for; no other expectation changed. +- Focused rerun after that fix: `chat_sessions_live_new_test.dart`, + `conversation/chat_seen_interaction_test.dart`, + `ui/sessions/chat_seen_interaction_test.dart`: 34 passed, 0 failed (memwatch + PASS, peak 1182 MB, names only those three paths). `tool/analyze.sh`: clean. ## Limitations diff --git a/app/test/features/chat/ui/sessions/chat_sessions_live_new_test.dart b/app/test/features/chat/ui/sessions/chat_sessions_live_new_test.dart index 6e0c6e29..a01e4c1d 100644 --- a/app/test/features/chat/ui/sessions/chat_sessions_live_new_test.dart +++ b/app/test/features/chat/ui/sessions/chat_sessions_live_new_test.dart @@ -229,29 +229,32 @@ void main() { expect(find.byKey(const Key('chat-row-unread')), findsOneWidget); }); - testWidgets('a tool call and reply in the open chat stay read on leaving', ( - tester, - ) async { - final fake = gateway(); - await _pump(tester, fake, active: 's1'); - fake.pushed.add(_tool('s1', 'running')); - fake.pushed.add(_tool('s1', 'completed')); - fake.pushed.add(_event('s1', delta: 'Here is the answer.')); - fake.pushed.add({ - 'type': 'chat_event', - 'chat_event': { - 'session_id': 's1', - 'kind': 'step', - 'step': {'status': 'ended'}, - }, - }); - await tester.pumpAndSettle(); - expect(find.byKey(const Key('chat-row-unread')), findsNothing); + testWidgets( + 'a tool call and reply in the open chat stay New on leaving without interaction', + (tester) async { + final fake = gateway(); + await _pump(tester, fake, active: 's1'); + fake.pushed.add(_tool('s1', 'running')); + fake.pushed.add(_tool('s1', 'completed')); + fake.pushed.add(_event('s1', delta: 'Here is the answer.')); + fake.pushed.add({ + 'type': 'chat_event', + 'chat_event': { + 'session_id': 's1', + 'kind': 'step', + 'step': {'status': 'ended'}, + }, + }); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('chat-row-unread')), findsNothing); - await _pump(tester, fake); - expect(find.byKey(const Key('chat-row-unread')), findsNothing); - expect(_store.state?.isUnseen('s1') ?? false, isFalse); - }); + // The chat was open but the user never interacted with it, so the + // reply is not seen: it stays New after the chat is left. + await _pump(tester, fake); + expect(find.byKey(const Key('chat-row-unread')), findsOneWidget); + expect(_store.state?.isUnseen('s1') ?? false, isTrue); + }, + ); testWidgets('only unresolved permission requests mark New', (tester) async { final fake = gateway(); From 4f8e99f316a2ba7b1a26bc8bf8db8d4b4bb2019a Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 12 Nov 2026 03:23:22 +0000 Subject: [PATCH 7/7] Serialize open-chat sync writes by server revision and fan out prunes Server: chat_open_workspace is a compare-and-swap on base_revision; a stale write is refused and answered with the current snapshot (rejected: true). Each stored change increments the revision; identical writes store nothing. A request with no body reads the set. Seeds apply only to a never-stored set. Validation uses the operator registry (recorded, not closed). chat_close and connection-time pruning store a new revision and push it to every connection; otherwise a new connection gets the current set to catch up. App: ChatOpenWorkspaceController keeps one write in flight, coalesces later changes, sends from the last replied revision and ignores lower revisions; pushes and rejected replies win over unsent changes. It starts after the local layout restores (seed or read), keeps a deep-linked chat, and is disposed on server/gateway rebind. Remote membership is applied by reconcileChatWorkspaceTree, keeping pane ids and split sizes. Federated lists keep their local layout. Tests: Go store/handler fan-out tests; app controller, reconcile and screen sync tests. Notes record a live two-client scratch check. --- app/lib/features/chat/chat_screen_float.dart | 12 +- .../features/chat/chat_screen_workspace.dart | 91 +++++++- .../chat_open_workspace_controller.dart | 106 +++++++-- .../chat_open_workspace_gateway.dart | 41 +++- .../workspace/chat_workspace_controller.dart | 42 +--- .../workspace/chat_workspace_reconcile.dart | 118 ++++++++++ app/notes/chat-open-workspace-sync.md | 75 +++++-- .../chat/chat_open_workspace_sync_test.dart | 205 +++++++++++++++++ .../chat_open_workspace_controller_test.dart | 211 ++++++++++++++++++ .../chat_open_workspace_gateway_test.dart | 5 +- .../chat_workspace_reconcile_test.dart | 56 +++++ internal/pipeline/chat_open_workspace.go | 160 ++++++++----- internal/pipeline/chat_open_workspace_test.go | 90 ++++++-- internal/protocol/chat_open_workspace.go | 17 +- internal/server/chat.go | 12 +- internal/server/chat_close.go | 21 +- internal/server/chat_open_workspace.go | 180 +++++++++------ internal/server/chat_open_workspace_test.go | 147 ++++++++++++ internal/server/chat_session_changes.go | 6 + internal/server/websocket.go | 14 +- 20 files changed, 1333 insertions(+), 276 deletions(-) create mode 100644 app/lib/features/chat/workspace/chat_workspace_reconcile.dart create mode 100644 app/test/features/chat/chat_open_workspace_sync_test.dart create mode 100644 app/test/features/chat/workspace/chat_open_workspace_controller_test.dart create mode 100644 app/test/features/chat/workspace/chat_workspace_reconcile_test.dart create mode 100644 internal/server/chat_open_workspace_test.go diff --git a/app/lib/features/chat/chat_screen_float.dart b/app/lib/features/chat/chat_screen_float.dart index 40761a95..56e9638b 100644 --- a/app/lib/features/chat/chat_screen_float.dart +++ b/app/lib/features/chat/chat_screen_float.dart @@ -46,9 +46,7 @@ mixin _ChatScreenFloat on State, _ChatScreenWorkspace { final pane = _workspace.detach(paneId); if (pane == null) return; widget.windows?.float(pane.sessionId); - if (!_applyingServerWorkspace) { - unawaited(_openWorkspace?.replace(_serverWorkspaceEntries())); - } + _syncOpenWorkspace(); // Floating the last tiled chat leaves the list, as closing it does. if (_workspace.paneCount == 0) _back(); } @@ -64,9 +62,7 @@ mixin _ChatScreenFloat on State, _ChatScreenWorkspace { _floatPane(pane.id); } else { windows.float(id); - if (!_applyingServerWorkspace) { - unawaited(_openWorkspace?.replace(_serverWorkspaceEntries())); - } + _syncOpenWorkspace(); } } @@ -75,9 +71,7 @@ mixin _ChatScreenFloat on State, _ChatScreenWorkspace { _workspaceVisible = true; if (!_pageOpen && showsListBesideDetail(context)) _usedWorkspace = true; _workspace.dock(sessionId); - if (!_applyingServerWorkspace) { - unawaited(_openWorkspace?.replace(_serverWorkspaceEntries())); - } + _syncOpenWorkspace(); _composerFocus.request(sessionId); } diff --git a/app/lib/features/chat/chat_screen_workspace.dart b/app/lib/features/chat/chat_screen_workspace.dart index e1b6d7e3..65cea8d2 100644 --- a/app/lib/features/chat/chat_screen_workspace.dart +++ b/app/lib/features/chat/chat_screen_workspace.dart @@ -101,12 +101,42 @@ mixin _ChatScreenWorkspace on State { } } + /// Sends this device's open chats to the server, unless the change is the + /// server's own snapshot being applied. + void _syncOpenWorkspace() { + if (_applyingServerWorkspace) return; + _openWorkspace?.replace(_serverWorkspaceEntries()); + } + + /// Binds the server's open-chat set for [widget.gateway], disposing the + /// previous binding (its subscription and queued writes) first. A + /// federated list spans several servers, so it keeps its local layout. + void _bindOpenWorkspace({required Future after}) { + _openWorkspace?.dispose(); + _openWorkspace = null; + _openWorkspaceApplied = false; + if (!widget.persistWorkspace || widget.gateway is FederatedChatGateway) { + return; + } + final open = ChatOpenWorkspaceController(gateway: widget.gateway) + ..onChanged = _applyOpenWorkspace; + _openWorkspace = open; + // Seed from the restored local layout once it is restored. + unawaited( + after.then((_) async { + if (!mounted || open.disposed) return; + await open.start(local: _serverWorkspaceEntries()); + }), + ); + } + void _bindWorkspacePersistence() { - if (!widget.persistWorkspace) return; + if (!widget.persistWorkspace) { + _bindOpenWorkspace(after: Future.value()); + return; + } final scope = serverStorageScope(serverIdentity(widget.gateway)); _workspaceScope = scope; - _openWorkspace = ChatOpenWorkspaceController(gateway: widget.gateway) - ..onChanged = _applyOpenWorkspace; _workspaceBinding = ChatWorkspaceBinding( controller: _workspace, store: widget.gateway is FederatedChatGateway @@ -132,14 +162,35 @@ mixin _ChatScreenWorkspace on State { _publishWorkspaceRoute(); }, ); - unawaited( - _workspaceBinding!.start(initialSessionId: widget.initialSessionId), + _bindOpenWorkspace( + after: _workspaceBinding!.start( + initialSessionId: widget.initialSessionId, + ), ); - unawaited(_openWorkspace!.start(legacy: _serverWorkspaceEntries())); } + /// Whether a server snapshot was applied since binding. The first one keeps + /// the chat this visit was opened on (a deep link) and adds it if absent. + bool _openWorkspaceApplied = false; + + /// Applies the server's membership: windows and panes for chats it no + /// longer lists close, floating state follows it, and tiled chats take its + /// order while this device's split geometry stays. void _applyOpenWorkspace(ChatOpenWorkspaceSnapshot snapshot) { if (!mounted) return; + final initial = widget.initialSessionId ?? ''; + final first = !_openWorkspaceApplied; + final keepInitial = + first && + initial.isNotEmpty && + !snapshot.entries.any((entry) => entry.sessionId == initial); + _openWorkspaceApplied = true; + if (keepInitial) { + snapshot = ChatOpenWorkspaceSnapshot(snapshot.revision, [ + ...snapshot.entries, + ChatOpenWorkspaceEntry(initial), + ]); + } _applyingServerWorkspace = true; try { final windows = widget.windows; @@ -172,20 +223,44 @@ mixin _ChatScreenWorkspace on State { .where((entry) => !entry.floating) .map((entry) => entry.sessionId), ); + if (keepInitial) { + final pane = _workspace.panes + .where((pane) => pane.sessionId == initial) + .firstOrNull; + if (pane != null) _workspace.activate(pane.id); + } if (_workspace.paneCount == 0 && _workspaceVisible) _back(); } finally { _applyingServerWorkspace = false; } + // The first snapshot shows the server's chats as a restored layout does; + // later ones never pull this device into a chat another one opened. + if (first && _workspace.paneCount > 0 && !_workspaceVisible) { + setState(() { + _usedWorkspace = true; + _workspaceVisible = true; + }); + _publishWorkspaceRoute(); + } + if (keepInitial) _syncOpenWorkspace(); } bool _updateWorkspacePersistence(ChatScreen oldWidget) { final scope = serverStorageScope(serverIdentity(widget.gateway)); if (oldWidget.persistWorkspace == widget.persistWorkspace && (!widget.persistWorkspace || scope == _workspaceScope)) { + // Another connection to the same server: only the open-chat sync + // follows the gateway. + if (widget.persistWorkspace && + !identical(oldWidget.gateway, widget.gateway)) { + _bindOpenWorkspace(after: Future.value()); + } return false; } _workspaceBinding?.dispose(); _workspaceBinding = null; + _openWorkspace?.dispose(); + _openWorkspace = null; if (_workspaceScope != null && scope != _workspaceScope) { _workspace.restoreLayout(ChatWorkspaceSnapshot.fromLayout(null, null)!); _workspaceVisible = false; @@ -261,9 +336,7 @@ mixin _ChatScreenWorkspace on State { '${_workspace.activePaneId}:${_workspace.panes.map((p) => '${p.id}=${p.sessionId}').join(',')}'; if (_workspaceSignature == signature) return; _workspaceSignature = signature; - if (!_applyingServerWorkspace) { - unawaited(_openWorkspace?.replace(_serverWorkspaceEntries())); - } + _syncOpenWorkspace(); void update() { if (!mounted) return; setState(() {}); diff --git a/app/lib/features/chat/workspace/chat_open_workspace_controller.dart b/app/lib/features/chat/workspace/chat_open_workspace_controller.dart index e1ebaba8..3448b9fa 100644 --- a/app/lib/features/chat/workspace/chat_open_workspace_controller.dart +++ b/app/lib/features/chat/workspace/chat_open_workspace_controller.dart @@ -1,43 +1,115 @@ import 'dart:async'; -import '../../../../core/api_gateway.dart'; +import '../../../core/api_gateway.dart'; import 'chat_open_workspace_gateway.dart'; +/// Keeps one device's open chats in step with the server's open-chat set. +/// +/// Writes are serialized: one is in flight at a time, and changes made while +/// it is pending coalesce into the latest full snapshot, sent next from the +/// revision the reply reported. Every reply and push is reconciled by server +/// revision, so a late or reordered one never overwrites newer state. A +/// snapshot from another device (or a refused stale write) wins over local +/// changes not yet sent, and reaches [onChanged]. class ChatOpenWorkspaceController { ChatOpenWorkspaceController({required ApiGateway gateway}) : _gateway = ChatOpenWorkspaceGateway(gateway); final ChatOpenWorkspaceGateway _gateway; StreamSubscription? _subscription; - int revision = 0; bool _disposed = false; + bool _writing = false; + List? _pending; + ChatOpenWorkspaceSnapshot? _current; + + /// Applies a server snapshot to the device's panes and windows. void Function(ChatOpenWorkspaceSnapshot snapshot)? onChanged; + + /// The latest server revision this device has seen; 0 before any. + int get revision => _current?.revision ?? 0; + + /// Whether the server answered, so local changes are sent. Before that (or + /// against a server without the request) the device keeps its own layout. + bool get ready => _current != null; + + bool get disposed => _disposed; + + /// Subscribes to pushes, then seeds the server from [local] (the device's + /// restored layout, migrated once from the old local snapshot) or, with no + /// local chats, reads the server's set. The server's answer is applied. Future start({ - Iterable legacy = const [], + Iterable local = const [], }) async { if (_subscription != null || _disposed) return; - _subscription = _gateway.changes.listen((snapshot) { - if (_disposed || snapshot.revision < revision) return; - revision = snapshot.revision; - onChanged?.call(snapshot); - }); - if (legacy.isNotEmpty) { - final snapshot = await _gateway.replace(legacy, seed: true); - if (snapshot != null && snapshot.revision >= revision) { - revision = snapshot.revision; - onChanged?.call(snapshot); + _subscription = _gateway.changes.listen(_accept); + final entries = local.toList(growable: false); + ChatOpenWorkspaceSnapshot? snapshot; + try { + snapshot = entries.isEmpty + ? await _gateway.read() + : await _gateway.replace(entries, seed: true); + } on Object { + return; + } + if (snapshot != null) _accept(snapshot, force: true); + } + + /// Sends the device's full open-chat set. Ignored until [ready]; coalesced + /// while a write is in flight. + void replace(Iterable entries) { + if (_disposed || !ready) return; + _pending = entries.toList(growable: false); + if (!_writing) unawaited(_drain()); + } + + Future _drain() async { + _writing = true; + try { + while (!_disposed) { + final sent = _pending; + _pending = null; + if (sent == null) return; + final current = _current; + if (current != null && current.sameEntries(sent)) continue; + ChatOpenWorkspaceSnapshot? reply; + try { + reply = await _gateway.replace(sent, baseRevision: revision); + } on Object { + reply = null; + } + if (_disposed || reply == null || reply.revision < revision) continue; + if (reply.rejected) { + // Another change landed first: the server's state wins over this + // write and anything queued behind it. + _accept(reply, force: true); + } else { + // The server may have left out closed or unknown chats. This device + // keeps showing them (a closed chat can still be read here); the + // other devices never receive them. + _current = reply; + } } + } finally { + _writing = false; } } - Future replace(Iterable entries) async { + void _accept(ChatOpenWorkspaceSnapshot snapshot, {bool force = false}) { if (_disposed) return; - final snapshot = await _gateway.replace(entries); - if (snapshot != null && snapshot.revision >= revision) { - revision = snapshot.revision; + final current = _current; + if (current != null && + (snapshot.revision < current.revision || + (!force && snapshot.revision == current.revision))) { + return; } + _current = snapshot; + _pending = null; + onChanged?.call(snapshot); } void dispose() { _disposed = true; + _pending = null; + onChanged = null; unawaited(_subscription?.cancel()); + _subscription = null; } } diff --git a/app/lib/features/chat/workspace/chat_open_workspace_gateway.dart b/app/lib/features/chat/workspace/chat_open_workspace_gateway.dart index 95405440..b5bf1df1 100644 --- a/app/lib/features/chat/workspace/chat_open_workspace_gateway.dart +++ b/app/lib/features/chat/workspace/chat_open_workspace_gateway.dart @@ -1,5 +1,7 @@ -import '../../../../core/api_gateway.dart'; +import '../../../core/api_gateway.dart'; +/// One chat in the server-owned open-chat set: its session and whether it is +/// floating. Geometry stays on the device. class ChatOpenWorkspaceEntry { const ChatOpenWorkspaceEntry(this.sessionId, {this.floating = false}); final String sessionId; @@ -17,10 +19,31 @@ class ChatOpenWorkspaceEntry { } } +/// The complete open-chat set at one server revision. [rejected] marks the +/// reply to a write from a stale base: the write was not applied and this is +/// the current state. class ChatOpenWorkspaceSnapshot { - const ChatOpenWorkspaceSnapshot(this.revision, this.entries); + const ChatOpenWorkspaceSnapshot( + this.revision, + this.entries, { + this.rejected = false, + }); final int revision; final List entries; + final bool rejected; + + bool sameEntries(Iterable other) { + final list = other.toList(growable: false); + if (list.length != entries.length) return false; + for (var i = 0; i < list.length; i++) { + if (list[i].sessionId != entries[i].sessionId || + list[i].floating != entries[i].floating) { + return false; + } + } + return true; + } + static ChatOpenWorkspaceSnapshot? fromJson(Object? value) { if (value is! Map || value['entries'] is! List) return null; final entries = []; @@ -36,15 +59,28 @@ class ChatOpenWorkspaceSnapshot { return ChatOpenWorkspaceSnapshot( (value['revision'] as num?)?.toInt() ?? 0, List.unmodifiable(entries), + rejected: value['rejected'] == true, ); } } +/// The `chat_open_workspace` request and its `chat_open_workspace_changed` +/// push, decoded. class ChatOpenWorkspaceGateway { ChatOpenWorkspaceGateway(this.gateway); final ApiGateway gateway; + + /// The current snapshot, without changing it. + Future read() async { + final response = await gateway.call('chat_open_workspace'); + return ChatOpenWorkspaceSnapshot.fromJson(response['chat_open_workspace']); + } + + /// Replaces the set, derived from [baseRevision]. A [seed] applies only + /// when the server never stored a set and otherwise returns the stored one. Future replace( Iterable entries, { + int baseRevision = 0, bool seed = false, }) async { final response = await gateway.call('chat_open_workspace', { @@ -52,6 +88,7 @@ class ChatOpenWorkspaceGateway { 'entries': entries .map((entry) => entry.toJson()) .toList(growable: false), + 'base_revision': baseRevision, if (seed) 'seed': true, }, }); diff --git a/app/lib/features/chat/workspace/chat_workspace_controller.dart b/app/lib/features/chat/workspace/chat_workspace_controller.dart index 0a7dc270..fdc825a5 100644 --- a/app/lib/features/chat/workspace/chat_workspace_controller.dart +++ b/app/lib/features/chat/workspace/chat_workspace_controller.dart @@ -1,6 +1,7 @@ import 'package:flutter/foundation.dart'; import 'chat_workspace_nodes.dart'; +import 'chat_workspace_reconcile.dart'; import 'chat_workspace_snapshot.dart'; export 'chat_workspace_nodes.dart'; @@ -203,45 +204,20 @@ class ChatWorkspaceController extends ChangeNotifier { _changed(); } - /// Reconciles tiled membership and order without discarding the local split - /// geometry. Floating membership is handled by the window host. + /// Tiles exactly [sessionIds] in order, as the server's open-chat set + /// names them, keeping this device's geometry (see + /// [reconcileChatWorkspaceTree]). Floating membership is the window host's. void reconcileSessions(Iterable sessionIds) { final wanted = []; final seen = {}; for (final id in sessionIds) { if (id.isNotEmpty && seen.add(id)) wanted.add(id); } - final current = panes; - if (wanted.isEmpty) { - if (_root == null) return; - _root = null; - _active = null; - _changed(); - return; - } - final retained = current.take(wanted.length).toList(); - for (var i = 0; i < retained.length; i++) { - final pane = retained[i]; - final id = wanted[i]; - if (pane.sessionId != id) { - _root = _replace(_root!, pane.id, ChatWorkspacePane(pane.id, id)); - } - } - for (final pane in current.skip(wanted.length).toList()) { - _root = _remove(_root!, pane.id); - } - if (retained.isEmpty) { - final pane = ChatWorkspacePane(_id('pane'), wanted.first); - _root = pane; - _active = pane.id; - } else { - for (final id in wanted.skip(retained.length)) { - splitActive(id, ChatSplitAxis.horizontal); - } - } - if (_active == null || !panes.any((pane) => pane.id == _active)) { - _active = panes.first.id; - } + final next = reconcileChatWorkspaceTree(_root, wanted, _id); + if (identical(next, _root)) return; + _root = next; + final ids = panes.map((pane) => pane.id).toSet(); + if (!ids.contains(_active)) _active = ids.firstOrNull; _changed(); } diff --git a/app/lib/features/chat/workspace/chat_workspace_reconcile.dart b/app/lib/features/chat/workspace/chat_workspace_reconcile.dart new file mode 100644 index 00000000..537cccf9 --- /dev/null +++ b/app/lib/features/chat/workspace/chat_workspace_reconcile.dart @@ -0,0 +1,118 @@ +import 'chat_workspace_nodes.dart'; + +/// Returns [root] tiled with exactly [wanted] (distinct session ids) in +/// order, keeping the local geometry: panes whose chat left are removed with +/// their splits, surviving panes keep their ids and split sizes and move +/// between slots to follow the order, and new chats split off the last pane. +/// Returns [root] itself when it already matches. +ChatWorkspaceNode? reconcileChatWorkspaceTree( + ChatWorkspaceNode? root, + List wanted, + String Function(String kind) newId, +) { + if (wanted.isEmpty) return null; + final keep = wanted.toSet(); + final seen = {}; + var node = root == null ? null : _retain(root, keep, seen); + final leaves = node == null ? [] : _leaves(node).toList(); + final bySession = {for (final pane in leaves) pane.sessionId: pane}; + final order = wanted.where(bySession.containsKey).toList(); + var slot = 0; + if (node != null) { + node = _reorder(node, () => bySession[order[slot++]]!); + } + for (final id in wanted.where((id) => !bySession.containsKey(id))) { + final added = ChatWorkspacePane(newId('pane'), id); + if (node == null) { + node = added; + continue; + } + final last = _leaves(node).last; + node = _swapLeaf( + node, + last.id, + ChatWorkspaceSplit(newId('split'), ChatSplitAxis.horizontal, last, added), + ); + } + return _same(node, root) ? root : node; +} + +Iterable _leaves(ChatWorkspaceNode node) sync* { + if (node is ChatWorkspacePane) yield node; + if (node is ChatWorkspaceSplit) { + yield* _leaves(node.first); + yield* _leaves(node.second); + } +} + +/// Drops panes outside [keep] and repeats of a session already kept. +ChatWorkspaceNode? _retain( + ChatWorkspaceNode node, + Set keep, + Set seen, +) { + if (node is ChatWorkspacePane) { + return keep.contains(node.sessionId) && seen.add(node.sessionId) + ? node + : null; + } + final split = node as ChatWorkspaceSplit; + final first = _retain(split.first, keep, seen); + final second = _retain(split.second, keep, seen); + if (first == null) return second; + if (second == null) return first; + return ChatWorkspaceSplit( + split.id, + split.axis, + first, + second, + ratio: split.ratio, + ); +} + +ChatWorkspaceNode _reorder( + ChatWorkspaceNode node, + ChatWorkspacePane Function() next, +) { + if (node is ChatWorkspacePane) return next(); + final split = node as ChatWorkspaceSplit; + final first = _reorder(split.first, next); + return ChatWorkspaceSplit( + split.id, + split.axis, + first, + _reorder(split.second, next), + ratio: split.ratio, + ); +} + +ChatWorkspaceNode _swapLeaf( + ChatWorkspaceNode node, + String id, + ChatWorkspaceNode replacement, +) { + if (node.id == id) return replacement; + if (node is! ChatWorkspaceSplit) return node; + return ChatWorkspaceSplit( + node.id, + node.axis, + _swapLeaf(node.first, id, replacement), + _swapLeaf(node.second, id, replacement), + ratio: node.ratio, + ); +} + +bool _same(ChatWorkspaceNode? a, ChatWorkspaceNode? b) { + if (a == null || b == null) return a == b; + if (a is ChatWorkspacePane && b is ChatWorkspacePane) { + return a.id == b.id && a.sessionId == b.sessionId; + } + if (a is ChatWorkspaceSplit && b is ChatWorkspaceSplit) { + return a.id == b.id && + a.axis == b.axis && + a.ratio == b.ratio && + _same(a.first, b.first) && + _same(a.second, b.second); + } + return false; +} diff --git a/app/notes/chat-open-workspace-sync.md b/app/notes/chat-open-workspace-sync.md index a170cfcb..cd21250a 100644 --- a/app/notes/chat-open-workspace-sync.md +++ b/app/notes/chat-open-workspace-sync.md @@ -2,33 +2,62 @@ ## Behaviour -The authenticated `/connect` protocol now stores one bounded ordered workspace -per server scope. Entries contain only operator session ids and a floating bit. -Opening, closing, reordering, docking and floating publish a full authoritative -snapshot; other connections receive `chat_open_workspace_changed`. The first -client may seed an empty server snapshot from its legacy local layout. Split -ratios, pane ids, window rectangles and other presentation geometry remain local. +The authenticated `/connect` protocol stores one bounded ordered open-chat set +per server scope (`default`). Entries hold only an operator session id and a +floating bit; split ratios, pane ids and window rectangles stay on the device. -The server drops closed, missing, unowned, or no-longer-live broker sessions -before saving. The store caps membership at 64 entries and rejects duplicates or -invalid ids. Protocol and application parsers apply the same bounds. +* `chat_open_workspace` without `chat_open_workspace_request` reads the set. + With a request it replaces the set as a compare-and-swap on `base_revision`: + a write from a stale base is not applied and the reply carries the current + set with `rejected: true`. Each stored change increments `revision`; an + identical write stores nothing. +* `seed: true` applies only when the server never stored a set (even an + emptied set wins over an old device-local snapshot), so the migration from + the old local layout happens once. +* Stored changes are pushed to every other connection as + `chat_open_workspace_changed`. Pushes run on separate goroutines and can + arrive out of order; clients keep the highest revision. +* Only recorded, not-closed operator chats are kept (registry check; the broker + is not asked, so validation never starts a harness). `chat_close` drops the + chat and pushes the new revision to every connection. A new connection + prunes stale entries and pushes the result to all connections, else sends + the current set to the new connection only (reconnect catch-up). -## Security and limits +App (`ChatOpenWorkspaceController`): one write in flight at a time; later +changes coalesce into the newest full set, sent from the revision of the last +reply. Pushes and replies with a lower (or, for pushes, equal) revision are +ignored. A push or a rejected reply wins over unsent local changes. After the +local layout is restored, the device seeds (or, with no chats, reads) and +applies the answer; the first answer keeps a deep-linked chat. Server drops in +a successful reply are not applied locally, so a closed chat can still be read +on the device that opened it, but no other device receives it. Remote +membership is applied with `reconcileChatWorkspaceTree`: removed chats' panes +go, survivors keep pane ids and split sizes and move to follow the order, new +chats split off the last pane. The controller is disposed on a server or +gateway rebind. A federated (all-servers) list keeps its local layout. -Workspace writes use the existing authenticated websocket. The server requires -both an operator-session registry row and a live broker session, so pipeline-owned -or another user's ids cannot be retained. No credentials, transcripts, drafts, -tokens or geometry are persisted. The current scope is the authenticated local -server's single operator (`default`); multi-user identity is not yet modelled. +Ctrl+Tab: main's behaviour (floating chats when shown, else visible panes) is +kept; the single-pane recent-chat swap is removed there. ## Verification -* `go test ./internal/protocol -run 'Test.*Chat|Test.*Workspace'` — passed. -* `go test ./internal/pipeline -run 'TestChatOpenWorkspace'` — passed. -* `go test ./internal/server -run 'TestChat(Open|Close|NewSession)|TestEmbeddedSchedulesReadOnlyOverWebSocket|TestStorageWebsocketProtocolAndNoStartupCleanup|TestTemplatesDoNotSeedDatabaseAndCreateOnlyPreservesExisting'` — passed. -* `go build ./cmd/pipelines-server` — passed. -* `cd app && tool/memwatch/full.sh 'test/features/chat/workspace/chat_open_workspace_gateway_test.dart test/features/chat/workspace/chat_workspace_binding_test.dart'` — 7 passed, 0 failed, 0 skipped; peak 800 MB; exit 0. -* `cd app && tool/analyze.sh` — clean; 0 errors, 0 warnings, 2 infos before the brace cleanup; rerun after cleanup was not captured. +* Go: `internal/pipeline` `TestChatOpenWorkspace*` (seed once, stale revision, + remove, bounds); `internal/server` `TestChatOpenWorkspaceSyncsEveryConnection` + (two connections get the same snapshot, stale write rejected, reorder, + close pruned and pushed to both, closed chat not restorable) and + `TestChatOpenWorkspacePrunesOnConnectForEveryone`. +* App: `test/features/chat/workspace/chat_open_workspace_controller_test.dart` + (serialized writes, late reply vs newer push, rejected write, dispose), + `chat_workspace_reconcile_test.dart`, and + `test/features/chat/chat_open_workspace_sync_test.dart` (seed migration, + remote removal drops the pane, server set wins over an old local snapshot, + rebind disposes the old sync). +* Live two-client check (2026-11-12): server built from this worktree, run on + an OS-assigned loopback port with a scratch HOME/XDG and database, three + scratch operator rows; a Node script drove two websocket clients through + read, open, reorder, stale write, float, pane close, `chat_close`, write-back + of the closed chat, and an out-of-band close pruned on a third connection. + All 16 checks passed (`RESULT: PASS`); every connection received the same + revisions. The scratch server and its own OpenCode child were stopped. -Not tested: a live two-client scratch websocket/broker check and rendered UI -captures. The shared server was not restarted or contacted. +Not verified: rendered UI captures and on-device behaviour. diff --git a/app/test/features/chat/chat_open_workspace_sync_test.dart b/app/test/features/chat/chat_open_workspace_sync_test.dart new file mode 100644 index 00000000..8b7c1379 --- /dev/null +++ b/app/test/features/chat/chat_open_workspace_sync_test.dart @@ -0,0 +1,205 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/servers/server_scope.dart'; +import 'package:pipelines_app/features/chat/screen.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace_store.dart'; +import 'package:pipelines_app/shell/adaptive_shell.dart'; +import 'package:pipelines_app/shell/destination.dart'; + +import 'conversation/chat_thread_fixtures.dart'; + +/// A chat server that keeps the open-chat set with the real revision rules: +/// a seed applies only to a never-stored set, a write from a stale base is +/// refused with the current set. +class _Server extends FakeChatGateway { + _Server({this.revision = 0, List open = const []}) + : open = List.of(open); + int revision; + List open; + final writes = >[]; + + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type == 'chat_sessions') { + return Future.value({ + 'chat_sessions': [ + for (final id in ['a', 'b', 'c', 'd']) + {'id': id, 'title': 'Chat $id'}, + ], + }); + } + if (type == 'chat_shells') return Future.value({'chat_shells': []}); + if (type == 'chat_open_workspace') return Future.value(_workspace(fields)); + return super.call(type, fields); + } + + JsonMap _workspace(JsonMap fields) { + final request = fields['chat_open_workspace_request'] as Map?; + var rejected = false; + if (request != null) { + final ids = [ + for (final entry in request['entries'] as List) + '${entry['session_id']}', + ]; + writes.add(ids); + if (request['seed'] == true) { + if (revision == 0) { + open = ids; + revision = 1; + } + } else if (request['base_revision'] != revision) { + rejected = true; + } else { + open = ids; + revision++; + } + } + return { + 'type': 'chat_open_workspace', + 'chat_open_workspace': _body(rejected), + }; + } + + JsonMap _body([bool rejected = false]) => { + 'revision': revision, + 'entries': [ + for (final id in open) {'session_id': id}, + ], + if (rejected) 'rejected': true, + }; + + /// Another device (or the server) changed the set. + void change(List ids) { + open = List.of(ids); + revision++; + emitRaw({ + 'type': 'chat_open_workspace_changed', + 'chat_open_workspace': _body(), + }); + } +} + +ChatWorkspaceController _workspace(WidgetTester tester) => + tester.widget(find.byType(ChatWorkspace)).controller; + +List _open(WidgetTester tester) => + _workspace(tester).panes.map((pane) => pane.sessionId).toList(); + +Future _mount(WidgetTester tester, _Server server) async { + await tester.pumpWidget( + MaterialApp( + home: AdaptiveShell( + destination: AppDestination.chat, + destinationBodies: { + AppDestination.chat: (_) => + ChatScreen(gateway: server, persistWorkspace: true), + }, + ), + ), + ); + await tester.pumpAndSettle(); +} + +_Server _server( + String identity, { + int revision = 0, + List open = const [], +}) { + final server = _Server(revision: revision, open: open) + ..history = (_) async => chatPage([]); + bindServerIdentity(server, identity); + addTearDown(server.close); + return server; +} + +void _saveLocal(String identity, List ids) { + final saved = ChatWorkspaceController()..open(ids.first); + for (final id in ids.skip(1)) { + saved.splitActive(id, ChatSplitAxis.horizontal); + } + SharedPreferences.setMockInitialValues({ + scopedServerKey(chatWorkspacePreferenceKey, identity): saved + .snapshot()! + .encode(), + }); +} + +void main() { + testWidgets( + 'the local layout seeds a new server and remote removal drops its pane', + (tester) async { + tester.view.physicalSize = const Size(1800, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + _saveLocal('server-a', ['a', 'b']); + final server = _server('server-a'); + await _mount(tester, server); + expect(server.revision, 1); + expect(server.open, ['a', 'b']); + expect(_open(tester), ['a', 'b']); + + server.change(['b']); + await tester.pumpAndSettle(); + expect(_open(tester), ['b']); + // Applying the server's change is not written back. + expect(server.writes, hasLength(1)); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pumpAndSettle(); + }, + ); + + testWidgets('an existing server set wins over an old local snapshot', ( + tester, + ) async { + tester.view.physicalSize = const Size(1800, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + _saveLocal('server-a', ['a']); + final server = _server('server-a', revision: 3, open: ['b', 'c']); + await _mount(tester, server); + expect(_open(tester), ['b', 'c']); + expect(server.open, ['b', 'c']); + expect(server.revision, 3); + // A local change is sent from the server's revision and accepted. + _workspace(tester).close(_workspace(tester).panes.first.id); + await tester.pumpAndSettle(); + expect(server.open, ['c']); + expect(server.revision, 4); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pumpAndSettle(); + }); + + testWidgets('rebinding to another server disposes the old sync', ( + tester, + ) async { + tester.view.physicalSize = const Size(1800, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + SharedPreferences.setMockInitialValues({}); + final first = _server('server-a', revision: 1, open: ['a']); + final second = _server('server-b', revision: 1, open: ['c']); + await _mount(tester, first); + expect(_open(tester), ['a']); + await _mount(tester, second); + expect(_open(tester), ['c']); + + // The old server's pushes no longer reach this screen. + first.change(['a', 'b', 'd']); + await tester.pumpAndSettle(); + expect(_open(tester), ['c']); + // The new server's do, and local changes go only to it. + second.change(['c', 'd']); + await tester.pumpAndSettle(); + expect(_open(tester), ['c', 'd']); + final firstWrites = first.writes.length; + _workspace(tester).close(_workspace(tester).panes.last.id); + await tester.pumpAndSettle(); + expect(second.open, ['c']); + expect(first.writes, hasLength(firstWrites)); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pumpAndSettle(); + }); +} diff --git a/app/test/features/chat/workspace/chat_open_workspace_controller_test.dart b/app/test/features/chat/workspace/chat_open_workspace_controller_test.dart new file mode 100644 index 00000000..d3d33438 --- /dev/null +++ b/app/test/features/chat/workspace/chat_open_workspace_controller_test.dart @@ -0,0 +1,211 @@ +import 'dart:async'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_open_workspace_controller.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_open_workspace_gateway.dart'; + +/// Answers each chat_open_workspace call only when the test completes it. +class _Gateway implements ApiGateway { + final requests = <({JsonMap fields, Completer reply})>[]; + final _frames = StreamController.broadcast(); + + @override + Future call(String type, [JsonMap fields = const {}]) { + final reply = Completer(); + requests.add((fields: fields, reply: reply)); + return reply.future; + } + + @override + Stream get frames => _frames.stream; + + void push(int revision, List ids) => _frames.add({ + 'type': 'chat_open_workspace_changed', + 'chat_open_workspace': _snapshot(revision, ids), + }); + + void answer( + int index, + int revision, + List ids, { + bool rejected = false, + }) => requests[index].reply.complete({ + 'type': 'chat_open_workspace', + 'chat_open_workspace': _snapshot(revision, ids, rejected: rejected), + }); + + List sentIds(int index) => [ + for (final entry + in (requests[index].fields['chat_open_workspace_request'] + as Map)['entries'] + as List) + '${entry['session_id']}', + ]; + + int base(int index) => + (requests[index].fields['chat_open_workspace_request'] + as Map)['base_revision']; +} + +JsonMap _snapshot(int revision, List ids, {bool rejected = false}) => { + 'revision': revision, + 'entries': [ + for (final id in ids) {'session_id': id}, + ], + if (rejected) 'rejected': true, +}; + +List _entries(List ids) => [ + for (final id in ids) ChatOpenWorkspaceEntry(id), +]; + +Future<(ChatOpenWorkspaceController, _Gateway, List>)> _started({ + int revision = 1, + List ids = const ['a'], +}) async { + final gateway = _Gateway(); + final applied = >[]; + final controller = ChatOpenWorkspaceController(gateway: gateway) + ..onChanged = (snapshot) => + applied.add(snapshot.entries.map((e) => e.sessionId).toList()); + final started = controller.start(local: _entries(ids)); + await pumpEventQueue(); + expect(gateway.requests.single.fields['chat_open_workspace_request'], { + 'entries': [ + for (final id in ids) {'session_id': id}, + ], + 'base_revision': 0, + 'seed': true, + }); + gateway.answer(0, revision, ids); + await started; + return (controller, gateway, applied); +} + +void main() { + test('reads instead of seeding when the device has no chats', () async { + final gateway = _Gateway(); + final controller = ChatOpenWorkspaceController(gateway: gateway); + final started = controller.start(); + await pumpEventQueue(); + expect(gateway.requests.single.fields, isEmpty); + gateway.answer(0, 4, ['x']); + await started; + expect(controller.revision, 4); + expect(controller.ready, isTrue); + }); + + test( + 'serializes writes and sends the latest from the replied revision', + () async { + final (controller, gateway, _) = await _started(); + controller.replace(_entries(['a', 'b'])); + controller.replace(_entries(['a', 'b', 'c'])); + controller.replace(_entries(['c', 'a', 'b'])); + await pumpEventQueue(); + // One write in flight; the two later ones coalesced behind it. + expect(gateway.requests, hasLength(2)); + expect(gateway.sentIds(1), ['a', 'b']); + expect(gateway.base(1), 1); + gateway.answer(1, 2, ['a', 'b']); + await pumpEventQueue(); + expect(gateway.requests, hasLength(3)); + expect(gateway.sentIds(2), ['c', 'a', 'b']); + expect(gateway.base(2), 2); + gateway.answer(2, 3, ['c', 'a', 'b']); + await pumpEventQueue(); + expect(controller.revision, 3); + // An unchanged set is not sent again. + controller.replace(_entries(['c', 'a', 'b'])); + await pumpEventQueue(); + expect(gateway.requests, hasLength(3)); + }, + ); + + test('a late reply never overwrites a newer pushed revision', () async { + final (controller, gateway, applied) = await _started(); + controller.replace(_entries(['a', 'b'])); + await pumpEventQueue(); + // Another device's change (revision 3) is pushed before this write's + // reply (revision 2) arrives. + gateway.push(3, ['z']); + await pumpEventQueue(); + gateway.answer(1, 2, ['a', 'b']); + await pumpEventQueue(); + expect(controller.revision, 3); + expect(applied.last, ['z']); + // Older and repeated pushes are ignored. + gateway.push(2, ['a', 'b']); + gateway.push(3, ['z']); + await pumpEventQueue(); + expect(applied, [ + ['a'], + ['z'], + ]); + }); + + test( + 'a refused stale write applies the server state and drops queued ones', + () async { + final (controller, gateway, applied) = await _started(); + controller.replace(_entries(['a', 'b'])); + await pumpEventQueue(); + controller.replace(_entries(['a', 'b', 'c'])); + gateway.answer(1, 5, ['q'], rejected: true); + await pumpEventQueue(); + expect(applied.last, ['q']); + expect(controller.revision, 5); + expect(gateway.requests, hasLength(2)); + // The next change is derived from the server's state. + controller.replace(_entries(['q', 'r'])); + await pumpEventQueue(); + expect(gateway.base(2), 5); + }, + ); + + test('a push applied while writing replaces the queued write', () async { + final (controller, gateway, applied) = await _started(); + controller.replace(_entries(['a', 'b'])); + await pumpEventQueue(); + controller.replace(_entries(['a', 'b', 'c'])); + gateway.push(4, ['b']); + await pumpEventQueue(); + expect(applied.last, ['b']); + gateway.answer(1, 4, ['b'], rejected: true); + await pumpEventQueue(); + expect(gateway.requests, hasLength(2)); + }); + + test('dispose stops pushes and writes', () async { + final (controller, gateway, applied) = await _started(); + controller.dispose(); + gateway.push(9, ['late']); + controller.replace(_entries(['x'])); + await pumpEventQueue(); + expect(applied, [ + ['a'], + ]); + expect(gateway.requests, hasLength(1)); + }); + + test( + 'stays local-only when the server does not answer the request', + () async { + final gateway = _Gateway(); + final controller = ChatOpenWorkspaceController(gateway: gateway); + final started = controller.start(local: _entries(['a'])); + await pumpEventQueue(); + gateway.requests.single.reply.completeError(StateError('unknown type')); + await started; + expect(controller.ready, isFalse); + controller.replace(_entries(['a', 'b'])); + await pumpEventQueue(); + expect(gateway.requests, hasLength(1)); + // A server push (a reconnect) brings it up to date and enables writes. + gateway.push(2, ['a']); + await pumpEventQueue(); + expect(controller.ready, isTrue); + }, + ); +} diff --git a/app/test/features/chat/workspace/chat_open_workspace_gateway_test.dart b/app/test/features/chat/workspace/chat_open_workspace_gateway_test.dart index f646d215..6d54ee9a 100644 --- a/app/test/features/chat/workspace/chat_open_workspace_gateway_test.dart +++ b/app/test/features/chat/workspace/chat_open_workspace_gateway_test.dart @@ -11,7 +11,10 @@ void main() { ], }); expect(snapshot?.revision, 7); - expect(snapshot?.entries.map((entry) => entry.sessionId), ['ses_a', 'ses_b']); + expect(snapshot?.entries.map((entry) => entry.sessionId), [ + 'ses_a', + 'ses_b', + ]); expect(snapshot?.entries.first.floating, isTrue); }); diff --git a/app/test/features/chat/workspace/chat_workspace_reconcile_test.dart b/app/test/features/chat/workspace/chat_workspace_reconcile_test.dart new file mode 100644 index 00000000..4ee23320 --- /dev/null +++ b/app/test/features/chat/workspace/chat_workspace_reconcile_test.dart @@ -0,0 +1,56 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace_controller.dart'; + +List _sessions(ChatWorkspaceController c) => + c.panes.map((pane) => pane.sessionId).toList(); + +ChatWorkspaceController _three() { + final c = ChatWorkspaceController()..open('a'); + c.splitActive('b', ChatSplitAxis.vertical); + c.splitActive('c', ChatSplitAxis.horizontal); + c.resize(c.root!.id, .3); + return c; +} + +void main() { + test('a remote removal drops only that pane and keeps the geometry', () { + final c = _three(); + final paneA = c.panes.first.id; + final paneC = c.panes.last.id; + c.reconcileSessions(['a', 'c']); + expect(_sessions(c), ['a', 'c']); + expect(c.panes.map((pane) => pane.id), [paneA, paneC]); + expect((c.root as ChatWorkspaceSplit).ratio, .3); + }); + + test('a reorder moves panes with their ids and keeps the splits', () { + final c = _three(); + final ids = {for (final pane in c.panes) pane.sessionId: pane.id}; + final splitId = c.root!.id; + c.reconcileSessions(['c', 'a', 'b']); + expect(_sessions(c), ['c', 'a', 'b']); + expect(c.panes.map((pane) => pane.id), [ids['c'], ids['a'], ids['b']]); + expect(c.root!.id, splitId); + expect((c.root as ChatWorkspaceSplit).ratio, .3); + }); + + test('new chats split off and an unchanged set notifies nothing', () { + final c = ChatWorkspaceController()..open('a'); + c.reconcileSessions(['a', 'b']); + expect(_sessions(c), ['a', 'b']); + var notified = 0; + c.addListener(() => notified++); + c.reconcileSessions(['a', 'b']); + expect(notified, 0); + c.reconcileSessions(const []); + expect(c.panes, isEmpty); + expect(c.activePane, isNull); + }); + + test('the active pane moves on when its chat is removed', () { + final c = _three(); + expect(c.activePane?.sessionId, 'c'); + c.reconcileSessions(['b']); + expect(c.activePane?.sessionId, 'b'); + }); +} diff --git a/internal/pipeline/chat_open_workspace.go b/internal/pipeline/chat_open_workspace.go index 71aac61f..8ee73fab 100644 --- a/internal/pipeline/chat_open_workspace.go +++ b/internal/pipeline/chat_open_workspace.go @@ -11,7 +11,8 @@ import ( "git.a-wan.net/alan/pipelines/internal/protocol" ) -const chatOpenWorkspaceLimit = 64 +// ChatOpenWorkspaceLimit bounds the open-chat set. +const ChatOpenWorkspaceLimit = 64 func (s *Store) initChatOpenWorkspace() error { _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS chat_open_workspaces ( @@ -22,13 +23,13 @@ updated_at INTEGER NOT NULL DEFAULT 0 } func validateOpenWorkspace(entries []protocol.ChatOpenWorkspaceEntry) error { - if len(entries) > chatOpenWorkspaceLimit { + if len(entries) > ChatOpenWorkspaceLimit { return fmt.Errorf("too many open chats") } seen := make(map[string]struct{}, len(entries)) for _, entry := range entries { id := strings.TrimSpace(entry.SessionID) - if id == "" || len(id) > 200 { + if id == "" || id != entry.SessionID || len(id) > 200 { return fmt.Errorf("invalid open chat session id") } if _, ok := seen[id]; ok { @@ -50,10 +51,32 @@ func decodeOpenWorkspace(raw string) ([]protocol.ChatOpenWorkspaceEntry, error) return entries, nil } +func sameOpenWorkspace(a, b []protocol.ChatOpenWorkspaceEntry) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + +// ChatOpenWorkspace reads the stored snapshot; revision 0 means none was ever +// stored. func (s *Store) ChatOpenWorkspace(ctx context.Context, scope string) (protocol.ChatOpenWorkspaceSnapshot, error) { + return readOpenWorkspace(ctx, s.db, scope) +} + +type rowQuerier interface { + QueryRowContext(context.Context, string, ...any) *sql.Row +} + +func readOpenWorkspace(ctx context.Context, db rowQuerier, scope string) (protocol.ChatOpenWorkspaceSnapshot, error) { var raw string - var snapshot protocol.ChatOpenWorkspaceSnapshot - err := s.db.QueryRowContext(ctx, `SELECT entries_json,revision FROM chat_open_workspaces WHERE scope=?`, scope).Scan(&raw, &snapshot.Revision) + snapshot := protocol.ChatOpenWorkspaceSnapshot{Entries: []protocol.ChatOpenWorkspaceEntry{}} + err := db.QueryRowContext(ctx, `SELECT entries_json,revision FROM chat_open_workspaces WHERE scope=?`, scope).Scan(&raw, &snapshot.Revision) if err == sql.ErrNoRows { return snapshot, nil } @@ -64,62 +87,93 @@ func (s *Store) ChatOpenWorkspace(ctx context.Context, scope string) (protocol.C return snapshot, err } -// SaveChatOpenWorkspace atomically applies a full snapshot. Seed never replaces -// a workspace that another device has already created. -func (s *Store) SaveChatOpenWorkspace(ctx context.Context, scope string, entries []protocol.ChatOpenWorkspaceEntry, seed bool) (protocol.ChatOpenWorkspaceSnapshot, error) { - if strings.TrimSpace(scope) == "" { - return protocol.ChatOpenWorkspaceSnapshot{}, fmt.Errorf("workspace scope is required") - } - if err := validateOpenWorkspace(entries); err != nil { - return protocol.ChatOpenWorkspaceSnapshot{}, err - } +func writeOpenWorkspace(ctx context.Context, tx *sql.Tx, scope string, revision int64, entries []protocol.ChatOpenWorkspaceEntry) error { raw, err := json.Marshal(entries) if err != nil { - return protocol.ChatOpenWorkspaceSnapshot{}, err + return err + } + _, err = tx.ExecContext(ctx, `INSERT INTO chat_open_workspaces(scope,entries_json,revision,updated_at) VALUES(?,?,?,?) +ON CONFLICT(scope) DO UPDATE SET entries_json=excluded.entries_json,revision=excluded.revision,updated_at=excluded.updated_at`, + scope, string(raw), revision, time.Now().UnixMilli()) + return err +} + +// SaveChatOpenWorkspace applies a full snapshot as one compare-and-swap. A +// write whose baseRevision is not the stored revision is not applied: the +// current snapshot is returned with Rejected set. A seed applies only when no +// workspace was ever stored and otherwise returns the stored one. changed +// reports whether a new revision was stored; an identical write stores none. +func (s *Store) SaveChatOpenWorkspace(ctx context.Context, scope string, entries []protocol.ChatOpenWorkspaceEntry, seed bool, baseRevision int64) (snapshot protocol.ChatOpenWorkspaceSnapshot, changed bool, err error) { + if strings.TrimSpace(scope) == "" { + return snapshot, false, fmt.Errorf("workspace scope is required") + } + if entries == nil { + entries = []protocol.ChatOpenWorkspaceEntry{} + } + if err := validateOpenWorkspace(entries); err != nil { + return snapshot, false, err } tx, err := s.db.BeginTx(ctx, nil) if err != nil { - return protocol.ChatOpenWorkspaceSnapshot{}, err + return snapshot, false, err } defer tx.Rollback() - var old string - var revision int64 - err = tx.QueryRowContext(ctx, `SELECT entries_json,revision FROM chat_open_workspaces WHERE scope=?`, scope).Scan(&old, &revision) - if err == sql.ErrNoRows { - revision = 1 - _, err = tx.ExecContext(ctx, `INSERT INTO chat_open_workspaces(scope,entries_json,revision,updated_at) VALUES(?,?,?,?)`, scope, string(raw), revision, time.Now().UnixMilli()) - } else if err == nil { - if seed { - current, decodeErr := decodeOpenWorkspace(old) - if decodeErr != nil { - return protocol.ChatOpenWorkspaceSnapshot{}, decodeErr - } - if len(current) != 0 { - entries = current - raw, _ = json.Marshal(entries) - } else { - revision++ - } - } else { - revision++ - } - if len(entries) == 0 && seed && old != "" { - // An explicitly empty seed is still a valid seed; only a non-empty - // existing list wins the race above. - var current []protocol.ChatOpenWorkspaceEntry - current, _ = decodeOpenWorkspace(old) - if len(current) != 0 { - entries = current - raw, _ = json.Marshal(entries) - } - } - _, err = tx.ExecContext(ctx, `UPDATE chat_open_workspaces SET entries_json=?,revision=?,updated_at=? WHERE scope=?`, string(raw), revision, time.Now().UnixMilli(), scope) - } + current, err := readOpenWorkspace(ctx, tx, scope) if err != nil { - return protocol.ChatOpenWorkspaceSnapshot{}, err + return snapshot, false, err } - if err = tx.Commit(); err != nil { - return protocol.ChatOpenWorkspaceSnapshot{}, err + if seed && current.Revision > 0 { + return current, false, nil } - return protocol.ChatOpenWorkspaceSnapshot{Revision: revision, Entries: entries}, nil + if !seed && baseRevision != current.Revision { + current.Rejected = true + return current, false, nil + } + if current.Revision > 0 && sameOpenWorkspace(current.Entries, entries) { + return current, false, nil + } + next := protocol.ChatOpenWorkspaceSnapshot{Revision: current.Revision + 1, Entries: entries} + if err := writeOpenWorkspace(ctx, tx, scope, next.Revision, entries); err != nil { + return snapshot, false, err + } + if err := tx.Commit(); err != nil { + return snapshot, false, err + } + return next, true, nil +} + +// RemoveChatOpenWorkspaceSessions drops the named sessions from the stored +// snapshot in one transaction, storing a new revision only when one was +// present. The server uses it for closed and no-longer-valid chats. +func (s *Store) RemoveChatOpenWorkspaceSessions(ctx context.Context, scope string, sessionIDs []string) (snapshot protocol.ChatOpenWorkspaceSnapshot, changed bool, err error) { + drop := make(map[string]bool, len(sessionIDs)) + for _, id := range sessionIDs { + drop[id] = true + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return snapshot, false, err + } + defer tx.Rollback() + current, err := readOpenWorkspace(ctx, tx, scope) + if err != nil || current.Revision == 0 { + return current, false, err + } + kept := make([]protocol.ChatOpenWorkspaceEntry, 0, len(current.Entries)) + for _, entry := range current.Entries { + if !drop[entry.SessionID] { + kept = append(kept, entry) + } + } + if len(kept) == len(current.Entries) { + return current, false, nil + } + next := protocol.ChatOpenWorkspaceSnapshot{Revision: current.Revision + 1, Entries: kept} + if err := writeOpenWorkspace(ctx, tx, scope, next.Revision, kept); err != nil { + return snapshot, false, err + } + if err := tx.Commit(); err != nil { + return snapshot, false, err + } + return next, true, nil } diff --git a/internal/pipeline/chat_open_workspace_test.go b/internal/pipeline/chat_open_workspace_test.go index f183be96..877ca1e9 100644 --- a/internal/pipeline/chat_open_workspace_test.go +++ b/internal/pipeline/chat_open_workspace_test.go @@ -2,58 +2,104 @@ package pipeline import ( "context" + "fmt" "testing" "git.a-wan.net/alan/pipelines/internal/protocol" ) -func TestChatOpenWorkspacePersistsAndSeedsOnce(t *testing.T) { - path := t.TempDir() + "/workspace.db" - ctx := context.Background() +func openWorkspaceStore(t *testing.T, path string) *Store { + t.Helper() store, err := Open(path) if err != nil { t.Fatal(err) } + return store +} + +func TestChatOpenWorkspacePersistsAndSeedsOnce(t *testing.T) { + path := t.TempDir() + "/workspace.db" + ctx := context.Background() + store := openWorkspaceStore(t, path) first := []protocol.ChatOpenWorkspaceEntry{{SessionID: "ses_a", Floating: true}} - snapshot, err := store.SaveChatOpenWorkspace(ctx, "default", first, true) - if err != nil { - t.Fatal(err) + snapshot, changed, err := store.SaveChatOpenWorkspace(ctx, "default", first, true, 0) + if err != nil || !changed { + t.Fatalf("seed: changed=%v err=%v", changed, err) } if snapshot.Revision != 1 || len(snapshot.Entries) != 1 || !snapshot.Entries[0].Floating { t.Fatalf("unexpected snapshot: %+v", snapshot) } - second, err := store.SaveChatOpenWorkspace(ctx, "default", []protocol.ChatOpenWorkspaceEntry{{SessionID: "ses_b"}}, true) - if err != nil { - t.Fatal(err) + second, changed, err := store.SaveChatOpenWorkspace(ctx, "default", []protocol.ChatOpenWorkspaceEntry{{SessionID: "ses_b"}}, true, 0) + if err != nil || changed || second.Rejected { + t.Fatalf("second seed: changed=%v rejected=%v err=%v", changed, second.Rejected, err) } if len(second.Entries) != 1 || second.Entries[0].SessionID != "ses_a" { t.Fatalf("seed replaced existing workspace: %+v", second) } + // An emptied workspace is still a stored workspace: an old device-local + // snapshot must not seed its chats back. + if _, _, err := store.SaveChatOpenWorkspace(ctx, "default", nil, false, 1); err != nil { + t.Fatal(err) + } + reseed, changed, err := store.SaveChatOpenWorkspace(ctx, "default", first, true, 0) + if err != nil || changed || len(reseed.Entries) != 0 || reseed.Revision != 2 { + t.Fatalf("seed restored an emptied workspace: %+v changed=%v err=%v", reseed, changed, err) + } if err := store.Close(); err != nil { t.Fatal(err) } - store, err = Open(path) - if err != nil { - t.Fatal(err) - } + store = openWorkspaceStore(t, path) defer store.Close() loaded, err := store.ChatOpenWorkspace(ctx, "default") if err != nil { t.Fatal(err) } - if loaded.Revision != 1 || loaded.Entries[0].SessionID != "ses_a" { + if loaded.Revision != 2 || len(loaded.Entries) != 0 { t.Fatalf("workspace did not survive restart: %+v", loaded) } } -func TestChatOpenWorkspaceRejectsDuplicatesAndBounds(t *testing.T) { - store, err := Open(t.TempDir() + "/workspace.db") - if err != nil { - t.Fatal(err) - } +func TestChatOpenWorkspaceRejectsStaleRevision(t *testing.T) { + store := openWorkspaceStore(t, t.TempDir()+"/workspace.db") defer store.Close() - entries := []protocol.ChatOpenWorkspaceEntry{{SessionID: "ses_a"}, {SessionID: "ses_a"}} - if _, err := store.SaveChatOpenWorkspace(context.Background(), "default", entries, false); err == nil { - t.Fatal("duplicate workspace entries accepted") + ctx := context.Background() + a := []protocol.ChatOpenWorkspaceEntry{{SessionID: "ses_a"}} + ab := []protocol.ChatOpenWorkspaceEntry{{SessionID: "ses_a"}, {SessionID: "ses_b"}} + if s, _, err := store.SaveChatOpenWorkspace(ctx, "default", a, false, 0); err != nil || s.Revision != 1 { + t.Fatalf("first write: %+v %v", s, err) + } + if s, _, err := store.SaveChatOpenWorkspace(ctx, "default", ab, false, 1); err != nil || s.Revision != 2 { + t.Fatalf("second write: %+v %v", s, err) + } + stale, changed, err := store.SaveChatOpenWorkspace(ctx, "default", nil, false, 1) + if err != nil || changed || !stale.Rejected || stale.Revision != 2 || len(stale.Entries) != 2 { + t.Fatalf("stale write = %+v changed=%v err=%v", stale, changed, err) + } + same, changed, err := store.SaveChatOpenWorkspace(ctx, "default", ab, false, 2) + if err != nil || changed || same.Revision != 2 { + t.Fatalf("identical write stored a revision: %+v changed=%v", same, changed) + } + removed, changed, err := store.RemoveChatOpenWorkspaceSessions(ctx, "default", []string{"ses_a", "ses_x"}) + if err != nil || !changed || removed.Revision != 3 || len(removed.Entries) != 1 || removed.Entries[0].SessionID != "ses_b" { + t.Fatalf("remove = %+v changed=%v err=%v", removed, changed, err) + } + if _, changed, _ := store.RemoveChatOpenWorkspaceSessions(ctx, "default", []string{"ses_a"}); changed { + t.Fatal("removing an absent chat stored a revision") + } +} + +func TestChatOpenWorkspaceRejectsDuplicatesAndBounds(t *testing.T) { + store := openWorkspaceStore(t, t.TempDir()+"/workspace.db") + defer store.Close() + entries := []protocol.ChatOpenWorkspaceEntry{{SessionID: "ses_a"}, {SessionID: "ses_a"}} + if _, _, err := store.SaveChatOpenWorkspace(context.Background(), "default", entries, false, 0); err == nil { + t.Fatal("duplicate workspace entries accepted") + } + many := make([]protocol.ChatOpenWorkspaceEntry, ChatOpenWorkspaceLimit+1) + for i := range many { + many[i].SessionID = fmt.Sprintf("ses_%d", i) + } + if _, _, err := store.SaveChatOpenWorkspace(context.Background(), "default", many, false, 0); err == nil { + t.Fatal("oversized workspace accepted") } } diff --git a/internal/protocol/chat_open_workspace.go b/internal/protocol/chat_open_workspace.go index c16ea661..4a30096b 100644 --- a/internal/protocol/chat_open_workspace.go +++ b/internal/protocol/chat_open_workspace.go @@ -7,14 +7,27 @@ type ChatOpenWorkspaceEntry struct { Floating bool `json:"floating,omitempty"` } +// ChatOpenWorkspaceRequest replaces the open-chat set. A chat_open_workspace +// without a request only reads the current snapshot. type ChatOpenWorkspaceRequest struct { Entries []ChatOpenWorkspaceEntry `json:"entries"` - // Seed is honored only when the server has no saved workspace yet. It makes - // migration from the old device-local snapshot race-safe. + // BaseRevision is the snapshot revision the client's entries were derived + // from. A write whose base is not the current revision is refused, and the + // reply carries the current snapshot with Rejected set, so a late write + // can never overwrite a newer change. + BaseRevision int64 `json:"base_revision"` + // Seed is honored only when the server has never stored a workspace. It + // makes migration from the old device-local snapshot race-safe; otherwise + // the reply is the existing snapshot, unchanged. Seed bool `json:"seed,omitempty"` } +// ChatOpenWorkspaceSnapshot is the complete open-chat set. Revision grows by +// one with every stored change. type ChatOpenWorkspaceSnapshot struct { Revision int64 `json:"revision"` Entries []ChatOpenWorkspaceEntry `json:"entries"` + // Rejected marks a reply to a write whose base revision was stale: the + // write was not applied and the snapshot is the current state. + Rejected bool `json:"rejected,omitempty"` } diff --git a/internal/server/chat.go b/internal/server/chat.go index 82d3536e..6ae310b0 100644 --- a/internal/server/chat.go +++ b/internal/server/chat.go @@ -214,11 +214,7 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker handleChatDirectories(ctx, request, registry, write) return true case protocol.ChatClose: - var store chatOpenWorkspaceStore - if candidate, ok := registry.(chatOpenWorkspaceStore); ok { - store = candidate - } - handleChatClose(ctx, request, broker, hub, registry, store, write) + handleChatClose(ctx, request, broker, hub, registry, write) return true case protocol.ChatReopen: handleChatReopen(ctx, request, registry, write) @@ -230,11 +226,7 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker handleChatColor(ctx, request, registry, hub.changes(), clientID, write) return true case protocol.ChatOpenWorkspace: - var store chatOpenWorkspaceStore - if candidate, ok := registry.(chatOpenWorkspaceStore); ok { - store = candidate - } - handleChatOpenWorkspace(ctx, request, broker, registry, store, hub.changes(), clientID, write) + handleChatOpenWorkspace(ctx, request, registry, hub.changes(), clientID, write) return true case protocol.ChatRename: handleChatRename(ctx, request, broker, registry, hub.changes(), clientID, write) diff --git a/internal/server/chat_close.go b/internal/server/chat_close.go index a5cab98d..d5eb98c6 100644 --- a/internal/server/chat_close.go +++ b/internal/server/chat_close.go @@ -17,7 +17,7 @@ import ( // registry, not on one device. A session id that is not a recorded operator // session is refused before anything is written, so a pipeline-owned run session // is never touched. -func handleChatClose(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, registry operatorRegistry, store chatOpenWorkspaceStore, write func(protocol.Message) error) { +func handleChatClose(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, registry operatorRegistry, write func(protocol.Message) error) { if broker == nil { _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"}) return @@ -92,22 +92,9 @@ func handleChatClose(ctx context.Context, request protocol.Message, broker chatB // chat_sessions without a re-list. response.ChatSessions = []protocol.ChatSession{wire} _ = write(response) - if store != nil { - workspace, workspaceErr := store.ChatOpenWorkspace(ctx, chatWorkspaceScope) - if workspaceErr == nil { - kept := workspace.Entries[:0] - for _, entry := range workspace.Entries { - if entry.SessionID != sessionID { - kept = append(kept, entry) - } - } - if len(kept) != len(workspace.Entries) { - if updated, saveErr := store.SaveChatOpenWorkspace(ctx, chatWorkspaceScope, kept, false); saveErr == nil && hub != nil { - hub.changes().broadcastWorkspace("", updated) - } - } - } - } + // A closed chat leaves every device's open-chat set, so no client can keep + // or restore it. + dropFromChatWorkspace(ctx, registry, hub.changes(), sessionID) } // handleChatReopen clears the closed state of an operator chat session so it diff --git a/internal/server/chat_open_workspace.go b/internal/server/chat_open_workspace.go index d9752197..dc707809 100644 --- a/internal/server/chat_open_workspace.go +++ b/internal/server/chat_open_workspace.go @@ -3,116 +3,162 @@ package server import ( "context" "fmt" + "log" "strings" + "git.a-wan.net/alan/pipelines/internal/pipeline" "git.a-wan.net/alan/pipelines/internal/protocol" ) +// chatWorkspaceScope keys the one operator's open-chat set: the authenticated +// local server has a single operator. const chatWorkspaceScope = "default" +// chatOpenWorkspaceStore persists the server-authoritative open-chat set (see +// pipeline.Store.SaveChatOpenWorkspace for the revision rules). type chatOpenWorkspaceStore interface { ChatOpenWorkspace(context.Context, string) (protocol.ChatOpenWorkspaceSnapshot, error) - SaveChatOpenWorkspace(context.Context, string, []protocol.ChatOpenWorkspaceEntry, bool) (protocol.ChatOpenWorkspaceSnapshot, error) + SaveChatOpenWorkspace(ctx context.Context, scope string, entries []protocol.ChatOpenWorkspaceEntry, seed bool, baseRevision int64) (protocol.ChatOpenWorkspaceSnapshot, bool, error) + RemoveChatOpenWorkspaceSessions(ctx context.Context, scope string, sessionIDs []string) (protocol.ChatOpenWorkspaceSnapshot, bool, error) } -func reconcileChatWorkspace(ctx context.Context, snapshot protocol.ChatOpenWorkspaceSnapshot, broker chatBroker, registry operatorRegistry, store chatOpenWorkspaceStore) (protocol.ChatOpenWorkspaceSnapshot, error) { - if broker == nil || registry == nil || store == nil { - return snapshot, nil +func openWorkspaceStoreOf(registry operatorRegistry) chatOpenWorkspaceStore { + store, _ := registry.(chatOpenWorkspaceStore) + return store +} + +// openOperatorChat reports whether id is a recorded operator chat that is not +// closed. Only those may be in the open-chat set, so a pipeline-owned run +// session, a closed chat or an unknown id is never kept. The registry is the +// authority; the broker is not asked, so validation never starts a harness. +func openOperatorChat(ctx context.Context, registry operatorRegistry, id string) (bool, error) { + row, found, err := registry.OperatorSession(ctx, id) + if err != nil { + return false, err } - valid := make([]protocol.ChatOpenWorkspaceEntry, 0, len(snapshot.Entries)) + return found && row.ClosedAt == 0, nil +} + +// pruneChatWorkspace drops every stored entry that is no longer an open +// operator chat. changed reports a new stored revision, which the caller +// broadcasts to every connection. +func pruneChatWorkspace(ctx context.Context, registry operatorRegistry, store chatOpenWorkspaceStore) (protocol.ChatOpenWorkspaceSnapshot, bool, error) { + snapshot, err := store.ChatOpenWorkspace(ctx, chatWorkspaceScope) + if err != nil || snapshot.Revision == 0 { + return snapshot, false, err + } + var stale []string for _, entry := range snapshot.Entries { - row, found, err := registry.OperatorSession(ctx, entry.SessionID) + open, err := openOperatorChat(ctx, registry, entry.SessionID) if err != nil { - return snapshot, err + return snapshot, false, err } - if !found || row.ClosedAt != 0 { - continue - } - if _, live, err := broker.Session(ctx, entry.SessionID); err != nil { - return snapshot, err - } else if live { - valid = append(valid, entry) + if !open { + stale = append(stale, entry.SessionID) } } - if len(valid) == len(snapshot.Entries) { - return snapshot, nil + if len(stale) == 0 { + return snapshot, false, nil } - return store.SaveChatOpenWorkspace(ctx, chatWorkspaceScope, valid, false) + return store.RemoveChatOpenWorkspaceSessions(ctx, chatWorkspaceScope, stale) } -func validateChatWorkspace(ctx context.Context, request protocol.Message, broker chatBroker, registry operatorRegistry) ([]protocol.ChatOpenWorkspaceEntry, error) { - if request.ChatOpenWorkspaceRequest == nil { - return nil, fmt.Errorf("chat_open_workspace_request is required") +// announceChatWorkspace runs when a connection opens: it prunes stale entries +// and, when that stored a new revision, pushes it to every connection; +// otherwise it sends the current snapshot to the new connection alone, so a +// reconnecting client catches up with changes it missed. +func announceChatWorkspace(ctx context.Context, registry operatorRegistry, changes *chatSessionChanges, write func(protocol.Message) error) { + store := openWorkspaceStoreOf(registry) + if store == nil { + return } - entries := request.ChatOpenWorkspaceRequest.Entries - if len(entries) > 64 { + snapshot, changed, err := pruneChatWorkspace(ctx, registry, store) + if err != nil { + log.Printf("reconcile open chat workspace: %v", err) + return + } + if changed { + changes.broadcastWorkspace("", snapshot) + } else if snapshot.Revision > 0 { + _ = write(protocol.Message{Type: protocol.ChatOpenWorkspaceChanged, ChatOpenWorkspace: &snapshot}) + } +} + +// dropFromChatWorkspace removes a closed chat from the open-chat set and pushes +// the new revision to every connection, the closing one included. +func dropFromChatWorkspace(ctx context.Context, registry operatorRegistry, changes *chatSessionChanges, sessionID string) { + store := openWorkspaceStoreOf(registry) + if store == nil { + return + } + snapshot, changed, err := store.RemoveChatOpenWorkspaceSessions(ctx, chatWorkspaceScope, []string{sessionID}) + if err != nil { + log.Printf("drop closed chat %s from open workspace: %v", sessionID, err) + return + } + if changed { + changes.broadcastWorkspace("", snapshot) + } +} + +// validChatWorkspaceEntries checks a client's snapshot and keeps only its open +// operator chats. Malformed or duplicate ids are refused; closed or unknown +// chats are dropped, so a stale client can never restore them. +func validChatWorkspaceEntries(ctx context.Context, request protocol.ChatOpenWorkspaceRequest, registry operatorRegistry) ([]protocol.ChatOpenWorkspaceEntry, error) { + if len(request.Entries) > pipeline.ChatOpenWorkspaceLimit { return nil, fmt.Errorf("too many open chats") } seen := map[string]bool{} - for i := range entries { - id := strings.TrimSpace(entries[i].SessionID) + valid := make([]protocol.ChatOpenWorkspaceEntry, 0, len(request.Entries)) + for _, entry := range request.Entries { + id := strings.TrimSpace(entry.SessionID) if !validChatSessionID(id) || seen[id] { return nil, fmt.Errorf("invalid or duplicate open chat session %q", id) } - entries[i].SessionID = id seen[id] = true - if registry == nil || broker == nil { - return nil, fmt.Errorf("chat workspace validation unavailable") - } - row, found, err := registry.OperatorSession(ctx, id) + open, err := openOperatorChat(ctx, registry, id) if err != nil { return nil, err } - if !found || row.ClosedAt != 0 { - continue - } - if _, live, err := broker.Session(ctx, id); err != nil { - return nil, err - } else if !live { - continue + if open { + valid = append(valid, protocol.ChatOpenWorkspaceEntry{SessionID: id, Floating: entry.Floating}) } } - return entries, nil + return valid, nil } -func handleChatOpenWorkspace(ctx context.Context, request protocol.Message, broker chatBroker, registry operatorRegistry, store chatOpenWorkspaceStore, changes *chatSessionChanges, clientID string, write func(protocol.Message) error) { - if store == nil { - _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat workspace persistence unavailable"}) +// handleChatOpenWorkspace reads (no request) or replaces the open-chat set. +// The reply always carries the resulting snapshot; a stored change is pushed +// to every other connection as chat_open_workspace_changed. +func handleChatOpenWorkspace(ctx context.Context, request protocol.Message, registry operatorRegistry, changes *chatSessionChanges, clientID string, write func(protocol.Message) error) { + fail := func(err error) { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) + } + store := openWorkspaceStoreOf(registry) + if registry == nil || store == nil { + fail(fmt.Errorf("chat workspace persistence unavailable")) return } - entries, err := validateChatWorkspace(ctx, request, broker, registry) - if err != nil { - _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) - return - } - // Invalid, closed, deleted, and replaced sessions are dropped rather than - // returned as errors: clients can never restore them from a stale snapshot. - valid := entries[:0] - for _, entry := range entries { - row, found, rowErr := registry.OperatorSession(ctx, entry.SessionID) - if rowErr != nil { - _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: rowErr.Error()}) - return - } - if !found || row.ClosedAt != 0 { - continue - } - _, live, sessionErr := broker.Session(ctx, entry.SessionID) - if sessionErr != nil { - _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: sessionErr.Error()}) - return - } - if live { - valid = append(valid, entry) + var ( + snapshot protocol.ChatOpenWorkspaceSnapshot + changed bool + err error + ) + if request.ChatOpenWorkspaceRequest == nil { + snapshot, changed, err = pruneChatWorkspace(ctx, registry, store) + } else { + var entries []protocol.ChatOpenWorkspaceEntry + entries, err = validChatWorkspaceEntries(ctx, *request.ChatOpenWorkspaceRequest, registry) + if err == nil { + snapshot, changed, err = store.SaveChatOpenWorkspace(ctx, chatWorkspaceScope, entries, request.ChatOpenWorkspaceRequest.Seed, request.ChatOpenWorkspaceRequest.BaseRevision) } } - snapshot, err := store.SaveChatOpenWorkspace(ctx, chatWorkspaceScope, valid, request.ChatOpenWorkspaceRequest.Seed) if err != nil { - _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) + fail(err) return } _ = write(protocol.Message{Type: protocol.ChatOpenWorkspace, ID: request.ID, ChatOpenWorkspace: &snapshot}) - if changes != nil { + if changed { changes.broadcastWorkspace(clientID, snapshot) } } diff --git a/internal/server/chat_open_workspace_test.go b/internal/server/chat_open_workspace_test.go new file mode 100644 index 00000000..96818c11 --- /dev/null +++ b/internal/server/chat_open_workspace_test.go @@ -0,0 +1,147 @@ +package server + +import ( + "context" + "testing" + + "github.com/coder/websocket" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +func workspaceWrite(id string, base int64, entries ...protocol.ChatOpenWorkspaceEntry) protocol.Message { + return protocol.Message{Type: protocol.ChatOpenWorkspace, ID: id, ChatOpenWorkspaceRequest: &protocol.ChatOpenWorkspaceRequest{Entries: entries, BaseRevision: base}} +} + +func workspaceIDs(snapshot *protocol.ChatOpenWorkspaceSnapshot) []string { + ids := []string{} + for _, entry := range snapshot.Entries { + id := entry.SessionID + if entry.Floating { + id += "*" + } + ids = append(ids, id) + } + return ids +} + +func sameIDs(a []string, b ...string) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + +// readWorkspacePush reads chat_open_workspace_changed pushes until one carries +// revision; lower revisions (pushed out of order) are skipped. +func readWorkspacePush(t *testing.T, ctx context.Context, conn *websocket.Conn, revision int64) *protocol.ChatOpenWorkspaceSnapshot { + t.Helper() + for { + message := readUntil(t, ctx, conn, protocol.ChatOpenWorkspaceChanged) + got := message.ChatOpenWorkspace + if got == nil { + t.Fatal("push without a snapshot") + } + if got.Revision == revision { + return got + } + if got.Revision > revision { + t.Fatalf("push revision %d, want %d", got.Revision, revision) + } + } +} + +// TestChatOpenWorkspaceSyncsEveryConnection is the fan-out evidence: a write +// from one connection is stored at the next revision and pushed to the other; +// a write from a stale base is refused with the current snapshot; closing a +// chat drops it and pushes the result to both connections; and a later write +// cannot put the closed chat back. +func TestChatOpenWorkspaceSyncsEveryConnection(t *testing.T) { + store := newOperatorStore(t) + ctx, _, conns := dialChatConns(t, Options{Chat: scriptedChat(), OperatorRegistry: store}, 2) + for _, id := range []string{"ses_a", "ses_b"} { + if err := store.RecordOperatorSession(ctx, id, "/work", id, protocol.ChatSessionTagOperator); err != nil { + t.Fatal(err) + } + } + a, b := protocol.ChatOpenWorkspaceEntry{SessionID: "ses_a"}, protocol.ChatOpenWorkspaceEntry{SessionID: "ses_b", Floating: true} + + writeChat(t, ctx, conns[0], workspaceWrite("w1", 0, a, b, protocol.ChatOpenWorkspaceEntry{SessionID: "ses_unknown"})) + reply := readUntil(t, ctx, conns[0], protocol.ChatOpenWorkspace).ChatOpenWorkspace + if reply.Revision != 1 || reply.Rejected || !sameIDs(workspaceIDs(reply), "ses_a", "ses_b*") { + t.Fatalf("first write reply = %+v", reply) + } + if push := readWorkspacePush(t, ctx, conns[1], 1); !sameIDs(workspaceIDs(push), "ses_a", "ses_b*") { + t.Fatalf("second connection got %v", workspaceIDs(push)) + } + writeChat(t, ctx, conns[1], protocol.Message{Type: protocol.ChatOpenWorkspace, ID: "r1"}) + if read := readUntil(t, ctx, conns[1], protocol.ChatOpenWorkspace).ChatOpenWorkspace; read.Revision != 1 || !sameIDs(workspaceIDs(read), "ses_a", "ses_b*") { + t.Fatalf("read = %+v", read) + } + + // A write derived from revision 0 lands after revision 1: refused. + writeChat(t, ctx, conns[1], workspaceWrite("w2", 0, b)) + stale := readUntil(t, ctx, conns[1], protocol.ChatOpenWorkspace).ChatOpenWorkspace + if !stale.Rejected || stale.Revision != 1 || !sameIDs(workspaceIDs(stale), "ses_a", "ses_b*") { + t.Fatalf("stale write reply = %+v", stale) + } + + // Reorder from the second connection reaches the first. + b.Floating = false + writeChat(t, ctx, conns[1], workspaceWrite("w3", 1, b, a)) + if got := readUntil(t, ctx, conns[1], protocol.ChatOpenWorkspace).ChatOpenWorkspace; got.Revision != 2 { + t.Fatalf("reorder reply = %+v", got) + } + if push := readWorkspacePush(t, ctx, conns[0], 2); !sameIDs(workspaceIDs(push), "ses_b", "ses_a") { + t.Fatalf("reorder push = %v", workspaceIDs(push)) + } + + // Closing ses_a drops it and pushes revision 3 to both connections. + writeChat(t, ctx, conns[0], protocol.Message{Type: protocol.ChatClose, ID: "c1", ChatQuery: &protocol.ChatQuery{SessionID: "ses_a"}}) + readUntil(t, ctx, conns[0], protocol.ChatClose) + for i, conn := range conns { + if push := readWorkspacePush(t, ctx, conn, 3); !sameIDs(workspaceIDs(push), "ses_b") { + t.Fatalf("connection %d close push = %v", i, workspaceIDs(push)) + } + } + + // A client still showing the closed chat cannot restore it. + writeChat(t, ctx, conns[1], workspaceWrite("w4", 3, a, b)) + if got := readUntil(t, ctx, conns[1], protocol.ChatOpenWorkspace).ChatOpenWorkspace; got.Revision != 3 || !sameIDs(workspaceIDs(got), "ses_b") { + t.Fatalf("closed chat restored: %+v", got) + } +} + +// TestChatOpenWorkspacePrunesOnConnectForEveryone pins that a chat closed +// behind the workspace's back is pruned when a connection opens, and that the +// pruned snapshot reaches the connections already open, not only the new one. +func TestChatOpenWorkspacePrunesOnConnectForEveryone(t *testing.T) { + store := newOperatorStore(t) + ctx, _, srv, conns := dialChatServer(t, Options{Chat: scriptedChat(), OperatorRegistry: store}, 1) + for _, id := range []string{"ses_a", "ses_b"} { + if err := store.RecordOperatorSession(ctx, id, "/work", id, protocol.ChatSessionTagOperator); err != nil { + t.Fatal(err) + } + } + writeChat(t, ctx, conns[0], workspaceWrite("w1", 0, protocol.ChatOpenWorkspaceEntry{SessionID: "ses_a"}, protocol.ChatOpenWorkspaceEntry{SessionID: "ses_b"})) + readUntil(t, ctx, conns[0], protocol.ChatOpenWorkspace) + if err := store.CloseOperatorSession(ctx, "ses_a"); err != nil { + t.Fatal(err) + } + late := dialChatConn(t, ctx, srv) + for i, conn := range []*websocket.Conn{conns[0], late} { + if push := readWorkspacePush(t, ctx, conn, 2); !sameIDs(workspaceIDs(push), "ses_b") { + t.Fatalf("connection %d prune push = %v", i, workspaceIDs(push)) + } + } + // With nothing to prune, a new connection alone is brought up to date. + third := dialChatConn(t, ctx, srv) + if push := readWorkspacePush(t, ctx, third, 2); !sameIDs(workspaceIDs(push), "ses_b") { + t.Fatalf("catch-up push = %v", workspaceIDs(push)) + } +} diff --git a/internal/server/chat_session_changes.go b/internal/server/chat_session_changes.go index 609a6e19..0b2cba75 100644 --- a/internal/server/chat_session_changes.go +++ b/internal/server/chat_session_changes.go @@ -62,7 +62,13 @@ func (c *chatSessionChanges) broadcast(sender string, session protocol.ChatSessi } } +// broadcastWorkspace pushes an open-chat snapshot to every connection except +// sender ("" reaches all of them). Writes run on their own goroutines, so they +// may arrive out of order; clients keep only the highest revision. func (c *chatSessionChanges) broadcastWorkspace(sender string, snapshot protocol.ChatOpenWorkspaceSnapshot) { + if c == nil { + return + } c.mu.Lock() targets := make([]func(protocol.Message) error, 0, len(c.clients)) for id, write := range c.clients { diff --git a/internal/server/websocket.go b/internal/server/websocket.go index 71ed4ba0..2fa57fe8 100644 --- a/internal/server/websocket.go +++ b/internal/server/websocket.go @@ -261,17 +261,9 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin // connection the same way. hub.sessionChanges.attach(clientID, write) defer hub.sessionChanges.detach(clientID) - if workspaceStore, ok := registry.(chatOpenWorkspaceStore); ok { - if snapshot, err := workspaceStore.ChatOpenWorkspace(connCtx, chatWorkspaceScope); err == nil && snapshot.Revision > 0 { - snapshot, err = reconcileChatWorkspace(connCtx, snapshot, options.Chat, registry, workspaceStore) - if err != nil { - log.Printf("reconcile open chat workspace: %v", err) - } - if err == nil { - _ = write(protocol.Message{Type: protocol.ChatOpenWorkspaceChanged, ChatOpenWorkspace: &snapshot}) - } - } - } + // The open-chat set: prune entries that are no longer open chats and + // push the result to every connection, else bring this one up to date. + announceChatWorkspace(connCtx, registry, hub.changes(), write) // Terminal lifecycle changes reach every connection; output only the // connections that opened or read that terminal. terminals.clients.attach(clientID, write)