Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

feat: bots react to messages with emoji

leepokaibd3e30c404ec
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.kt b/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.kt
index 8ee93c2f..85383cb0 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.kt
@@ -37,6 +37,7 @@ import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextAlign
@@ -118,7 +119,7 @@ internal fun chatItems(entries: List<Entry>, pending: List<PendingSend>): List<C
"user" -> Column(Modifier.fillMaxWidth().padding(top = if (groupStart) 12.dp else 4.dp).animateContentSize(Motion.layoutSize),
horizontalAlignment = Alignment.End, verticalArrangement = Arrangement.spacedBy(4.dp)) {
UserBubble(entry, state, store, reply)
- ReactionsRow(entry, store)
+ ReactionsRow(entry, state, store)
ThreadChip(entry, state, reply)
}
"agent" -> Column(Modifier.fillMaxWidth().padding(top = if (groupStart) 12.dp else 4.dp).animateContentSize(Motion.layoutSize),
@@ -126,7 +127,7 @@ internal fun chatItems(entries: List<Entry>, pending: List<PendingSend>): List<C
if (group && groupStart) AuthorLabel(entry.data.text("author"), state)
AgentBubble(entry, state, store, openTrace, reply)
Column(Modifier.padding(start = if (group) 34.dp else 0.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
- ReactionsRow(entry, store)
+ ReactionsRow(entry, state, store)
ThreadChip(entry, state, reply)
}
}
@@ -275,21 +276,40 @@ internal val Entry.reactions: List<String> get() = (data["reactions"] as? JsonAr
}
}
-/** The user's reactions under a message; tapping one takes it back. */
-@Composable private fun ReactionsRow(entry: Entry, store: AppStore) {
- val reactions = entry.reactions
- if (reactions.isEmpty()) return
+/** A message's reactions: the user's (tapping one takes it back), then the bots', each emoji with the avatars of the
+ * bots that chose it. */
+@Composable private fun ReactionsRow(entry: Entry, state: AppState, store: AppStore) {
+ val mine = entry.reactions
+ val theirs = entry.botReactions.mapValues { (_, ids) -> ids.mapNotNull { id -> state.bots.firstOrNull { it.id == id } } }
+ .filterValues { it.isNotEmpty() }
+ if (mine.isEmpty() && theirs.isEmpty()) return
Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
- for (emoji in reactions) {
+ for (emoji in mine) {
val (source, pressed) = rememberPress()
Text(emoji, Modifier.pressScale(pressed).clip(Capsule()).background(Palette.surface)
.clickable(source, null, role = Role.Button) { store.command("react", body("entryId" to entry.id, "emoji" to emoji), "react:" + entry.id) }
.semantics { contentDescription = "Remove reaction $emoji" }
.padding(horizontal = 8.dp, vertical = 3.dp), style = Type.system(15f))
}
+ for ((emoji, bots) in theirs) {
+ Row(Modifier.clip(Capsule()).background(Palette.surface)
+ .clearAndSetSemantics { contentDescription = "${bots.joinToString { it.name }} reacted $emoji" }
+ .padding(horizontal = 8.dp, vertical = 3.dp), verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(4.dp)) {
+ Text(emoji, style = Type.system(15f))
+ Row(horizontalArrangement = Arrangement.spacedBy((-5).dp)) {
+ for (bot in bots.take(3)) CharacterAvatar(bot.avatarShape, bot.avatarColor, 16.dp)
+ }
+ }
+ }
}
}
+/** The bots' reactions by emoji, in the order each first appeared: each emoji with the bots that chose it. */
+internal val Entry.botReactions: Map<String, List<String>> get() =
+ (data["botReactions"] as? JsonArray).orEmpty().mapNotNull { it as? JsonObject }
+ .groupBy({ it["emoji"]?.jsonPrimitive?.contentOrNull.orEmpty() }, { it["bot"]?.jsonPrimitive?.contentOrNull.orEmpty() })
+
/** A routine's run in the main chat: tapping it opens Routines on that routine. */
@Composable internal fun RoutineNotice(entry: Entry, open: () -> Unit) {
Row(Modifier.plainButton(action = open).padding(vertical = 10.dp), verticalAlignment = Alignment.CenterVertically,
diff --git a/apps/desktop/src/renderer/views/thread/ChatRows.tsx b/apps/desktop/src/renderer/views/thread/ChatRows.tsx
index ae717a34..08545975 100644
--- a/apps/desktop/src/renderer/views/thread/ChatRows.tsx
+++ b/apps/desktop/src/renderer/views/thread/ChatRows.tsx
@@ -1,6 +1,6 @@
import { FileDownloadCard } from './FileDownloadCard'
import { memo, useEffect, useRef, useState } from 'react'
-import { isGroup, isWorking, needsInput, type Bot, type Entry, type ThreadSummary } from '@shared/models'
+import { groupBotReactions, isGroup, isWorking, needsInput, type Bot, type Entry, type ThreadSummary } from '@shared/models'
import { BotAvatar } from '../../components/Avatar'
import { Hairline, IconButton } from '../../components/Controls'
import { Icon } from '../../components/Icon'
@@ -290,18 +290,37 @@ function Timer({ since }: { since: number }) {
return <Text size="footnote" tone="tertiary" tabular>{h ? `${h}:${String(m).padStart(2, '0')}:${sec}` : `${m}:${sec}`}</Text>
}
-/** The user's reactions under a message; clicking one takes it back. */
+/** A message's reactions: the user's (clicking one takes it back), then the bots', each emoji with the avatars of the
+ * bots that chose it. */
export function ReactionsRow({ entry }: { entry: Entry }) {
const store = useStore()
- const reactions = entry.data.reactions
- if (!reactions?.length) return null
+ const mine = entry.data.reactions ?? []
+ const theirs = groupBotReactions(entry.data.botReactions ?? [])
+ .map(({ emoji, bots }) => ({ emoji, bots: bots.map((id) => store.bots.get(id)).filter((b): b is Bot => !!b) }))
+ .filter((g) => g.bots.length)
+ if (!mine.length && !theirs.length) return null
return (
<HStack align="stretch" gap={4}>
- {reactions.map((emoji) => (
+ {mine.map((emoji) => (
<button key={emoji} className="press reaction-chip" title={`Remove ${emoji}`} aria-label={`Remove reaction ${emoji}`} onClick={() => store.react(entry, emoji)}>
<Text size="body">{emoji}</Text>
</button>
))}
+ {theirs.map(({ emoji, bots }) => {
+ const label = `${bots.map((b) => b.name).join(', ')} reacted ${emoji}`
+ return (
+ <HStack key={`bots-${emoji}`} gap={4} className="reaction-chip" title={label} aria-label={label} role="img">
+ <Text size="body">{emoji}</Text>
+ <HStack as="span" className="reaction-chip-bots">
+ {bots.slice(0, 3).map((b) => (
+ <span key={b.id}>
+ <BotAvatar bot={b} size={16} animated={false} />
+ </span>
+ ))}
+ </HStack>
+ </HStack>
+ )
+ })}
</HStack>
)
}
diff --git a/apps/desktop/src/renderer/views/thread/thread.css b/apps/desktop/src/renderer/views/thread/thread.css
index aaeb9b2e..acf87d53 100644
--- a/apps/desktop/src/renderer/views/thread/thread.css
+++ b/apps/desktop/src/renderer/views/thread/thread.css
@@ -315,6 +315,9 @@
border-radius: var(--radius-pill);
background: var(--surface);
}
+.reaction-chip-bots > * + * {
+ margin-left: -5px;
+}
.thread-chip {
display: flex;
align-items: center;
diff --git a/apps/desktop/src/shared/models.ts b/apps/desktop/src/shared/models.ts
index 567e19e5..aec97e00 100644
--- a/apps/desktop/src/shared/models.ts
+++ b/apps/desktop/src/shared/models.ts
@@ -132,6 +132,23 @@ export interface PlanItem {
priority?: string
}
+/** One bot's emoji on a message. */
+export interface BotReaction {
+ bot: string
+ emoji: string
+}
+
+/** The bots' reactions on one message, by emoji in the order each first appeared. */
+export function groupBotReactions(reactions: BotReaction[]): { emoji: string; bots: string[] }[] {
+ const groups: { emoji: string; bots: string[] }[] = []
+ for (const r of reactions) {
+ const group = groups.find((g) => g.emoji === r.emoji)
+ if (group) group.bots.push(r.bot)
+ else groups.push({ emoji: r.emoji, bots: [r.bot] })
+ }
+ return groups
+}
+
export interface ThreadSummary {
count: number
lastAt: number
@@ -217,6 +234,8 @@ export interface EntryData {
author?: string
thread?: ThreadSummary
reactions?: string[]
+ /** The bots' reactions, one per bot, oldest first. */
+ botReactions?: BotReaction[]
attachments?: Attachment[]
files?: SharedFile[]
callSeconds?: number
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift b/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift
index c7571be4..bae73ee8 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift
@@ -41,6 +41,8 @@ public struct EntryData: Codable, Hashable, Sendable {
public var thread: ThreadSummary?
/// The user's emoji reactions, oldest first.
public var reactions: [String]?
+ /// The bots' reactions, one per bot, oldest first.
+ public var botReactions: [BotReaction]?
/// Files sent with a user message.
public var attachments: [Attachment]?
/// Immutable files explicitly sent by the bot.
@@ -58,6 +60,25 @@ public struct EntryData: Codable, Hashable, Sendable {
/// A memory line from an older host, known only to keep it out of the chat.
public struct MemoryLine: Codable, Hashable, Sendable {}
+/// One bot's emoji on a message.
+public struct BotReaction: Codable, Hashable, Sendable {
+ public var bot: String
+ public var emoji: String
+}
+
+extension EntryData {
+ /// The bots' reactions by emoji, in the order each first appeared.
+ public var botReactionGroups: [(emoji: String, bots: [String])] {
+ (botReactions ?? []).reduce(into: []) { groups, r in
+ if let i = groups.firstIndex(where: { $0.emoji == r.emoji }) {
+ groups[i].bots.append(r.bot)
+ } else {
+ groups.append((r.emoji, [r.bot]))
+ }
+ }
+ }
+}
+
/// A file sent with a message; the agent reads it on the computer.
public struct Attachment: Codable, Hashable, Sendable, Identifiable {
public var id: String
diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swift
index 8ed19ef8..4116594c 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swift
@@ -25,6 +25,7 @@ struct ChatRow: View {
threadChip
}
.animation(Motion.reduced(Motion.layout, reduceMotion), value: entry.data.reactions)
+ .animation(Motion.reduced(Motion.layout, reduceMotion), value: entry.data.botReactions)
.padding(.top, groupStart ? 12 : 4)
case "agent":
VStack(alignment: .leading, spacing: 4) {
@@ -37,6 +38,7 @@ struct ChatRow: View {
.padding(.leading, chat?.isGroup == true ? 34 : 0)
}
.animation(Motion.reduced(Motion.layout, reduceMotion), value: entry.data.reactions)
+ .animation(Motion.reduced(Motion.layout, reduceMotion), value: entry.data.botReactions)
.padding(.top, groupStart ? 12 : 4)
case "permission":
VStack(alignment: .leading, spacing: 4) {
@@ -368,15 +370,20 @@ extension BotStore {
}
}
-/// The user's reactions under a message; tapping one takes it back.
+/// A message's reactions: the user's (tapping one takes it back), then the bots', each emoji with
+/// the avatars of the bots that chose it.
struct ReactionsRow: View {
let entry: Entry
@Environment(BotStore.self) private var model
var body: some View {
- if let reactions = entry.data.reactions, !reactions.isEmpty {
+ let mine = entry.data.reactions ?? []
+ let theirs = entry.data.botReactionGroups
+ .map { (emoji: $0.emoji, bots: $0.bots.compactMap { model.bots[$0] }) }
+ .filter { !$0.bots.isEmpty }
+ if !mine.isEmpty || !theirs.isEmpty {
HStack(spacing: 4) {
- ForEach(reactions, id: \.self) { emoji in
+ ForEach(mine, id: \.self) { emoji in
Button { model.react(entry, emoji) } label: {
Text(emoji)
.font(.system(size: 15))
@@ -390,6 +397,20 @@ struct ReactionsRow: View {
.accessibilityLabel("Remove reaction \(emoji)")
.transition(.scale.combined(with: .opacity))
}
+ ForEach(theirs, id: \.emoji) { group in
+ HStack(spacing: 4) {
+ Text(group.emoji).font(.system(size: 15))
+ HStack(spacing: -5) {
+ ForEach(group.bots.prefix(3)) { bot in CharacterAvatar(bot: bot, size: 16, animated: false) }
+ }
+ }
+ .padding(.horizontal, 8)
+ .padding(.vertical, 3)
+ .background(Palette.surface, in: Capsule())
+ .accessibilityElement(children: .ignore)
+ .accessibilityLabel("\(group.bots.map(\.name).joined(separator: ", ")) reacted \(group.emoji)")
+ .transition(.scale.combined(with: .opacity))
+ }
}
}
}
diff --git a/apps/ios/WhatsNew.md b/apps/ios/WhatsNew.md
index 49d1a5af..444b604c 100644
--- a/apps/ios/WhatsNew.md
+++ b/apps/ios/WhatsNew.md
@@ -9,8 +9,10 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o
### zh-Hant
+- Bot 會用表情符號回應你的訊息:道謝時回一顆 ❤️,好消息回 🎉。群組裡的 Bot 之間也會互相按表情。
- 當機報告更完整,讓我們更快找到並修正 App 閃退的問題。
### en-US
+- Bots react to your messages with emoji: a ❤️ when you say thanks, a 🎉 for good news. In groups, bots react to each other too.
- More complete crash reports, so we can find and fix crashes faster.
diff --git a/docs/architecture/conversation-runtime.md b/docs/architecture/conversation-runtime.md
index d040ed1d..c8990d4a 100644
--- a/docs/architecture/conversation-runtime.md
+++ b/docs/architecture/conversation-runtime.md
@@ -6,4 +6,4 @@
- **A session that fails** with an internal error its agent gives no category (JSON-RPC `-32603` without `data.errorKind`) is closed right after the turn, when the agent can close and load sessions: Claude's adapter otherwise answers every later prompt on it with "The Claude Agent session has ended". The next message loads it again and the conversation carries on (`acp::may_end_session`).
- Bot collaboration: built-in `team` MCP (`chat/team.rs`) lists visible bots and asks one for a reply or sends it an independent message through its actor queue. Asks are separate turns, cycle-checked and cancellable; native subagents stay with the harness. See [docs/features/bot-collaboration.md](../features/bot-collaboration.md).
- **Context & memory**: frozen instruction snapshot per session + compaction epoch (Claude gets it as a system prompt), profile edits as update blocks, memory in the host (a layer shared by all bots and one per bot, written by the user, the bots' tools and dreaming), busy-time messages folded into one turn, interrupted turns resumed: [docs/features/context-and-memory.md](../features/context-and-memory.md).
-- **Chat shows only**: user messages, the bot's messages (`data.final`: each `send_message` call from the built-in `chat` MCP, Grok Bot's way; a turn that sent none falls back to its last text), permission cards, notices. Nothing streams into a bubble; narration, thoughts, tool calls, plans are trace entries (Full conversation sheet): [docs/features/chat-messages.md](../features/chat-messages.md).
+- **Chat shows only**: user messages, the bot's messages (`data.final`: each `send_message` call from the built-in `chat` MCP, Grok Bot's way; a turn that sent none falls back to its last text, unless it reacted to the user's message instead), permission cards, notices. Nothing streams into a bubble; narration, thoughts, tool calls, plans are trace entries (Full conversation sheet): [docs/features/chat-messages.md](../features/chat-messages.md).
diff --git a/docs/features/chat-messages.md b/docs/features/chat-messages.md
index 3518a046..5a96c71c 100644
--- a/docs/features/chat-messages.md
+++ b/docs/features/chat-messages.md
@@ -41,6 +41,22 @@ it has no pointer tooltip or link-opening action.
- Clients never stream text into a bubble: the chat shows user messages, `final` agent entries,
permission cards and notices (`isChat`). Nothing pops in and out while a turn runs.
+## Bot reactions
+
+- The `chat` server's `react {emoji, to?}` (`host/src/chat/reactions.rs`) goes through the bot's actor,
+ which puts one emoji on the message the turn answers: in its own chat or thread, the user's message that
+ started the turn; in a group, the newest message its prompt showed from `to` ("user" or a participant's
+ name), or from anyone else. Routines and bot requests can't react. Each bot keeps one reaction per
+ message; a new emoji replaces it.
+- Stored as `data.botReactions: [{bot, emoji}]` beside the user's own `data.reactions`. The first one also
+ records `data.contentRev`, the rev before it, which the unread count uses, so a read message stays read.
+- The instructions ask for reactions where a person would react (thanks, good news, a joke, a plain OK), and
+ not on most messages. A reaction can be the whole reply: a turn that reacted and sent no message
+ doesn't fall back to its last text, and its push says "Reacted ❤️ to your message".
+- Clients show each bot emoji as a chip with the avatars of the bots that chose it (up to three), after the
+ user's own chips; it isn't tappable, and a bot that was deleted drops out. The terminal UI lists
+ `❤️ Ann, Ben` after the user's reactions.
+
## While it works
The working line under the last message shows the bot's activity; composing a `send_message`
diff --git a/docs/features/groups-and-threads.md b/docs/features/groups-and-threads.md
index 9fed9df5..541965b7 100644
--- a/docs/features/groups-and-threads.md
+++ b/docs/features/groups-and-threads.md
@@ -39,7 +39,7 @@ replies itself.
| `deleteBot` | `botId` | A group's bots stay. A deleted bot leaves its groups. |
| `reorderBots` | `ids` | The roster as the user dragged it, top first; groups count as rows. See [bot order](computer-order.md#bot-order). |
| `stop` | `botId` | For a group: ends its room turns (main and threads) and stops members working in it. |
-| `react` | `entryId, emoji` | Toggles the user's reaction on a chat message (`data.reactions`, oldest first, at most 8). A reacted-to message never turns unread again. The bot isn't told. |
+| `react` | `entryId, emoji` | Toggles the user's reaction on a chat message (`data.reactions`, oldest first, at most 8). A reacted-to message never turns unread again. The bot isn't told, except in a group, where members see reactions on the room lines they're shown. Bots react themselves with the `chat` server's `react` ([bot reactions](chat-messages.md#bot-reactions)). |
| `respondPermission` | `entryId, optionId?` | Routed to `data.author`, so cards in a group reach the bot that asked. |
| `markRead` | `botId, threadId?, all?` | The main chat, one thread (`threadId`), or everything (`all`, the roster's "Mark as read"). A no-op when nothing there is unread, so clients call it whenever a chat or thread is on screen. `send` marks its own lane read. |
@@ -53,7 +53,9 @@ replies itself.
- A member runs the turn in its **own main session** (its history is unified across chats),
told who's in the room and what was said since it last spoke there, framed as
`[Group chat: "<name>" - with …]`. Its final reply is the one message the room sees; replying
- `(pass)` says nothing. A round where nobody speaks ends the room turn.
+ `(pass)` says nothing. A round where nobody speaks ends the room turn. A member can also
+ react to someone's message (`react(emoji, to?)`), so it can agree with a reaction and pass.
+ Room lines carry their reactions: `Ann: Shipped. (reactions: User 👍, Ben 🎉)`.
- A new message in the same lane, or Stop, ends a running room turn before its next speaker;
a member still busy elsewhere skips the old room turn's queued request.
- Tool calls, thoughts and permission cards of a member's group turn are written to the
@@ -76,6 +78,6 @@ replies itself.
## Client checklist
Roster row for groups (member avatars), a trace per lane (main chat, or one thread), author label on group replies, the thread summary
-under a root (opens the thread; "N new" while `unread > 0`), "Reply in thread" on any main-chat message (desktop: while the pointer is over a message, its footer beside the time shows quick reactions, reply, copy — never on the bubble; iPhone: long-press, reactions on top of the menu), reactions under a message (tap to take back), a thread view
+under a root (opens the thread; "N new" while `unread > 0`), "Reply in thread" on any main-chat message (desktop: while the pointer is over a message, its footer beside the time shows quick reactions, reply, copy — never on the bubble; iPhone: long-press, reactions on top of the menu), reactions under a message (the user's: tap to take back; the bots': emoji plus the avatars of who chose it), a thread view
(root, replies, composer sending `threadId`), group create/edit (name, members), Stop in a
group calls `stop` with the group id.
diff --git a/host/src/agent/bot/mod.rs b/host/src/agent/bot/mod.rs
index fe6c3653..eddde15f 100644
--- a/host/src/agent/bot/mod.rs
+++ b/host/src/agent/bot/mod.rs
@@ -66,6 +66,13 @@ pub enum Cmd {
text: String,
reply: tokio::sync::oneshot::Sender<Result<()>>,
},
+ /// `react` from the bot's `chat` MCP server: an emoji on the message the turn answers.
+ React {
+ emoji: String,
+ /// In a room: whose message (see `chat::reactions::in_room`).
+ to: Option<String>,
+ reply: tokio::sync::oneshot::Sender<Result<()>>,
+ },
SendFile {
path: String,
name: Option<String>,
@@ -162,6 +169,7 @@ pub fn spawn(hub: Arc<Hub>, cfg: BotConfig) -> BotHandle {
plan_entry: None,
last_text: None,
sent: Vec::new(),
+ reacted: None,
files: files::FileShares::default(),
perms: HashMap::new(),
stop_requested: false,
@@ -319,6 +327,8 @@ struct Actor {
last_text: Option<String>,
/// Messages the bot sent the user this turn (`send_message`); none: its last text is the reply.
sent: Vec<String>,
+ /// The emoji the bot put on the user's message this turn (`react`); with no message sent, it is the reply.
+ reacted: Option<String>,
files: files::FileShares,
/// permission entry id -> JSON-RPC request id
perms: HashMap<String, Value>,
diff --git a/host/src/agent/bot/queue.rs b/host/src/agent/bot/queue.rs
index 74c543d3..0101a967 100644
--- a/host/src/agent/bot/queue.rs
+++ b/host/src/agent/bot/queue.rs
@@ -63,6 +63,9 @@ impl Actor {
Cmd::SendToUser { text, reply } => {
let _ = reply.send(self.send_to_user(text));
}
+ Cmd::React { emoji, to, reply } => {
+ let _ = reply.send(self.react(&emoji, to.as_deref()));
+ }
Cmd::SendFile { path, name, cancelled, reply } => self.begin_file(path, name, cancelled, reply),
Cmd::Stop => self.stop().await,
Cmd::Permission { entry_id, option_id } => self.answer_permission(&entry_id, option_id).await,
diff --git a/host/src/agent/bot/turn.rs b/host/src/agent/bot/turn.rs
index 583ef814..bd887bcf 100644
--- a/host/src/agent/bot/turn.rs
+++ b/host/src/agent/bot/turn.rs
@@ -105,6 +105,7 @@ impl Actor {
self.plan_entry = None;
self.last_text = None;
self.sent.clear();
+ self.reacted = None;
self.files.summary = None;
self.files.cancel();
// A delegated or group turn has no live waiter after a host restart. Its persisted
@@ -242,10 +243,15 @@ impl Actor {
let grouped = self.active_group.is_some() || routine;
let delegated = self.active_request.as_ref().is_some_and(crate::chat::team::BotRequest::expects_reply);
let sent = std::mem::take(&mut self.sent);
+ // The emoji the bot put on the user's message, when that was its whole reply.
+ let reaction = self.reacted.take().filter(|_| sent.is_empty());
if !sent.is_empty() {
// The bot talked through send_message: what it wrote as its reply stays in the trace.
self.last_text = None;
final_text = Some(sent.join("\n\n"));
+ } else if reaction.is_some() {
+ // A reaction was its whole reply: what it wrote stays in the trace too.
+ self.last_text = None;
}
if let Some(id) = self.last_text.take().filter(|_| !stopped)
&& let Some(mut e) = self.hub.store.entry(&id)
@@ -353,8 +359,9 @@ impl Actor {
&& !grouped
&& let Some(kind) = turn_alert(failed || message_failed, &stop_reason, more)
{
- let body = final_text.unwrap_or_else(|| match kind {
- AlertKind::Done => "Finished.".into(),
+ let body = final_text.unwrap_or_else(|| match (kind, reaction) {
+ (AlertKind::Done, Some(emoji)) => format!("Reacted {emoji} to your message"),
+ (AlertKind::Done, None) => "Finished.".into(),
_ => "The agent didn't finish.".into(),
});
push::notify(&self.hub, &self.cfg, None, &self.cfg.name, &body, kind);
diff --git a/host/src/agent/bot/updates.rs b/host/src/agent/bot/updates.rs
index 3e05fbe3..6b3acd91 100644
--- a/host/src/agent/bot/updates.rs
+++ b/host/src/agent/bot/updates.rs
@@ -246,6 +246,23 @@ impl Actor {
Ok(())
}
+ /// `react`: the emoji goes on the user's message this turn answers, or in a room on a message the bot was shown.
+ pub(super) fn react(&mut self, emoji: &str, to: Option<&str>) -> anyhow::Result<()> {
+ if self.turn.is_none() {
+ anyhow::bail!("no turn is running");
+ }
+ let target = match (&self.active_group, self.turn_entries.last()) {
+ (Some(g), _) => crate::chat::reactions::in_room(&self.hub, &g.lane, &self.cfg.id, to, g.shown)?,
+ (None, Some(id)) => id.clone(),
+ (None, None) => anyhow::bail!("react works only on a message you're answering in a chat or a group chat"),
+ };
+ self.hub.bot_react(&target, &self.cfg.id, emoji)?;
+ if self.active_group.is_none() {
+ self.reacted = Some(emoji.trim().to_owned());
+ }
+ Ok(())
+ }
+
// MARK: streaming text segments
pub(super) fn append(&mut self, kind: SegKind, text: &str) {
diff --git a/host/src/chat/group.rs b/host/src/chat/group.rs
index 4d3ad098..ee3b4494 100644
--- a/host/src/chat/group.rs
+++ b/host/src/chat/group.rs
@@ -35,6 +35,8 @@ const PASS: &str = "(pass)";
pub struct GroupTurn {
pub lane: Lane,
pub prompt: String,
+ /// The newest message `prompt` shows (its `seq`): a reaction goes on what the member saw.
+ pub shown: i64,
/// The room turn that asked; a member skips it once a newer one started (see [`Rooms::current`]).
pub epoch: u64,
/// The reply the room sees, or `None` for a pass.
@@ -140,9 +142,10 @@ async fn run(hub: &Arc<Hub>, group_id: &str, lane: &Lane, epoch: u64) -> Result<
if replies >= MAX_REPLIES {
break 'rounds;
}
+ let shown = hub.store.messages_after(lane, 0, 1)?.last().map_or(0, |e| e.seq);
let prompt = member_prompt(hub, &group, &members, member, lane)?;
let (reply, answer) = oneshot::channel();
- let turn = GroupTurn { lane: lane.clone(), prompt, epoch, reply };
+ let turn = GroupTurn { lane: lane.clone(), prompt, shown, epoch, reply };
if hub.send_cmd(&member.id, Cmd::Group(turn)).is_err() {
continue;
}
@@ -237,7 +240,8 @@ fn member_prompt(hub: &Hub, group: &BotConfig, members: &[BotConfig], me: &BotCo
"You have your full toolkit here. Do the work first, then answer: your final reply of this turn is \
the one message the room sees. Keep it short and conversational. @-mention another participant only \
when you need them to act. If you have nothing new worth adding, reply exactly \"{PASS}\". Never \
- reveal private one-on-one context."
+ reveal private one-on-one context. React with react(emoji, to) where a person would, `to` naming whose \
+ newest message (\"user\" or a participant); a reaction with \"{PASS}\" agrees without adding a message."
));
out.push(String::new());
@@ -270,6 +274,7 @@ fn member_prompt(hub: &Hub, group: &BotConfig, members: &[BotConfig], me: &BotCo
fn line(hub: &Hub, group: &BotConfig, e: &Entry, me: &BotConfig) -> String {
let text = e.data["text"].as_str().unwrap_or_default();
+ let reacted = crate::chat::reactions::describe(hub, e);
if e.kind == EntryKind::User.as_str() {
let root = crate::chat::uploads::root(group);
let files: Vec<_> = e.data["attachments"]
@@ -279,11 +284,15 @@ fn line(hub: &Hub, group: &BotConfig, e: &Entry, me: &BotConfig) -> String {
.filter_map(|a| crate::chat::uploads::path_of(&root, a))
.collect();
let files = if files.is_empty() { String::new() } else { crate::chat::uploads::prompt_suffix(&files) };
- return format!("User: {text}{files}");
+ return format!("User: {text}{reacted}{files}");
}
let author = e.data["author"].as_str().unwrap_or_default();
let text = crate::agent::acp::truncate(text, LINE_CHARS);
- if author == me.id { format!("{} (you): {text}", me.name) } else { format!("{}: {text}", hub.bot_name(author)) }
+ if author == me.id {
+ format!("{} (you): {text}{reacted}", me.name)
+ } else {
+ format!("{}: {text}{reacted}", hub.bot_name(author))
+ }
}
/// A member's final text is a pass (the room doesn't see it).
diff --git a/host/src/chat/mod.rs b/host/src/chat/mod.rs
index a0dd5a24..03699a6d 100644
--- a/host/src/chat/mod.rs
+++ b/host/src/chat/mod.rs
@@ -1,4 +1,4 @@
-//! Conversation features on top of bots: messages to the user, group room turns,
+//! Conversation features on top of bots: messages to the user and reactions, group room turns,
//! bot-to-bot requests, prompt snapshots, long-term memory and automatic bot names.
pub mod context;
@@ -11,5 +11,6 @@ pub mod oneshot;
pub mod outbox;
pub mod profile;
pub mod prompt;
+pub mod reactions;
pub mod team;
pub mod uploads;
diff --git a/host/src/chat/outbox.rs b/host/src/chat/outbox.rs
index d71d5f20..85b02ac1 100644
--- a/host/src/chat/outbox.rs
+++ b/host/src/chat/outbox.rs
@@ -9,12 +9,15 @@ use anyhow::{Result, anyhow, bail};
use serde_json::{Value, json};
use std::sync::Arc;
use std::time::Duration;
+use tokio::sync::oneshot;
/// How to talk to the user: part of every bot's instructions (`context`), and the `chat` server's.
pub const INSTRUCTIONS: &str = "In your chat with the user and its threads, the user sees only what you send with send_message; \
text you write as your reply never reaches them. Send a message whenever you have something worth telling them: \
short and plain, one thought per message, in the user's language. Lead with the result, then what needs the user. \
-Use send_file(path, name?) to share a generated regular file (any type, up to 100 MiB); a local path in text is not a download. Don't send just to acknowledge, to say you started or are still working, or to repeat yourself.";
+Use send_file(path, name?) to share a generated regular file (any type, up to 100 MiB); a local path in text is not a download. Don't send just to acknowledge, to say you started or are still working, or to repeat yourself. \
+React with react(emoji) where a person would: ❤️ to thanks, 🎉 to good news, 😂 to a joke, 👍 to a plain OK. When a message needs no words, \
+the reaction is the whole reply; otherwise answer as usual. Most messages get no reaction.";
/// Longest message accepted, in bytes.
const MAX_MESSAGE_BYTES: usize = 32 * 1024;
@@ -43,6 +46,12 @@ pub async fn call(hub: &Arc<Hub>, bot: &str, name: &str, args: &Value) -> Result
if name == "send_file" {
return send_file(hub, bot, args).await;
}
+ if name == crate::chat::reactions::TOOL {
+ let (emoji, to) =
+ (args["emoji"].as_str().unwrap_or_default().to_owned(), args["to"].as_str().map(str::to_owned));
+ deliver(hub, bot, |reply| Cmd::React { emoji, to, reply }).await?;
+ return Ok(json!({"reacted": true}));
+ }
if name != "send_message" {
bail!("unknown chat tool: {name}");
}
@@ -50,13 +59,18 @@ pub async fn call(hub: &Arc<Hub>, bot: &str, name: &str, args: &Value) -> Result
if text.is_empty() || text.len() > MAX_MESSAGE_BYTES {
bail!("text must be nonempty and at most {MAX_MESSAGE_BYTES} bytes");
}
- let (reply, delivered) = tokio::sync::oneshot::channel();
- hub.send_cmd(bot, Cmd::SendToUser { text: text.to_owned(), reply })?;
+ deliver(hub, bot, |reply| Cmd::SendToUser { text: text.to_owned(), reply }).await?;
+ Ok(json!({"sent": true}))
+}
+
+/// Hands the bot's actor a command for its running turn and waits for its answer.
+async fn deliver(hub: &Hub, bot: &str, cmd: impl FnOnce(oneshot::Sender<Result<()>>) -> Cmd) -> Result<()> {
+ let (reply, delivered) = oneshot::channel();
+ hub.send_cmd(bot, cmd(reply))?;
tokio::time::timeout(DELIVERY_TIMEOUT, delivered)
.await
.map_err(|_| anyhow!("the bot didn't take the message in time"))?
- .map_err(|_| anyhow!("the bot shut down"))??;
- Ok(json!({"sent": true}))
+ .map_err(|_| anyhow!("the bot shut down"))?
}
struct CancelCopy(Arc<std::sync::atomic::AtomicBool>);
@@ -73,7 +87,7 @@ async fn send_file(hub: &Arc<Hub>, bot: &str, args: &Value) -> Result<Value> {
None => None,
};
let guard = CancelCopy(Arc::new(std::sync::atomic::AtomicBool::new(false)));
- let (reply, delivered) = tokio::sync::oneshot::channel();
+ let (reply, delivered) = oneshot::channel();
hub.send_cmd(bot, Cmd::SendFile { path: path.to_owned(), name, cancelled: guard.0.clone(), reply })?;
let result = tokio::time::timeout(Duration::from_secs(60), delivered).await;
let delivered = result.map_err(|_| anyhow!("file sharing timed out; check the conversation before retrying"))?;
diff --git a/host/src/chat/reactions.rs b/host/src/chat/reactions.rs
new file mode 100644
index 00000000..8238f919
--- /dev/null
+++ b/host/src/chat/reactions.rs
@@ -0,0 +1,107 @@
+//! A bot reacts to the message it's answering with one emoji (the `chat` server's `react`):
+//! the user's message in its own chat, or someone's in a group's room turn. The bot's actor
+//! picks the message (`Actor::react`), since it knows what the turn answers.
+
+use crate::hub::Hub;
+use crate::store::{Entry, EntryKind, Lane};
+use anyhow::{Result, anyhow};
+use serde_json::{Value, json};
+
+pub const TOOL: &str = "react";
+/// Room messages searched for the one to react to.
+const RECENT: i64 = 24;
+
+pub fn tool() -> Value {
+ json!({
+ "name": TOOL,
+ "description": "React to the message you're answering with one emoji, as a person would in a chat app. It replaces your earlier reaction on that message.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "emoji": {"type": "string", "description": "One emoji, e.g. ❤️ 👍 🎉 😂."},
+ "to": {"type": "string", "description": "Group chats: whose newest message you react to, \"user\" or a participant's name. Without it: the newest message that isn't yours."},
+ },
+ "required": ["emoji"],
+ },
+ "annotations": {"readOnlyHint": false, "idempotentHint": true},
+ })
+}
+
+/// In a room, the newest message up to `shown` (the newest the bot's prompt showed) from `to`, or from anyone
+/// but `bot` when `None`.
+pub fn in_room(hub: &Hub, lane: &Lane, bot: &str, to: Option<&str>, shown: i64) -> Result<String> {
+ let to = to.map(|t| t.trim().to_lowercase()).filter(|t| !t.is_empty());
+ let from = |e: &Entry| match (&to, e.data["author"].as_str()) {
+ (_, Some(author)) if author == bot => false,
+ (None, _) => true,
+ (Some(to), _) if e.kind == EntryKind::User.as_str() => to == "user",
+ (Some(to), Some(author)) => hub.bot_name(author).trim().to_lowercase() == *to,
+ (Some(_), None) => false,
+ };
+ hub.store
+ .messages_after(lane, 0, RECENT)?
+ .into_iter()
+ .rev()
+ .find(|e| e.seq <= shown && from(e))
+ .map(|e| e.id)
+ .ok_or_else(|| anyhow!("no recent message from {} in this chat", to.as_deref().unwrap_or("anyone else")))
+}
+
+/// A room line's reactions, as members read them: ` (reactions: User 👍, Owen 🎉)`, or nothing.
+pub fn describe(hub: &Hub, e: &Entry) -> String {
+ let user =
+ e.data["reactions"].as_array().into_iter().flatten().filter_map(Value::as_str).map(|r| format!("User {r}"));
+ let bots = e.data["botReactions"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .filter_map(|r| Some(format!("{} {}", hub.bot_name(r["bot"].as_str()?), r["emoji"].as_str()?)));
+ let all: Vec<String> = user.chain(bots).collect();
+ if all.is_empty() { String::new() } else { format!(" (reactions: {})", all.join(", ")) }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::remote::identity::Identity;
+ use crate::store::{BotConfig, ReadScope, Store};
+
+ #[test]
+ fn room_reactions_pick_the_message_and_keep_it_read() {
+ let dir = std::env::temp_dir().join(format!("codync-reactions-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let store = Store::open(std::path::Path::new(":memory:")).unwrap();
+ for bot in [
+ json!({"id": "a", "name": "Ann", "backend": "claude", "cwd": dir}),
+ json!({"id": "b", "name": "Ben", "backend": "claude", "cwd": dir}),
+ json!({"id": "g", "kind": "group", "name": "Crew", "members": ["a", "b"]}),
+ ] {
+ store.save_bot(&serde_json::from_value::<BotConfig>(bot).unwrap()).unwrap();
+ }
+ let hub = Hub::new(store, "reactions-test".into(), Identity::load_or_create(&dir).unwrap(), "test".into(), 0);
+ let room = Lane::main("g");
+ let said = |kind, data: Value| hub.add_entry(&room, kind, 1, &data).unwrap();
+ let asked = said(EntryKind::User, json!({"text": "ship it?"}));
+ let reply = said(EntryKind::Agent, json!({"text": "Shipped.", "final": true, "author": "a"}));
+ let mine = said(EntryKind::Agent, json!({"text": "Nice.", "final": true, "author": "b"}));
+ let later = said(EntryKind::User, json!({"text": "one more thing"}));
+ hub.mark_read("g", ReadScope::All).unwrap();
+ let unread = || hub.bot_value_for_test("g")["unread"].as_i64().unwrap();
+
+ // Ben's turn was shown up to his own reply: the newest message from someone else before it is Ann's.
+ let target = |to| in_room(&hub, &room, "b", to, mine.seq);
+ assert_eq!(target(None).unwrap(), reply.id);
+ assert_eq!(target(Some("User")).unwrap(), asked.id, "not the message his prompt didn't show");
+ assert!(target(Some("Ben")).is_err(), "not his own message");
+ assert_eq!(in_room(&hub, &room, "b", None, later.seq).unwrap(), later.id);
+
+ // One reaction per bot; a read message stays read.
+ hub.bot_react(&reply.id, "b", "👍").unwrap();
+ let reacted = hub.bot_react(&reply.id, "b", "🎉").unwrap();
+ assert_eq!(reacted.data["botReactions"], json!([{"bot": "b", "emoji": "🎉"}]));
+ assert_eq!(unread(), 0);
+ assert_eq!(describe(&hub, &reacted), " (reactions: Ben 🎉)");
+ assert!(hub.bot_react(&reply.id, "b", "ok").is_err(), "only emoji");
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+}
diff --git a/host/src/hub.rs b/host/src/hub.rs
index e3e2b951..70a00538 100644
--- a/host/src/hub.rs
+++ b/host/src/hub.rs
@@ -19,6 +19,7 @@ use std::time::Duration;
use tokio::sync::{broadcast, watch};
mod order;
+mod reactions;
mod sync;
/// What a bot is doing right now (wire values: `idle` / `working` / `needsInput` / `error`).
@@ -47,9 +48,6 @@ pub struct Runtime {
pub fast_mode: crate::agent::config::FastModeSupport,
}
-/// Reactions per message: a handful of distinct emoji.
-const MAX_REACTIONS: usize = 8;
-
pub struct Hub {
pub analytics: crate::analytics::Analytics,
pub routines: crate::routines::Routines,
@@ -467,31 +465,6 @@ impl Hub {
updated
}
- /// Toggles the user's `emoji` reaction on a chat message (`data.reactions`, oldest first).
- /// A message keeps `reactions: []` once reacted to, so it never turns unread again.
- pub fn react(&self, id: &str, emoji: &str) -> Result<Entry> {
- let emoji = emoji.trim();
- if emoji.is_empty() || emoji.len() > 32 || emoji.chars().any(|c| c.is_alphanumeric() || c.is_whitespace()) {
- bail!("`emoji` must be one emoji");
- }
- let mut e = self.store.entry(id).ok_or_else(|| anyhow!("unknown message"))?;
- let visible =
- e.kind == EntryKind::User.as_str() || (e.kind == EntryKind::Agent.as_str() && e.data["final"] == true);
- if !visible {
- bail!("only chat messages take reactions");
- }
- let mut reactions: Vec<String> = serde_json::from_value(e.data["reactions"].clone()).unwrap_or_default();
- if let Some(i) = reactions.iter().position(|r| r == emoji) {
- reactions.remove(i);
- } else if reactions.len() >= MAX_REACTIONS {
- bail!("a message takes at most {MAX_REACTIONS} reactions");
- } else {
- reactions.push(emoji.to_owned());
- }
- e.data["reactions"] = json!(reactions);
- self.set_entry(id, &e.data).ok_or_else(|| anyhow!("couldn't save the reaction"))
- }
-
/// A message in a thread refreshes the summary on its root (`data.thread`: reply count,
/// newest reply, who replied, unread replies), which the main chat shows under it.
fn update_thread_summary(&self, e: &Entry) {
diff --git a/host/src/hub/reactions.rs b/host/src/hub/reactions.rs
new file mode 100644
index 00000000..dc8bc723
--- /dev/null
+++ b/host/src/hub/reactions.rs
@@ -0,0 +1,66 @@
+//! Emoji reactions on chat messages: the user's (`data.reactions`, toggled from any client) and
+//! the bots' (`data.botReactions`, one `{bot, emoji}` per bot, set with the `react` tool).
+
+use super::Hub;
+use crate::store::{Entry, EntryKind};
+use anyhow::{Result, anyhow, bail};
+use serde_json::json;
+
+/// The user's reactions per message: a handful of distinct emoji.
+const MAX_REACTIONS: usize = 8;
+
+impl Hub {
+ /// Toggles the user's `emoji` reaction on a chat message (`data.reactions`, oldest first).
+ /// A message keeps `reactions: []` once reacted to, so it never turns unread again.
+ pub fn react(&self, id: &str, emoji: &str) -> Result<Entry> {
+ let emoji = one_emoji(emoji)?;
+ let mut e = self.chat_message(id)?;
+ let mut reactions: Vec<String> = serde_json::from_value(e.data["reactions"].clone()).unwrap_or_default();
+ if let Some(i) = reactions.iter().position(|r| r == emoji) {
+ reactions.remove(i);
+ } else if reactions.len() >= MAX_REACTIONS {
+ bail!("a message takes at most {MAX_REACTIONS} reactions");
+ } else {
+ reactions.push(emoji.to_owned());
+ }
+ e.data["reactions"] = json!(reactions);
+ self.set_entry(id, &e.data).ok_or_else(|| anyhow!("couldn't save the reaction"))
+ }
+
+ /// `bot` reacts to a chat message with `emoji`, replacing its earlier reaction there.
+ /// The message keeps the rev of its content (`contentRev`), so a message the user read stays read.
+ pub fn bot_react(&self, id: &str, bot: &str, emoji: &str) -> Result<Entry> {
+ let emoji = one_emoji(emoji)?;
+ let mut e = self.chat_message(id)?;
+ let mut reactions = e.data["botReactions"].as_array().cloned().unwrap_or_default();
+ if reactions.iter().any(|r| r["bot"] == bot && r["emoji"] == emoji) {
+ return Ok(e);
+ }
+ reactions.retain(|r| r["bot"] != bot);
+ reactions.push(json!({"bot": bot, "emoji": emoji}));
+ e.data["botReactions"] = json!(reactions);
+ if e.data["contentRev"].is_null() {
+ e.data["contentRev"] = e.rev.into();
+ }
+ self.set_entry(id, &e.data).ok_or_else(|| anyhow!("couldn't save the reaction"))
+ }
+
+ /// A message the user sees: theirs, or a bot's final one.
+ fn chat_message(&self, id: &str) -> Result<Entry> {
+ let e = self.store.entry(id).ok_or_else(|| anyhow!("unknown message"))?;
+ let visible =
+ e.kind == EntryKind::User.as_str() || (e.kind == EntryKind::Agent.as_str() && e.data["final"] == true);
+ if !visible {
+ bail!("only chat messages take reactions");
+ }
+ Ok(e)
+ }
+}
+
+fn one_emoji(emoji: &str) -> Result<&str> {
+ let emoji = emoji.trim();
+ if emoji.is_empty() || emoji.len() > 32 || emoji.chars().any(|c| c.is_alphanumeric() || c.is_whitespace()) {
+ bail!("`emoji` must be one emoji");
+ }
+ Ok(emoji)
+}
diff --git a/host/src/mcp.rs b/host/src/mcp.rs
index 1d28ce0f..d705d000 100644
--- a/host/src/mcp.rs
+++ b/host/src/mcp.rs
@@ -1,4 +1,4 @@
-//! Built-in stdio MCP servers: `chat` sends the user messages and changes the bot's name and instructions; `team` discovers and asks other bots; `computer`
+//! Built-in stdio MCP servers: `chat` sends the user messages, reacts to messages and changes the bot's name and instructions; `team` discovers and asks other bots; `computer`
//! operates the desktop when enabled. Calls go through authenticated loopback
//! HTTP to the running host, which owns delegation and screen control.
@@ -56,6 +56,7 @@ pub async fn serve(bot: String, port: u16, server: Server) -> Result<()> {
let mut tools = crate::chat::outbox::tools();
if let Some(list) = tools.as_array_mut() {
list.extend(crate::chat::profile::tools());
+ list.push(crate::chat::reactions::tool());
}
("codync-chat", crate::chat::outbox::INSTRUCTIONS, tools)
}
diff --git a/host/src/store/bots.rs b/host/src/store/bots.rs
index 8c8776e9..e24b97ff 100644
--- a/host/src/store/bots.rs
+++ b/host/src/store/bots.rs
@@ -125,8 +125,10 @@ impl Store {
/// Final agent messages + pending permission cards newer than what the user has read in
/// `scope`. A thread counts from when it was last read (never read: the main chat's
/// `read_rev`). A thread root or a reacted-to message doesn't count again when it
- /// changes: the user replied or reacted, so they have seen it.
+ /// changes: the user replied or reacted, so they have seen it. A bot's reaction isn't a change either
+ /// (`contentRev`, see `Hub::bot_react`).
pub fn unread(&self, id: &str, read_rev: i64, scope: ReadScope) -> i64 {
+ let seen = "COALESCE(json_extract(data, '$.contentRev'), rev)";
let mut args: Vec<&dyn rusqlite::ToSql> = vec![&id, &read_rev];
let filter = match &scope {
ReadScope::All => "",
@@ -143,8 +145,8 @@ impl Store {
((kind = 'agent' AND json_extract(data, '$.final') = 1) OR
(kind = 'permission' AND json_extract(data, '$.status') = 'pending')) AND
json_extract(data, '$.reactions') IS NULL AND
- CASE WHEN thread_id IS NULL THEN rev > ?2 AND json_extract(data, '$.thread') IS NULL
- ELSE rev > COALESCE((SELECT CAST(v AS INTEGER) FROM kv WHERE k = 'read.' || thread_id), ?2) END"
+ CASE WHEN thread_id IS NULL THEN {seen} > ?2 AND json_extract(data, '$.thread') IS NULL
+ ELSE {seen} > COALESCE((SELECT CAST(v AS INTEGER) FROM kv WHERE k = 'read.' || thread_id), ?2) END"
),
args.as_slice(),
|r| r.get(0),
diff --git a/host/src/tui/view/transcript.rs b/host/src/tui/view/transcript.rs
index 8b2d87da..58774aad 100644
--- a/host/src/tui/view/transcript.rs
+++ b/host/src/tui/view/transcript.rs
@@ -220,7 +220,7 @@ fn entry_lines(
]));
}
out.lines.extend(with_bg(body, width, t.band));
- reactions(out, e);
+ reactions(out, app, e);
out.messages.push((e.id.clone(), from, out.lines.len()));
if main {
thread_line(out, app, e);
@@ -253,7 +253,7 @@ fn entry_lines(
} else {
out.lines.extend(md::render(e.text(), width, 1));
}
- reactions(out, e);
+ reactions(out, app, e);
out.messages.push((e.id.clone(), from, out.lines.len()));
if let Some(ti) = info.get(&e.turn).filter(|ti| ti.steps > 0 && ti.last_message.as_ref() == Some(&e.id)) {
let files = if ti.files.is_empty() {
@@ -378,11 +378,24 @@ fn bot_message_line(out: &mut Built, app: &App, e: &Entry, peer: &str, lead: &st
out.messages.push((e.id.clone(), from, out.lines.len()));
}
-/// A message's reactions, under it.
-fn reactions(out: &mut Built, e: &Entry) {
- let r: Vec<&str> = e.data["reactions"].as_array().into_iter().flatten().filter_map(|r| r.as_str()).collect();
+/// A message's reactions, under it: the user's, then the bots', each emoji with who chose it.
+fn reactions(out: &mut Built, app: &App, e: &Entry) {
+ let mut r: Vec<String> =
+ e.data["reactions"].as_array().into_iter().flatten().filter_map(|r| r.as_str().map(str::to_owned)).collect();
+ let mut bots: Vec<(&str, Vec<String>)> = vec![];
+ for b in e.data["botReactions"].as_array().into_iter().flatten() {
+ let (Some(emoji), Some(bot)) = (b["emoji"].as_str(), app.bots.get(b["bot"].as_str().unwrap_or_default()))
+ else {
+ continue;
+ };
+ match bots.iter_mut().find(|(e, _)| *e == emoji) {
+ Some((_, names)) => names.push(bot.name.clone()),
+ None => bots.push((emoji, vec![bot.name.clone()])),
+ }
+ }
+ r.extend(bots.into_iter().map(|(emoji, names)| format!("{emoji} {}", names.join(", "))));
if !r.is_empty() {
- out.lines.push(Line::from(Span::raw(format!(" {}", r.join(" ")))));
+ out.lines.push(Line::from(Span::raw(format!(" {}", r.join(" ")))));
}
}
diff --git a/host/tests/fixtures/team_agent.py b/host/tests/fixtures/team_agent.py
index 98d2e967..2cbdeda1 100644
--- a/host/tests/fixtures/team_agent.py
+++ b/host/tests/fixtures/team_agent.py
@@ -100,6 +100,12 @@ def prompt(request):
time.sleep(0.3)
send({"id": request["id"], "result": {"stopReason": "end_turn"}})
return
+ if text.split("\n\n")[-1] == "THANKS":
+ response = mcp_call("chat", "react", {"emoji": "❤️"})
+ assert not response.get("isError"), response
+ update({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "Reacted with a heart"}})
+ send({"id": request["id"], "result": {"stopReason": "end_turn"}})
+ return
if "PERMISSION" in text:
send({"id": "permission", "method": "session/request_permission", "params": {
"sessionId": "session", "toolCall": {"toolCallId": "edit", "title": "Edit a file"},
@@ -119,6 +125,10 @@ def prompt(request):
room = text.split("New messages in the room (oldest first):\n", 1)[-1].split("\n\n", 1)[0]
last = room.strip().splitlines()[-1] if "New messages" in text else ""
reply = "reply: group" if last.startswith("User:") else "(pass)"
+ if "REACT" in last:
+ response = mcp_call("chat", "react", {"emoji": "👍", "to": "user"})
+ assert not response.get("isError"), response
+ reply = "(pass)"
# Two chunks, apart: the streamed entry is rewritten before it's final.
update({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": reply[:3]}})
time.sleep(0.4)
diff --git a/host/tests/turns_e2e.rs b/host/tests/turns_e2e.rs
index b26a1cb6..af4a87e4 100644
--- a/host/tests/turns_e2e.rs
+++ b/host/tests/turns_e2e.rs
@@ -1,5 +1,5 @@
//! A real host driving scripted ACP agents: Stop on an agent that ignores it, room turns
-//! that a newer group message replaced, and Fast mode across session resumes.
+//! that a newer group message replaced, a reaction as the whole reply, and Fast mode across session resumes.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
@@ -74,6 +74,20 @@ impl Host {
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
+
+ /// Polls until every bot is idle.
+ async fn wait_idle(&self) {
+ let deadline = Instant::now() + Duration::from_secs(60);
+ while common::snapshot(&self.base, &self.token).await["bots"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .any(|b| b["status"] != "idle")
+ {
+ assert!(Instant::now() < deadline, "a turn didn't finish");
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ }
}
fn python_missing() -> bool {
@@ -139,6 +153,44 @@ async fn a_member_busy_elsewhere_answers_only_the_latest_room_turn() {
assert_eq!(finals.count(), 1);
}
+#[tokio::test]
+async fn a_reaction_can_be_the_whole_reply() {
+ if python_missing() {
+ return;
+ }
+ let host = Host::start().await;
+ let bot = host.bot("Warm", "tests/fixtures/team_agent.py").await;
+ let finals = |entries: Vec<Value>| {
+ entries.into_iter().filter(|e| e["kind"] == "agent" && e["data"]["final"] == true).count()
+ };
+
+ // In its own chat: the heart on the user's message is the reply; what the agent wrote stays in the trace.
+ let thanks = host.call("send", json!({"botId": bot, "text": "THANKS"})).await;
+ let heart = json!([{"bot": bot, "emoji": "❤️"}]);
+ host.wait_for(&bot, Duration::from_secs(60), |e| {
+ e["id"] == thanks["entry"]["id"] && e["data"]["botReactions"] == heart
+ })
+ .await;
+ host.wait_idle().await;
+ let entries = host.entries(&bot).await;
+ assert!(entries.iter().any(|e| e["data"]["text"] == "Reacted with a heart" && e["data"]["final"] == false));
+ assert_eq!(finals(entries), 0);
+
+ // In a room: the member reacts to the user's message and passes.
+ let group = host.call("createBot", json!({"name": "Room", "kind": "group", "members": [bot]})).await["bot"]["id"]
+ .as_str()
+ .unwrap()
+ .to_owned();
+ let asked = host.call("send", json!({"botId": group, "text": "REACT if you agree"})).await;
+ let thumb = json!([{"bot": bot, "emoji": "👍"}]);
+ host.wait_for(&group, Duration::from_secs(60), |e| {
+ e["id"] == asked["entry"]["id"] && e["data"]["botReactions"] == thumb
+ })
+ .await;
+ host.wait_idle().await;
+ assert_eq!(finals(host.entries(&group).await), 0);
+}
+
/// A final reply that starts with `speed` and quotes `word` from its prompt.
fn speed_reply(speed: &'static str, word: &'static str) -> impl Fn(&Value) -> bool {
move |e: &Value| {