Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

feat(bots): react to visible messages (#89)

Leo453e53d2b22b
diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
index eec8f6ab2..9826927db 100644
--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
@@ -1264,6 +1264,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
role: event.payload.role,
text: nextText,
...(nextAttachments !== undefined ? { attachments: [...nextAttachments] } : {}),
+ reactions: previousMessage?.reactions ?? [],
isStreaming: event.payload.streaming,
createdAt: previousMessage?.createdAt ?? event.payload.createdAt,
updatedAt: event.payload.updatedAt,
@@ -1271,6 +1272,25 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
return;
}
+ case "thread.message-reaction-set": {
+ const existingMessage = yield* projectionThreadMessageRepository.getByMessageId({
+ messageId: event.payload.messageId,
+ });
+ if (Option.isNone(existingMessage)) return;
+ const withoutReaction = (existingMessage.value.reactions ?? []).filter(
+ (reaction) =>
+ reaction.botId !== event.payload.botId || reaction.emoji !== event.payload.emoji,
+ );
+ yield* projectionThreadMessageRepository.upsert({
+ ...existingMessage.value,
+ reactions: event.payload.present
+ ? [...withoutReaction, { botId: event.payload.botId, emoji: event.payload.emoji }]
+ : withoutReaction,
+ updatedAt: event.payload.updatedAt,
+ });
+ return;
+ }
+
case "thread.reverted": {
const existingRows = yield* projectionThreadMessageRepository.listByThreadId({
threadId: event.payload.threadId,
diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts
index 4a54d12a1..ca2164944 100644
--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts
+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts
@@ -413,6 +413,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
text: "hello from projection",
turnId: asTurnId("turn-1"),
respondingBotId: null,
+ reactions: [],
streaming: false,
createdAt: "2026-02-24T00:00:04.000Z",
updatedAt: "2026-02-24T00:00:05.000Z",
diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
index 4713de75e..a5ddee189 100644
--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
@@ -12,6 +12,7 @@ import {
McpServerId,
NonNegativeInt,
OrchestrationCheckpointFile,
+ OrchestrationMessageReaction,
OrchestrationProposedPlanId,
OrchestrationReadModel,
OrchestrationThreadSearchSource,
@@ -112,6 +113,7 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
Struct.assign({
isStreaming: Schema.Number,
attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))),
+ reactions: Schema.fromJsonString(Schema.Array(OrchestrationMessageReaction)),
}),
);
const ProjectionThreadProposedPlanDbRowSchema = ProjectionThreadProposedPlan;
@@ -662,6 +664,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
role,
text,
attachments_json AS "attachments",
+ reactions_json AS "reactions",
is_streaming AS "isStreaming",
created_at AS "createdAt",
updated_at AS "updatedAt"
@@ -1135,6 +1138,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
role,
text,
attachments_json AS "attachments",
+ reactions_json AS "reactions",
is_streaming AS "isStreaming",
created_at AS "createdAt",
updated_at AS "updatedAt"
@@ -1382,6 +1386,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
role,
text,
attachments_json AS "attachments",
+ reactions_json AS "reactions",
is_streaming AS "isStreaming",
created_at AS "createdAt",
updated_at AS "updatedAt"
@@ -1767,6 +1772,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
...(row.attachments !== null ? { attachments: row.attachments } : {}),
turnId: row.turnId,
respondingBotId: row.respondingBotId ?? null,
+ reactions: row.reactions,
streaming: row.isStreaming === 1,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
@@ -2982,6 +2988,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
text: row.text,
turnId: row.turnId,
respondingBotId: row.respondingBotId ?? null,
+ reactions: row.reactions,
streaming: row.isStreaming === 1,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
index 31a8371d1..82c0a73ab 100644
--- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
+++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
@@ -354,6 +354,12 @@ const make = Effect.gen(function* () {
if (agentController.configureDelegation) {
yield* agentController.configureDelegation({
readSnapshot: () => runPromise(projectionSnapshotQuery.getCommandReadModel()),
+ readThread: (threadId) =>
+ runPromise(
+ projectionSnapshotQuery
+ .getThreadDetailById(threadId)
+ .pipe(Effect.map(Option.getOrUndefined)),
+ ),
dispatch: (command) => runPromise(orchestrationEngine.dispatch(command)),
});
}
diff --git a/apps/server/src/orchestration/Schemas.ts b/apps/server/src/orchestration/Schemas.ts
index 563d19f10..1f9bd3a07 100644
--- a/apps/server/src/orchestration/Schemas.ts
+++ b/apps/server/src/orchestration/Schemas.ts
@@ -32,6 +32,7 @@ import {
ThreadUnpinnedPayload as ContractsThreadUnpinnedPayloadSchema,
ThreadPinReorderedPayload as ContractsThreadPinReorderedPayloadSchema,
ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,
+ ThreadMessageReactionSetPayload as ContractsThreadMessageReactionSetPayloadSchema,
ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,
ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,
ThreadTurnDiffCompletedPayload as ContractsThreadTurnDiffCompletedPayloadSchema,
@@ -81,6 +82,7 @@ export const ThreadUnpinnedPayload = ContractsThreadUnpinnedPayloadSchema;
export const ThreadPinReorderedPayload = ContractsThreadPinReorderedPayloadSchema;
export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;
+export const ThreadMessageReactionSetPayload = ContractsThreadMessageReactionSetPayloadSchema;
export const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema;
export const ThreadSessionSetPayload = ContractsThreadSessionSetPayloadSchema;
export const ThreadTurnDiffCompletedPayload = ContractsThreadTurnDiffCompletedPayloadSchema;
diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts
index 74f7e5872..f35d78ece 100644
--- a/apps/server/src/orchestration/decider.ts
+++ b/apps/server/src/orchestration/decider.ts
@@ -2298,6 +2298,50 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
}
+ case "thread.message.reaction.set": {
+ const thread = yield* requireThread({
+ readModel,
+ command,
+ threadId: command.threadId,
+ });
+ if (!thread.messages.some((message) => message.id === command.messageId)) {
+ return yield* new OrchestrationCommandInvariantError({
+ commandType: command.type,
+ detail: `Message '${command.messageId}' is not visible in thread '${command.threadId}'.`,
+ });
+ }
+ if (thread.groupId != null) {
+ yield* requireActiveGroupMember({
+ readModel,
+ command,
+ groupId: thread.groupId,
+ botId: command.botId,
+ });
+ } else if (thread.botId !== command.botId) {
+ return yield* new OrchestrationCommandInvariantError({
+ commandType: command.type,
+ detail: `Bot '${command.botId}' cannot react in thread '${command.threadId}'.`,
+ });
+ }
+ return {
+ ...(yield* withEventBase({
+ aggregateKind: "thread",
+ aggregateId: command.threadId,
+ occurredAt: command.updatedAt,
+ commandId: command.commandId,
+ })),
+ type: "thread.message-reaction-set",
+ payload: {
+ threadId: command.threadId,
+ messageId: command.messageId,
+ botId: command.botId,
+ emoji: command.emoji,
+ present: command.present,
+ updatedAt: command.updatedAt,
+ },
+ };
+ }
+
case "thread.proposed-plan.upsert": {
yield* requireThread({
readModel,
diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts
index a0c45003f..834a04b90 100644
--- a/apps/server/src/orchestration/projector.ts
+++ b/apps/server/src/orchestration/projector.ts
@@ -40,6 +40,7 @@ import {
ThreadCreatedPayload,
ThreadDeletedPayload,
ThreadInteractionModeSetPayload,
+ ThreadMessageReactionSetPayload,
ThreadMetaUpdatedPayload,
ThreadProposedPlanUpsertedPayload,
ThreadRuntimeModeSetPayload,
@@ -846,6 +847,39 @@ export function projectEvent(
};
});
+ case "thread.message-reaction-set":
+ return decodeForEvent(
+ ThreadMessageReactionSetPayload,
+ event.payload,
+ event.type,
+ "payload",
+ ).pipe(
+ Effect.map((payload) => {
+ const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
+ if (!thread) return nextBase;
+ const messages = thread.messages.map((message) => {
+ if (message.id !== payload.messageId) return message;
+ const withoutReaction = (message.reactions ?? []).filter(
+ (reaction) => reaction.botId !== payload.botId || reaction.emoji !== payload.emoji,
+ );
+ return {
+ ...message,
+ reactions: payload.present
+ ? [...withoutReaction, { botId: payload.botId, emoji: payload.emoji }]
+ : withoutReaction,
+ updatedAt: payload.updatedAt,
+ };
+ });
+ return {
+ ...nextBase,
+ threads: updateThread(nextBase.threads, payload.threadId, {
+ messages,
+ updatedAt: payload.updatedAt,
+ }),
+ };
+ }),
+ );
+
case "thread.turn-start-requested":
return decodeForEvent(
ThreadTurnStartRequestedPayload,
diff --git a/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts b/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts
index 9b20c2c94..a8c9e2db2 100644
--- a/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts
+++ b/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts
@@ -5,7 +5,7 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Struct from "effect/Struct";
-import { ChatAttachment } from "@t3tools/contracts";
+import { ChatAttachment, OrchestrationMessageReaction } from "@t3tools/contracts";
import { toPersistenceSqlError } from "../Errors.ts";
import {
@@ -21,6 +21,7 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
Struct.assign({
isStreaming: Schema.Number,
attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))),
+ reactions: Schema.fromJsonString(Schema.Array(OrchestrationMessageReaction)),
}),
);
@@ -38,6 +39,7 @@ function toProjectionThreadMessage(
createdAt: row.createdAt,
updatedAt: row.updatedAt,
...(row.attachments !== null ? { attachments: row.attachments } : {}),
+ reactions: row.reactions,
};
}
@@ -49,6 +51,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
execute: (row) => {
const nextAttachmentsJson =
row.attachments !== undefined ? JSON.stringify(row.attachments) : null;
+ const reactionsJson = JSON.stringify(row.reactions ?? []);
return sql`
INSERT INTO projection_thread_messages (
message_id,
@@ -58,6 +61,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
role,
text,
attachments_json,
+ reactions_json,
is_streaming,
created_at,
updated_at
@@ -77,6 +81,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
WHERE message_id = ${row.messageId}
)
),
+ ${reactionsJson},
${row.isStreaming ? 1 : 0},
${row.createdAt},
${row.updatedAt}
@@ -92,6 +97,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
excluded.attachments_json,
projection_thread_messages.attachments_json
),
+ reactions_json = excluded.reactions_json,
is_streaming = excluded.is_streaming,
created_at = excluded.created_at,
updated_at = excluded.updated_at
@@ -112,6 +118,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
role,
text,
attachments_json AS "attachments",
+ reactions_json AS "reactions",
is_streaming AS "isStreaming",
created_at AS "createdAt",
updated_at AS "updatedAt"
@@ -134,6 +141,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
role,
text,
attachments_json AS "attachments",
+ reactions_json AS "reactions",
is_streaming AS "isStreaming",
created_at AS "createdAt",
updated_at AS "updatedAt"
diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts
index ebf57e646..16ff578b7 100644
--- a/apps/server/src/persistence/Migrations.ts
+++ b/apps/server/src/persistence/Migrations.ts
@@ -72,6 +72,7 @@ import Migration0056 from "./Migrations/056_AkeruBotUsageLedger.ts";
import Migration0057 from "./Migrations/057_AkeruMemoryCandidateUpdates.ts";
import Migration0058 from "./Migrations/058_ProjectionDelegations.ts";
import Migration0059 from "./Migrations/059_ProjectionThreadSessionMcpServers.ts";
+import Migration0060 from "./Migrations/060_ProjectionMessageReactions.ts";
/**
* Migration loader with all migrations defined inline.
@@ -143,6 +144,7 @@ export const migrationEntries = [
[57, "AkeruMemoryCandidateUpdates", Migration0057],
[58, "ProjectionDelegations", Migration0058],
[59, "ProjectionThreadSessionMcpServers", Migration0059],
+ [60, "ProjectionMessageReactions", Migration0060],
] as const;
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
diff --git a/apps/server/src/persistence/Migrations/060_ProjectionMessageReactions.ts b/apps/server/src/persistence/Migrations/060_ProjectionMessageReactions.ts
new file mode 100644
index 000000000..822c1c9a7
--- /dev/null
+++ b/apps/server/src/persistence/Migrations/060_ProjectionMessageReactions.ts
@@ -0,0 +1,7 @@
+import * as Effect from "effect/Effect";
+import * as SqlClient from "effect/unstable/sql/SqlClient";
+
+export default Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ yield* sql`ALTER TABLE projection_thread_messages ADD COLUMN reactions_json TEXT NOT NULL DEFAULT '[]'`;
+});
diff --git a/apps/server/src/persistence/Services/ProjectionThreadMessages.ts b/apps/server/src/persistence/Services/ProjectionThreadMessages.ts
index a55853b33..51396d708 100644
--- a/apps/server/src/persistence/Services/ProjectionThreadMessages.ts
+++ b/apps/server/src/persistence/Services/ProjectionThreadMessages.ts
@@ -10,6 +10,7 @@ import {
BotId,
ChatAttachment,
MessageId,
+ OrchestrationMessageReaction,
OrchestrationMessageRole,
ThreadId,
TurnId,
@@ -18,7 +19,7 @@ import {
import * as Schema from "effect/Schema";
import * as Context from "effect/Context";
import type * as Option from "effect/Option";
-import type * as Effect from "effect/Effect";
+import * as Effect from "effect/Effect";
import type { ProjectionRepositoryError } from "../Errors.ts";
@@ -30,6 +31,7 @@ export const ProjectionThreadMessage = Schema.Struct({
role: OrchestrationMessageRole,
text: Schema.String,
attachments: Schema.optional(Schema.Array(ChatAttachment)),
+ reactions: Schema.optional(Schema.Array(OrchestrationMessageReaction)),
isStreaming: Schema.Boolean,
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
diff --git a/apps/server/src/provider/AkeruChannelRuntime.test.ts b/apps/server/src/provider/AkeruChannelRuntime.test.ts
index 14a1bf727..a539849b7 100644
--- a/apps/server/src/provider/AkeruChannelRuntime.test.ts
+++ b/apps/server/src/provider/AkeruChannelRuntime.test.ts
@@ -1,4 +1,12 @@
-import { BotId, GroupId, type OrchestrationReadModel } from "@t3tools/contracts";
+import {
+ BotId,
+ GroupId,
+ MessageId,
+ ProjectId,
+ ProviderInstanceId,
+ ThreadId,
+ type OrchestrationReadModel,
+} from "@t3tools/contracts";
import { describe, expect, it, vi } from "vite-plus/test";
import { createAkeruChannelRuntime } from "./AkeruChannelRuntime.ts";
@@ -7,6 +15,8 @@ const now = "2026-09-01T00:00:00.000Z";
const bossBotId = BotId.make("boss");
const specialistBotId = BotId.make("specialist");
const channelId = GroupId.make("channel-1");
+const threadId = ThreadId.make("thread-1");
+const messageId = MessageId.make("message-1");
const bot = (id: BotId, groupId: GroupId | null) => ({
id,
@@ -49,6 +59,48 @@ const snapshot: OrchestrationReadModel = {
updatedAt: now,
};
+const snapshotWithMessage = (reacted = false): OrchestrationReadModel => ({
+ ...snapshot,
+ threads: [
+ {
+ id: threadId,
+ projectId: ProjectId.make("project-1"),
+ botId: null,
+ groupId: channelId,
+ respondingBotId: bossBotId,
+ title: "Launch",
+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
+ runtimeMode: "approval-required",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ latestTurn: null,
+ createdAt: now,
+ updatedAt: now,
+ archivedAt: null,
+ settledOverride: null,
+ settledAt: null,
+ deletedAt: null,
+ messages: [
+ {
+ id: messageId,
+ role: "user",
+ text: "Ship it",
+ turnId: null,
+ reactions: reacted ? [{ botId: bossBotId, emoji: "πŸ‘" }] : [],
+ streaming: false,
+ createdAt: now,
+ updatedAt: now,
+ },
+ ],
+ proposedPlans: [],
+ activities: [],
+ checkpoints: [],
+ session: null,
+ },
+ ],
+});
+
describe("AkeruChannelRuntime", () => {
it("creates a persisted group with the calling bot as boss", async () => {
const dispatch = vi.fn();
@@ -99,4 +151,114 @@ describe("AkeruChannelRuntime", () => {
).rejects.toThrow("does not exist");
expect(dispatch).not.toHaveBeenCalled();
});
+
+ it("adds reactions once and keeps retries idempotent", async () => {
+ const dispatch = vi.fn();
+ const readThread = vi
+ .fn()
+ .mockResolvedValueOnce(snapshotWithMessage().threads[0])
+ .mockResolvedValue(snapshotWithMessage(true).threads[0]);
+ const runtime = createAkeruChannelRuntime({
+ readSnapshot: async () => snapshot,
+ readThread,
+ dispatch,
+ now: () => now,
+ });
+ const input = { messageId, emoji: "πŸ‘", action: "add" as const };
+
+ await expect(
+ runtime.react(threadId, bossBotId, input, "reaction-add-1"),
+ ).resolves.toMatchObject({
+ status: "applied",
+ changed: true,
+ });
+ await expect(
+ runtime.react(threadId, bossBotId, input, "reaction-add-1"),
+ ).resolves.toMatchObject({
+ status: "applied",
+ changed: false,
+ });
+ expect(dispatch).toHaveBeenCalledOnce();
+ });
+
+ it("dispatches a new command when a removed reaction is added again", async () => {
+ const dispatch = vi.fn();
+ const readSnapshot = vi
+ .fn<() => Promise<OrchestrationReadModel>>()
+ .mockResolvedValueOnce({ ...snapshot, snapshotSequence: 1 })
+ .mockResolvedValueOnce({ ...snapshot, snapshotSequence: 2 })
+ .mockResolvedValueOnce({ ...snapshot, snapshotSequence: 3 });
+ const readThread = vi
+ .fn()
+ .mockResolvedValueOnce(snapshotWithMessage().threads[0])
+ .mockResolvedValueOnce(snapshotWithMessage(true).threads[0])
+ .mockResolvedValueOnce(snapshotWithMessage().threads[0]);
+ const runtime = createAkeruChannelRuntime({
+ readSnapshot,
+ readThread,
+ dispatch,
+ now: () => now,
+ });
+
+ await runtime.react(
+ threadId,
+ bossBotId,
+ { messageId, emoji: "πŸ‘", action: "add" },
+ "reaction-add-1",
+ );
+ await runtime.react(
+ threadId,
+ bossBotId,
+ { messageId, emoji: "πŸ‘", action: "remove" },
+ "reaction-remove-1",
+ );
+ await runtime.react(
+ threadId,
+ bossBotId,
+ { messageId, emoji: "πŸ‘", action: "add" },
+ "reaction-add-1",
+ );
+
+ expect(dispatch).toHaveBeenCalledTimes(3);
+ expect(new Set(dispatch.mock.calls.map(([command]) => command.commandId)).size).toBe(3);
+ });
+
+ it("returns a typed unsupported result and rejects invisible messages", async () => {
+ const dispatch = vi.fn();
+ const unsupported = createAkeruChannelRuntime({
+ readSnapshot: async () => snapshotWithMessage(),
+ dispatch,
+ supportsReactions: () => false,
+ });
+ await expect(
+ unsupported.react(
+ threadId,
+ bossBotId,
+ { messageId, emoji: "πŸ‘", action: "add" },
+ "reaction-unsupported",
+ ),
+ ).resolves.toEqual({
+ status: "unsupported",
+ messageId,
+ reason: "channel-does-not-support-reactions",
+ });
+
+ const hidden = createAkeruChannelRuntime({
+ readSnapshot: async () => snapshotWithMessage(),
+ dispatch,
+ });
+ await expect(
+ hidden.react(
+ threadId,
+ BotId.make("outsider"),
+ {
+ messageId,
+ emoji: "πŸ‘",
+ action: "add",
+ },
+ "reaction-hidden",
+ ),
+ ).rejects.toThrow("not visible");
+ expect(dispatch).not.toHaveBeenCalled();
+ });
});
diff --git a/apps/server/src/provider/AkeruChannelRuntime.ts b/apps/server/src/provider/AkeruChannelRuntime.ts
index 90b1ed2f2..49b19bfd0 100644
--- a/apps/server/src/provider/AkeruChannelRuntime.ts
+++ b/apps/server/src/provider/AkeruChannelRuntime.ts
@@ -3,19 +3,24 @@ import * as NodeCrypto from "node:crypto";
import {
BotId,
+ type AkeruMessageReactionResult,
CommandId,
GroupId,
+ ThreadId,
type AkeruToolInputSchemas,
type OrchestrationCommand,
type OrchestrationReadModel,
+ type OrchestrationThread,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
export interface AkeruChannelRuntimeOptions {
readonly readSnapshot: () => Promise<OrchestrationReadModel>;
+ readonly readThread?: (threadId: ThreadId) => Promise<OrchestrationThread | undefined>;
readonly dispatch: (command: OrchestrationCommand) => Promise<unknown>;
readonly now?: () => string;
readonly id?: () => string;
+ readonly supportsReactions?: (thread: OrchestrationThread) => boolean;
}
export function createAkeruChannelRuntime(options: AkeruChannelRuntimeOptions) {
@@ -61,7 +66,55 @@ export function createAkeruChannelRuntime(options: AkeruChannelRuntimeOptions) {
return input.channelId;
};
- return { create, update };
+ const react = async (
+ threadId: ThreadId,
+ botId: BotId,
+ input: (typeof AkeruToolInputSchemas.ReactToMessage)["Type"],
+ toolCallId: string,
+ ): Promise<AkeruMessageReactionResult> => {
+ const snapshot = await options.readSnapshot();
+ const thread = options.readThread
+ ? await options.readThread(threadId)
+ : snapshot.threads.find((entry) => entry.id === threadId);
+ const message = thread?.messages.find((entry) => entry.id === input.messageId);
+ if (!thread || !message) throw new Error("The target message is not visible to this bot.");
+ const isVisible =
+ thread.botId === botId ||
+ (thread.groupId != null &&
+ snapshot.groups
+ .find((group) => group.id === thread.groupId)
+ ?.members.some((member) => member.botId === botId));
+ if (!isVisible) throw new Error("The target message is not visible to this bot.");
+ if (options.supportsReactions?.(thread) === false) {
+ return {
+ status: "unsupported",
+ messageId: input.messageId,
+ reason: "channel-does-not-support-reactions",
+ };
+ }
+
+ const present = (message.reactions ?? []).some(
+ (reaction) => reaction.botId === botId && reaction.emoji === input.emoji,
+ );
+ const nextPresent = input.action === "add";
+ if (present === nextPresent) return { status: "applied", ...input, changed: false };
+ const commandKey = NodeCrypto.createHash("sha256")
+ .update(`${threadId}\u0000${botId}\u0000${toolCallId}\u0000${snapshot.snapshotSequence}`)
+ .digest("hex");
+ await options.dispatch({
+ type: "thread.message.reaction.set",
+ commandId: CommandId.make(`reaction:${commandKey}`),
+ threadId: thread.id,
+ messageId: input.messageId,
+ botId,
+ emoji: input.emoji,
+ present: nextPresent,
+ updatedAt: now(),
+ });
+ return { status: "applied", ...input, changed: true };
+ };
+
+ return { create, update, react };
}
export type AkeruChannelRuntime = ReturnType<typeof createAkeruChannelRuntime>;
diff --git a/apps/server/src/provider/AkeruToolRuntime.test.ts b/apps/server/src/provider/AkeruToolRuntime.test.ts
index b6627fc79..c445d6730 100644
--- a/apps/server/src/provider/AkeruToolRuntime.test.ts
+++ b/apps/server/src/provider/AkeruToolRuntime.test.ts
@@ -779,6 +779,28 @@ describe("AkeruToolRuntime", () => {
expect(receipts.map((receipt) => receipt.phase)).toEqual(["start", "failure"]);
});
+ it("requires approval before a message reaction runs", async () => {
+ const reactToMessage = vi.fn(async () => ({ status: "applied", changed: true }));
+ const runtime = createAkeruToolRuntime();
+ runtime.registerSession("thread-reaction", {
+ botId: BotId.make("parent"),
+ runtimeMode: "full-access",
+ workspaceType: "none",
+ reactToMessage,
+ });
+ const execution = {
+ threadId: "thread-reaction",
+ toolId: "ReactToMessage" as const,
+ toolCallId: "reaction-1",
+ input: { messageId: "message-1", emoji: "πŸ‘", action: "add" as const },
+ approvalMode: "require-grant" as const,
+ };
+ await expect(runtime.execute(execution)).rejects.toThrow("requires approval");
+ runtime.grantApproval(execution);
+ await expect(runtime.execute(execution)).resolves.toMatchObject({ status: "applied" });
+ expect(reactToMessage).toHaveBeenCalledWith(execution.input, execution.toolCallId);
+ });
+
it("translates await handles to workspace process ids", async () => {
const runtime = createAkeruToolRuntime();
runtime.registerSession("thread-1", {
diff --git a/apps/server/src/provider/AkeruToolRuntime.ts b/apps/server/src/provider/AkeruToolRuntime.ts
index 8b7bc6377..1463037d0 100644
--- a/apps/server/src/provider/AkeruToolRuntime.ts
+++ b/apps/server/src/provider/AkeruToolRuntime.ts
@@ -87,6 +87,10 @@ export interface AkeruToolSession {
input: (typeof AkeruToolInputSchemas.SendToUser)["Type"],
) => Promise<AkeruToolReceipt>;
readonly botState?: Pick<AkeruBotStateRuntime, "updateProfile">;
+ readonly reactToMessage?: (
+ input: (typeof AkeruToolInputSchemas.ReactToMessage)["Type"],
+ toolCallId: string,
+ ) => Promise<unknown>;
readonly catalogHandlers?: Partial<Record<AkeruToolId, AkeruCatalogToolHandler>>;
}
@@ -141,6 +145,7 @@ const BACKEND_NAMES: Record<
| "UpdateBotProfile"
| "SearchPlugins"
| "GetPlugin"
+ | "ReactToMessage"
| "InstallPlugin"
| "UninstallPlugin"
| "GetMcpServerStatus"
@@ -371,6 +376,7 @@ export function createAkeruToolRuntime(options?: AkeruToolRuntimeOptions): Akeru
}
if (session.sendToUser) tools.add("SendToUser");
if (session.botId && session.botState) tools.add("UpdateBotProfile");
+ if (session.reactToMessage) tools.add("ReactToMessage");
for (const toolId of Object.keys(session.catalogHandlers ?? {}) as AkeruToolId[]) {
tools.add(toolId);
}
@@ -680,6 +686,15 @@ export function createAkeruToolRuntime(options?: AkeruToolRuntimeOptions): Akeru
emitReceipt(input, "failure", { failureCode, summary });
return result;
}
+ } else if (input.toolId === "ReactToMessage") {
+ if (!session.reactToMessage) {
+ throw new Error("Message reactions are not available for this session.");
+ }
+ failureCode = "internal";
+ result = await session.reactToMessage(
+ decodeAkeruToolInput("ReactToMessage", decoded),
+ input.toolCallId,
+ );
} else if (input.toolId === "CopyToBox" || input.toolId === "CopyFromBox") {
const source =
input.toolId === "CopyToBox" ? session.userComputerWorkspace : session.workspace;
diff --git a/apps/server/src/provider/Layers/AgentController.ts b/apps/server/src/provider/Layers/AgentController.ts
index 2a5c20a18..e7bba1c00 100644
--- a/apps/server/src/provider/Layers/AgentController.ts
+++ b/apps/server/src/provider/Layers/AgentController.ts
@@ -1513,6 +1513,8 @@ const make = (options?: AgentControllerLiveOptions) =>
: {}),
...(input.botId && channelRuntime
? {
+ reactToMessage: (request, toolCallId) =>
+ channelRuntime!.react(threadId, input.botId!, request, toolCallId),
channels: {
create: (request) => channelRuntime!.create(input.botId!, request),
update: (request) => channelRuntime!.update(input.botId!, request),
diff --git a/apps/server/src/provider/Services/AgentController.ts b/apps/server/src/provider/Services/AgentController.ts
index d701178d8..7af6a92b4 100644
--- a/apps/server/src/provider/Services/AgentController.ts
+++ b/apps/server/src/provider/Services/AgentController.ts
@@ -18,6 +18,7 @@ import type {
ProviderUploadFeedbackResult,
OrchestrationCommand,
OrchestrationReadModel,
+ OrchestrationThread,
ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
@@ -52,6 +53,7 @@ export interface AgentControllerShape {
}) => Effect.Effect<void>;
readonly configureDelegation?: (input: {
readonly readSnapshot: () => Promise<OrchestrationReadModel>;
+ readonly readThread?: (threadId: ThreadId) => Promise<OrchestrationThread | undefined>;
readonly dispatch: (command: OrchestrationCommand) => Promise<{ readonly sequence: number }>;
}) => Effect.Effect<void>;
readonly failDelegation?: (input: {
diff --git a/apps/web/src/components/chat/MessageReactions.test.tsx b/apps/web/src/components/chat/MessageReactions.test.tsx
new file mode 100644
index 000000000..3d10e1696
--- /dev/null
+++ b/apps/web/src/components/chat/MessageReactions.test.tsx
@@ -0,0 +1,26 @@
+import { renderToStaticMarkup } from "react-dom/server";
+import { BotId } from "@t3tools/contracts";
+import { describe, expect, it } from "vite-plus/test";
+
+import { MessageReactions } from "./MessageReactions";
+
+describe("MessageReactions", () => {
+ it("groups matching emoji reactions and renders their count", () => {
+ const html = renderToStaticMarkup(
+ <MessageReactions
+ reactions={[
+ { botId: BotId.make("bot-1"), emoji: "πŸ‘" },
+ { botId: BotId.make("bot-2"), emoji: "πŸ‘" },
+ { botId: BotId.make("bot-1"), emoji: "πŸŽ‰" },
+ ]}
+ />,
+ );
+
+ expect(html).toContain("πŸ‘ 2");
+ expect(html).toContain("πŸŽ‰");
+ });
+
+ it("renders nothing without reactions", () => {
+ expect(renderToStaticMarkup(<MessageReactions reactions={[]} />)).toBe("");
+ });
+});
diff --git a/apps/web/src/components/chat/MessageReactions.tsx b/apps/web/src/components/chat/MessageReactions.tsx
new file mode 100644
index 000000000..9e500b35f
--- /dev/null
+++ b/apps/web/src/components/chat/MessageReactions.tsx
@@ -0,0 +1,28 @@
+import type { OrchestrationMessageReaction } from "@t3tools/contracts";
+
+export function MessageReactions({
+ reactions,
+}: {
+ readonly reactions: ReadonlyArray<OrchestrationMessageReaction>;
+}) {
+ const counts = new Map<string, number>();
+ for (const reaction of reactions) {
+ counts.set(reaction.emoji, (counts.get(reaction.emoji) ?? 0) + 1);
+ }
+ if (counts.size === 0) return null;
+
+ return (
+ <div className="mt-1 flex flex-wrap gap-1" data-testid="message-reactions">
+ {[...counts].map(([emoji, count]) => (
+ <span
+ key={emoji}
+ className="rounded-full border border-border bg-background px-2 py-0.5 text-xs"
+ data-reaction-emoji={emoji}
+ >
+ {emoji}
+ {count > 1 ? ` ${count}` : ""}
+ </span>
+ ))}
+ </div>
+ );
+}
diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx
index fe91ebb75..7b30fcd88 100644
--- a/apps/web/src/components/chat/MessagesTimeline.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.tsx
@@ -91,6 +91,7 @@ import {
TIMELINE_MINIMAP_MIN_ITEMS,
type TimelineLatestTurn,
} from "./MessagesTimeline.logic";
+import { MessageReactions } from "./MessageReactions";
import { TerminalContextInlineChip } from "./TerminalContextInlineChip";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import {
@@ -1069,6 +1070,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
markdownCwd={ctx.markdownCwd}
/>
</div>
+ <MessageReactions reactions={row.message.reactions ?? []} />
<div className="flex w-full max-w-[80%] items-center justify-end pe-1 text-xs tabular-nums opacity-0 transition-opacity duration-200 focus-within:opacity-100 group-hover:opacity-100">
<div className="flex shrink-0 items-center gap-2">
<Tooltip>
@@ -1156,6 +1158,7 @@ function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "mess
lineBreaks={shouldPreserveAssistantLineBreaks(messageText)}
skills={ctx.skills}
/>
+ <MessageReactions reactions={row.message.reactions ?? []} />
<AssistantChangedFilesSection
turnSummary={row.assistantTurnDiffSummary}
routeThreadKey={ctx.routeThreadKey}
diff --git a/packages/client-runtime/src/state/threadReducer.ts b/packages/client-runtime/src/state/threadReducer.ts
index c23efc3ce..11604f27d 100644
--- a/packages/client-runtime/src/state/threadReducer.ts
+++ b/packages/client-runtime/src/state/threadReducer.ts
@@ -391,6 +391,36 @@ export function applyThreadDetailEvent(
};
}
+ case "thread.message-reaction-set": {
+ const message = thread.messages.find((entry) => entry.id === event.payload.messageId);
+ if (!message) return { kind: "unchanged" };
+ const withoutReaction = (message.reactions ?? []).filter(
+ (reaction) =>
+ reaction.botId !== event.payload.botId || reaction.emoji !== event.payload.emoji,
+ );
+ return {
+ kind: "updated",
+ thread: {
+ ...thread,
+ messages: thread.messages.map((entry) =>
+ entry.id === event.payload.messageId
+ ? {
+ ...entry,
+ reactions: event.payload.present
+ ? [
+ ...withoutReaction,
+ { botId: event.payload.botId, emoji: event.payload.emoji },
+ ]
+ : withoutReaction,
+ updatedAt: event.payload.updatedAt,
+ }
+ : entry,
+ ),
+ updatedAt: event.payload.updatedAt,
+ },
+ };
+ }
+
// ── Session ─────────────────────────────────────────────────────
case "thread.session-set": {
// Leaving the "running" session status is the turn-end signal: settle a
diff --git a/packages/contracts/src/akeruTools.test.ts b/packages/contracts/src/akeruTools.test.ts
index 79dcd8950..d716ad4fa 100644
--- a/packages/contracts/src/akeruTools.test.ts
+++ b/packages/contracts/src/akeruTools.test.ts
@@ -158,6 +158,13 @@ describe("Akeru tool contracts", () => {
).toThrow();
});
+ it("validates message reactions and keeps them approval-gated", () => {
+ const input = { messageId: "message-1", emoji: "πŸ‘", action: "add" as const };
+ expect(decodeAkeruToolInput("ReactToMessage", input)).toEqual(input);
+ expect(() => decodeAkeruToolInput("ReactToMessage", { ...input, action: "toggle" })).toThrow();
+ expect(AKERU_TOOL_CATALOG.find((tool) => tool.id === "ReactToMessage")?.approval).toBe("send");
+ });
+
it("never lets full access bypass protected commands or paths", () => {
const shell = AKERU_TOOL_CATALOG.find((tool) => tool.id === "ExternalShell")!;
const read = AKERU_TOOL_CATALOG.find((tool) => tool.id === "ExternalRead")!;
diff --git a/packages/contracts/src/akeruTools.ts b/packages/contracts/src/akeruTools.ts
index 6da8705e3..8fa5387c6 100644
--- a/packages/contracts/src/akeruTools.ts
+++ b/packages/contracts/src/akeruTools.ts
@@ -6,6 +6,7 @@ import {
BotId,
GroupId,
IsoDateTime,
+ MessageId,
NonNegativeInt,
PositiveInt,
ThreadId,
@@ -73,6 +74,7 @@ export const AkeruToolId = Schema.Literals([
"SendToUser",
"SearchPlugins",
"GetPlugin",
+ "ReactToMessage",
"InstallPlugin",
"UninstallPlugin",
"GetMcpServerStatus",
@@ -149,6 +151,11 @@ export const AkeruToolInputSchemas = {
limit: Schema.optional(PositiveInt.check(Schema.isLessThanOrEqualTo(50))),
}),
GetPlugin: Schema.Struct({ pluginId: TrimmedNonEmptyString }),
+ ReactToMessage: Schema.Struct({
+ messageId: MessageId,
+ emoji: TrimmedNonEmptyString.check(Schema.isMaxLength(32)),
+ action: Schema.Literals(["add", "remove"]),
+ }),
InstallPlugin: Schema.Struct({ pluginId: TrimmedNonEmptyString }),
UninstallPlugin: Schema.Struct({ pluginId: TrimmedNonEmptyString }),
GetMcpServerStatus: McpServerIdInput,
@@ -161,6 +168,22 @@ export const AkeruToolInputSchemas = {
}),
} as const satisfies Record<AkeruToolId, Schema.Top>;
+export const AkeruMessageReactionResult = Schema.Union([
+ Schema.Struct({
+ status: Schema.Literal("applied"),
+ messageId: MessageId,
+ emoji: TrimmedNonEmptyString,
+ action: Schema.Literals(["add", "remove"]),
+ changed: Schema.Boolean,
+ }),
+ Schema.Struct({
+ status: Schema.Literal("unsupported"),
+ messageId: MessageId,
+ reason: Schema.Literal("channel-does-not-support-reactions"),
+ }),
+]);
+export type AkeruMessageReactionResult = typeof AkeruMessageReactionResult.Type;
+
const AkeruToolInputDecoders = Object.fromEntries(
Object.entries(AkeruToolInputSchemas).map(([toolId, schema]) => [
toolId,
@@ -298,6 +321,12 @@ export const AKERU_TOOL_CATALOG = [
"bot-workspace",
"Inspect a plugin, its connection, permissions, health, and dependents.",
),
+ define(
+ "ReactToMessage",
+ "bot-workspace",
+ "Add or remove an emoji reaction on a visible message.",
+ { approval: "send" },
+ ),
define("InstallPlugin", "bot-workspace", "Install a curated plugin after inspecting it.", {
approval: "production",
}),
diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts
index 1ace69be3..3f2e300af 100644
--- a/packages/contracts/src/orchestration.ts
+++ b/packages/contracts/src/orchestration.ts
@@ -377,6 +377,12 @@ export type OrchestrationGroup = typeof OrchestrationGroup.Type;
export const OrchestrationMessageRole = Schema.Literals(["user", "assistant", "system"]);
export type OrchestrationMessageRole = typeof OrchestrationMessageRole.Type;
+export const OrchestrationMessageReaction = Schema.Struct({
+ emoji: TrimmedNonEmptyString,
+ botId: BotId,
+});
+export type OrchestrationMessageReaction = typeof OrchestrationMessageReaction.Type;
+
export const OrchestrationMessage = Schema.Struct({
id: MessageId,
role: OrchestrationMessageRole,
@@ -384,6 +390,7 @@ export const OrchestrationMessage = Schema.Struct({
attachments: Schema.optional(Schema.Array(ChatAttachment)),
turnId: Schema.NullOr(TurnId),
respondingBotId: Schema.optional(Schema.NullOr(BotId)),
+ reactions: Schema.optional(Schema.Array(OrchestrationMessageReaction)),
streaming: Schema.Boolean,
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
@@ -1418,6 +1425,17 @@ const ThreadMessageAssistantCompleteCommand = Schema.Struct({
createdAt: IsoDateTime,
});
+const ThreadMessageReactionSetCommand = Schema.Struct({
+ type: Schema.Literal("thread.message.reaction.set"),
+ commandId: CommandId,
+ threadId: ThreadId,
+ messageId: MessageId,
+ botId: BotId,
+ emoji: TrimmedNonEmptyString,
+ present: Schema.Boolean,
+ updatedAt: IsoDateTime,
+});
+
const ThreadProposedPlanUpsertCommand = Schema.Struct({
type: Schema.Literal("thread.proposed-plan.upsert"),
commandId: CommandId,
@@ -1497,6 +1515,7 @@ const InternalOrchestrationCommand = Schema.Union([
ThreadSessionSetCommand,
ThreadMessageAssistantDeltaCommand,
ThreadMessageAssistantCompleteCommand,
+ ThreadMessageReactionSetCommand,
ThreadProposedPlanUpsertCommand,
ThreadTurnDiffCompleteCommand,
ThreadActivityAppendCommand,
@@ -1548,6 +1567,7 @@ export const OrchestrationEventType = Schema.Literals([
"thread.runtime-mode-set",
"thread.interaction-mode-set",
"thread.message-sent",
+ "thread.message-reaction-set",
"thread.turn-start-requested",
"thread.turn-interrupt-requested",
"thread.approval-response-requested",
@@ -1843,6 +1863,15 @@ export const ThreadMessageSentPayload = Schema.Struct({
updatedAt: IsoDateTime,
});
+export const ThreadMessageReactionSetPayload = Schema.Struct({
+ threadId: ThreadId,
+ messageId: MessageId,
+ botId: BotId,
+ emoji: TrimmedNonEmptyString,
+ present: Schema.Boolean,
+ updatedAt: IsoDateTime,
+});
+
export const ThreadTurnStartRequestedPayload = Schema.Struct({
threadId: ThreadId,
messageId: MessageId,
@@ -2132,6 +2161,11 @@ export const OrchestrationEvent = Schema.Union([
type: Schema.Literal("thread.message-sent"),
payload: ThreadMessageSentPayload,
}),
+ Schema.Struct({
+ ...EventBaseFields,
+ type: Schema.Literal("thread.message-reaction-set"),
+ payload: ThreadMessageReactionSetPayload,
+ }),
Schema.Struct({
...EventBaseFields,
type: Schema.Literal("thread.turn-start-requested"),