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(channels): connect external conversations to bots (#190)

Leo763182238011
diff --git a/apps/mobile/src/features/threads/ThreadChannels.test.tsx b/apps/mobile/src/features/threads/ThreadChannels.test.tsx
new file mode 100644
index 000000000..146e88701
--- /dev/null
+++ b/apps/mobile/src/features/threads/ThreadChannels.test.tsx
@@ -0,0 +1,75 @@
+import { BotId, EnvironmentId, MessageId, ProjectId } from "@t3tools/contracts";
+import type { ChannelBinding } from "@t3tools/contracts";
+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
+
+const state = vi.hoisted(() => ({ snapshot: undefined as unknown }));
+vi.mock("@effect/atom-react", () => ({ useAtomValue: () => state.snapshot }));
+vi.mock("../../state/shell", () => ({ environmentSnapshotAtom: (id: string) => id }));
+vi.mock("react-native", () => ({ Text: "span", View: "div" }));
+
+import { ThreadChannels } from "./ThreadChannels";
+
+const botId = BotId.make("bot-1");
+const projectId = ProjectId.make("project-1");
+const environmentId = EnvironmentId.make("environment-1");
+const binding: ChannelBinding = {
+ botId,
+ projectId,
+ provider: "telegram",
+ status: "connected",
+ externalIdentity: "private-identity",
+ connectedAt: null,
+ lastError: "private-credential-error",
+ sentMessageIds: [MessageId.make("message-1")],
+};
+
+function render(bot = botId) {
+ const tree = ThreadChannels({ environmentId, botId: bot });
+ return tree === null ? "" : JSON.stringify(tree);
+}
+
+describe("mobile thread channels", () => {
+ beforeEach(() => {
+ state.snapshot = {
+ bots: [{ id: botId, channelBindings: [binding] }],
+ projects: [{ id: projectId, title: "Selected workspace" }],
+ };
+ });
+
+ it("renders read-only health, selected project, and confirmed delivery from the snapshot", () => {
+ const html = render();
+ expect(html).toContain("Telegram");
+ expect(html).toContain("Connected");
+ expect(html).toContain("Selected workspace");
+ expect(html).toContain("1 confirmed delivery");
+ expect(html).not.toContain("private-");
+ expect(html).not.toContain("button");
+ expect(html).not.toContain("input");
+ });
+
+ it("renders changed health and missing project without using another project", () => {
+ state.snapshot = {
+ bots: [
+ { id: botId, channelBindings: [{ ...binding, status: "failed", sentMessageIds: [] }] },
+ ],
+ projects: [{ id: "other-project", title: "Wrong workspace" }],
+ };
+ const html = render();
+ expect(html).toContain("Connection failed");
+ expect(html).toContain("Project unavailable");
+ expect(html).toContain("No confirmed deliveries");
+ expect(html).not.toContain("Wrong workspace");
+ expect(html).not.toContain("private-credential-error");
+ });
+
+ it("does not show another bot's channels", () => {
+ expect(render(BotId.make("other-bot"))).toBe("");
+ });
+
+ it("renders nothing before the snapshot loads or after detach", () => {
+ state.snapshot = undefined;
+ expect(render()).toBe("");
+ state.snapshot = { bots: [{ id: botId, channelBindings: [] }], projects: [] };
+ expect(render()).toBe("");
+ });
+});
diff --git a/apps/mobile/src/features/threads/ThreadChannels.tsx b/apps/mobile/src/features/threads/ThreadChannels.tsx
new file mode 100644
index 000000000..61b2c5cc3
--- /dev/null
+++ b/apps/mobile/src/features/threads/ThreadChannels.tsx
@@ -0,0 +1,42 @@
+import { useAtomValue } from "@effect/atom-react";
+import { channelBindingPresentation } from "@t3tools/client-runtime/channel-presentation";
+import type { BotId, EnvironmentId } from "@t3tools/contracts";
+import { Text, View } from "react-native";
+
+import { environmentSnapshotAtom } from "../../state/shell";
+
+export function ThreadChannels(props: {
+ readonly environmentId: EnvironmentId;
+ readonly botId: BotId | null;
+}) {
+ const snapshot = useAtomValue(environmentSnapshotAtom(props.environmentId));
+ const bot = snapshot?.bots.find((candidate) => candidate.id === props.botId);
+ if (!bot?.channelBindings.length) return null;
+
+ return (
+ <View className="mb-3 gap-2" accessibilityLabel="Channels">
+ <Text className="font-t3-medium text-sm text-neutral-900 dark:text-neutral-100">
+ Channels
+ </Text>
+ {bot.channelBindings.map((binding, index) => {
+ const channel = channelBindingPresentation(binding, snapshot?.projects ?? []);
+ return (
+ <View key={binding.connectionId ?? `${binding.provider}:${index}`} className="gap-1">
+ <Text className="font-t3-medium text-xs text-neutral-900 dark:text-neutral-100">
+ {channel.provider} · {channel.health}
+ </Text>
+ {channel.warning ? (
+ <Text className="text-xs text-amber-700 dark:text-amber-400">{channel.warning}</Text>
+ ) : null}
+ <Text className="text-xs text-neutral-600 dark:text-neutral-300">
+ Project · {channel.project}
+ </Text>
+ <Text className="text-xs text-neutral-600 dark:text-neutral-300">
+ Recent delivery · {channel.delivery}
+ </Text>
+ </View>
+ );
+ })}
+ </View>
+ );
+}
diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
index ee02fd0c5..80c82e71a 100644
--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
@@ -610,6 +610,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
key={props.selectedThread.id}
environmentId={props.environmentId}
threadId={props.selectedThread.id}
+ botId={props.selectedThread.botId ?? null}
workspaceRoot={props.threadCwd}
feed={props.selectedThreadFeed}
contentPresentation={props.contentPresentation}
diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx
index 3ec6ddd70..198a5c159 100644
--- a/apps/mobile/src/features/threads/ThreadFeed.tsx
+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx
@@ -1,7 +1,8 @@
import * as Haptics from "expo-haptics";
import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
import { type LegendListRef } from "@legendapp/list/react-native";
-import type { EnvironmentId, MessageId, ThreadId, TurnId } from "@t3tools/contracts";
+import type { BotId, EnvironmentId, MessageId, ThreadId, TurnId } from "@t3tools/contracts";
+import { channelOriginLabel } from "@t3tools/client-runtime/channel-presentation";
import { classifyMarkdownImageSource } from "@t3tools/client-runtime/markdown-images";
import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
@@ -98,6 +99,7 @@ import {
type ThreadFeedLatestTurn,
} from "../../lib/threadActivity";
import type { ThreadContentPresentation } from "./threadContentPresentation";
+import { ThreadChannels } from "./ThreadChannels";
import {
resolveThreadFeedLiveFollow,
type ThreadFeedLiveFollowEvent,
@@ -153,6 +155,7 @@ function isFreshTimestamp(input: string): boolean {
export interface ThreadFeedProps {
readonly environmentId: EnvironmentId;
readonly threadId: ThreadId;
+ readonly botId: BotId | null;
readonly workspaceRoot?: string | null;
readonly feed: ReadonlyArray<ThreadFeedEntry>;
readonly contentPresentation: ThreadContentPresentation;
@@ -1118,6 +1121,11 @@ function renderFeedEntry(
: null),
}}
>
+ {message.channelOrigin ? (
+ <NativeText className="font-t3-medium text-[11px] text-neutral-600 dark:text-neutral-300">
+ {channelOriginLabel(message.channelOrigin, message.authorDisplayName)}
+ </NativeText>
+ ) : null}
{message.text.trim().length > 0 ? (
<UserMessageContent
text={message.text}
@@ -2283,6 +2291,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
ListHeaderComponent={
<>
{usesNativeAutomaticInsets ? null : <View style={{ height: topContentInset }} />}
+ <ThreadChannels environmentId={props.environmentId} botId={props.botId} />
{props.loadEarlier != null ? (
<Pressable
onPress={props.loadEarlier.onLoadEarlier}
diff --git a/apps/server/package.json b/apps/server/package.json
index 3fe3db930..f4e01f175 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -26,6 +26,8 @@
"@ai-sdk/openai": "3.0.101",
"@ai-sdk/openai-compatible": "2.0.72",
"@anthropic-ai/claude-agent-sdk": "^0.3.170",
+ "@chat-adapter/discord": "4.39.0",
+ "@chat-adapter/slack": "4.39.0",
"@chat-adapter/state-memory": "4.39.0",
"@chat-adapter/whatsapp": "4.39.0",
"@composio/core": "0.18.0",
diff --git a/apps/server/src/channels/ChannelCommand.ts b/apps/server/src/channels/ChannelCommand.ts
index dd944e60a..5551d9661 100644
--- a/apps/server/src/channels/ChannelCommand.ts
+++ b/apps/server/src/channels/ChannelCommand.ts
@@ -4,6 +4,7 @@ import {
connectChannel,
attachChannelConnection,
deleteChannelConnection,
+ detachChannelConnection,
disconnectChannel,
reconnectChannel,
saveChannelConnection,
@@ -36,12 +37,15 @@ export async function executeChannelCommand(
dependencies,
command.botId,
command.connectionId,
+ command.projectId,
command.provider,
)
: command.type === "channel.disconnect"
? await disconnectChannel(dependencies, command.botId, command.provider)
- : command.type === "channel.reconnect"
- ? await reconnectChannel(dependencies, command.botId, command.provider)
- : await sendChannelMessage(dependencies, command);
+ : command.type === "channel.detach"
+ ? await detachChannelConnection(dependencies, command.botId, command.provider)
+ : command.type === "channel.reconnect"
+ ? await reconnectChannel(dependencies, command.botId, command.provider)
+ : await sendChannelMessage(dependencies, command);
return { sequence };
}
diff --git a/apps/server/src/channels/ChannelDeliveryStore.test.ts b/apps/server/src/channels/ChannelDeliveryStore.test.ts
index e1722505a..ea75c8778 100644
--- a/apps/server/src/channels/ChannelDeliveryStore.test.ts
+++ b/apps/server/src/channels/ChannelDeliveryStore.test.ts
@@ -6,7 +6,10 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";
import { runMigrations } from "../persistence/Migrations.ts";
import * as NodeSqliteClient from "../persistence/NodeSqliteClient.ts";
-import { makeChannelDeliveryStore } from "./ChannelDeliveryStore.ts";
+import {
+ makeChannelDeliveryStore,
+ makeMemoryChannelDeliveryStore,
+} from "./ChannelDeliveryStore.ts";
const TestLayer = Layer.mergeAll(NodeSqliteClient.layerMemory());
@@ -44,6 +47,50 @@ it.layer(TestLayer)("channel delivery store", (it) => {
}),
);
+ it.effect("retains unfinished claims across store reconstruction until sent repair", () =>
+ Effect.gen(function* () {
+ yield* runMigrations();
+ const store = yield* makeChannelDeliveryStore;
+ const claim = {
+ messageId: MessageId.make("message-ambiguous"),
+ botId: BotId.make("bot-1"),
+ threadId: ThreadId.make("thread-1"),
+ provider: "telegram" as const,
+ externalThreadId: "chat-1",
+ requestedAt: "2026-08-27T20:00:00.000Z",
+ };
+ assert.equal(yield* store.claim(claim), "claimed");
+ const restored = yield* makeChannelDeliveryStore;
+ assert.equal(yield* restored.claim(claim), "requested");
+ yield* restored.markSent({ messageId: claim.messageId, sentAt: claim.requestedAt });
+ assert.equal(yield* restored.claim(claim), "sent");
+ }),
+ );
+
+ it.effect("keeps memory and SQL release and repair semantics equal", () =>
+ Effect.gen(function* () {
+ yield* runMigrations();
+ const sqlStore = yield* makeChannelDeliveryStore;
+ for (const store of [sqlStore, makeMemoryChannelDeliveryStore()]) {
+ const claim = {
+ messageId: MessageId.make("message-store-parity"),
+ botId: BotId.make("bot-1"),
+ threadId: ThreadId.make("thread-1"),
+ provider: "telegram" as const,
+ externalThreadId: "chat-1",
+ requestedAt: "2026-08-27T20:00:00.000Z",
+ };
+ yield* store.markSent({ messageId: claim.messageId, sentAt: claim.requestedAt });
+ assert.equal(yield* store.claim(claim), "claimed");
+ yield* store.releaseRequested(claim.messageId);
+ assert.equal(yield* store.claim(claim), "claimed");
+ yield* store.markSent({ messageId: claim.messageId, sentAt: claim.requestedAt });
+ yield* store.releaseRequested(claim.messageId);
+ assert.equal(yield* store.claim(claim), "sent");
+ }
+ }),
+ );
+
it.effect("releases only requested deliveries", () =>
Effect.gen(function* () {
yield* runMigrations();
diff --git a/apps/server/src/channels/ChannelDeliveryStore.ts b/apps/server/src/channels/ChannelDeliveryStore.ts
index 32c3ecec5..0a1f1e545 100644
--- a/apps/server/src/channels/ChannelDeliveryStore.ts
+++ b/apps/server/src/channels/ChannelDeliveryStore.ts
@@ -22,6 +22,7 @@ export interface ChannelDeliveryStoreShape {
readonly claim: (
input: ChannelDeliveryClaim,
) => Effect.Effect<ChannelDeliveryClaimResult, ProjectionRepositoryError>;
+ /** Release only before transport starts or after confirmed non-delivery. */
readonly releaseRequested: (
messageId: MessageId,
) => Effect.Effect<void, ProjectionRepositoryError>;
@@ -91,7 +92,13 @@ export function makeMemoryChannelDeliveryStore(): ChannelDeliveryStoreShape {
status.set(input.messageId, "requested");
return "claimed";
}),
- releaseRequested: (messageId) => Effect.sync(() => void status.delete(messageId)),
- markSent: ({ messageId }) => Effect.sync(() => void status.set(messageId, "sent")),
+ releaseRequested: (messageId) =>
+ Effect.sync(() => {
+ if (status.get(messageId) === "requested") status.delete(messageId);
+ }),
+ markSent: ({ messageId }) =>
+ Effect.sync(() => {
+ if (status.has(messageId)) status.set(messageId, "sent");
+ }),
};
}
diff --git a/apps/server/src/channels/ChannelInboundRestart.test.ts b/apps/server/src/channels/ChannelInboundRestart.test.ts
new file mode 100644
index 000000000..aeb869f4b
--- /dev/null
+++ b/apps/server/src/channels/ChannelInboundRestart.test.ts
@@ -0,0 +1,290 @@
+import * as NodeCrypto from "node:crypto";
+
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import {
+ BotId,
+ CHANNEL_PROVIDERS,
+ CommandId,
+ DEFAULT_SERVER_SETTINGS,
+ ProjectId,
+ ProviderInstanceId,
+} from "@t3tools/contracts";
+import { it } from "@effect/vitest";
+import * as Cause from "effect/Cause";
+import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
+import * as Path from "effect/Path";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+import * as Queue from "effect/Queue";
+import * as Stream from "effect/Stream";
+import { describe, expect } from "vite-plus/test";
+
+import { ServerConfig } from "../config.ts";
+import { OrchestrationEngineLive } from "../orchestration/Layers/OrchestrationEngine.ts";
+import { OrchestrationProjectionPipelineLive } from "../orchestration/Layers/ProjectionPipeline.ts";
+import { OrchestrationProjectionSnapshotQueryLive } from "../orchestration/Layers/ProjectionSnapshotQuery.ts";
+import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts";
+import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts";
+import * as ThreadBackgroundLiveness from "../orchestration/ThreadBackgroundLiveness.ts";
+import * as ThreadPlanProgress from "../orchestration/ThreadPlanProgress.ts";
+import { OrchestrationCommandReceiptRepositoryLive } from "../persistence/Layers/OrchestrationCommandReceipts.ts";
+import { OrchestrationEventStoreLive } from "../persistence/Layers/OrchestrationEventStore.ts";
+import { makeSqlitePersistenceLive } from "../persistence/Layers/Sqlite.ts";
+import { OrchestrationCommandReceiptRepository } from "../persistence/Services/OrchestrationCommandReceipts.ts";
+import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
+import { makeMemoryChannelDeliveryStore } from "./ChannelDeliveryStore.ts";
+import {
+ dispatchInboundChannelMessage,
+ shutdownAllChannels,
+ type ChannelRuntimeDependencies,
+} from "./ChannelRuntime.ts";
+
+const NOW = "2026-09-04T12:00:00.000Z";
+const LATER = "2026-09-04T13:00:00.000Z";
+const BOT_ID = BotId.make("inbound-restart-bot");
+const FIRST_PROJECT_ID = ProjectId.make("first-project");
+const TARGET_PROJECT_ID = ProjectId.make("selected-project");
+
+function makeLayer(dbPath: string) {
+ return OrchestrationEngineLive.pipe(
+ Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),
+ Layer.provide(OrchestrationProjectionPipelineLive),
+ Layer.provide(ThreadBackgroundLiveness.layer),
+ Layer.provide(ThreadPlanProgress.layer),
+ Layer.provide(OrchestrationEventStoreLive),
+ Layer.provideMerge(OrchestrationCommandReceiptRepositoryLive),
+ Layer.provide(RepositoryIdentityResolver.layer),
+ Layer.provide(makeSqlitePersistenceLive(dbPath)),
+ Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "akeru-inbound-restart-" })),
+ Layer.provideMerge(NodeServices.layer),
+ );
+}
+
+const makeDependencies = Effect.fn("makeDependencies")(function* (now: string) {
+ const engine = yield* OrchestrationEngineService;
+ const snapshots = yield* ProjectionSnapshotQuery;
+ const queries = yield* Queue.unbounded<Effect.Effect<void>>();
+ yield* Queue.take(queries).pipe(Effect.flatten, Effect.forever, Effect.forkScoped);
+
+ // Promise callbacks submit projection reads to the scoped test worker.
+ const readAsPromise = <A, E>(query: Effect.Effect<A, E>): Promise<A> =>
+ new Promise((resolve, reject) => {
+ Queue.offerUnsafe(
+ queries,
+ query.pipe(
+ Effect.matchCause({
+ onSuccess: resolve,
+ onFailure: (cause) => reject(Cause.squash(cause)),
+ }),
+ ),
+ );
+ });
+
+ return {
+ engine,
+ readModel: () => readAsPromise(snapshots.getCommandReadModel()),
+ readThread: (threadId) =>
+ readAsPromise(snapshots.getThreadDetailById(threadId).pipe(Effect.map(Option.getOrNull))),
+ nowIso: async () => now,
+ randomUuid: async () => NodeCrypto.randomUUID(),
+ deliveryStore: makeMemoryChannelDeliveryStore(),
+ secretStore: {
+ get: () => Effect.die("Inbound dispatch must not read secrets."),
+ set: () => Effect.die("Inbound dispatch must not write secrets."),
+ create: () => Effect.die("Inbound dispatch must not create secrets."),
+ getOrCreateRandom: () => Effect.die("Inbound dispatch must not create secrets."),
+ remove: () => Effect.die("Inbound dispatch must not remove secrets."),
+ },
+ settings: {
+ getSettings: Effect.succeed(DEFAULT_SERVER_SETTINGS),
+ updateSettings: () => Effect.die("Inbound dispatch must not change settings."),
+ },
+ } satisfies ChannelRuntimeDependencies;
+});
+
+const seedProjectsAndBot = Effect.fn("seedProjectsAndBot")(function* (root: string) {
+ const engine = yield* OrchestrationEngineService;
+ const path = yield* Path.Path;
+ for (const projectId of [FIRST_PROJECT_ID, TARGET_PROJECT_ID]) {
+ yield* engine.dispatch({
+ type: "project.create",
+ commandId: CommandId.make(`create-${projectId}`),
+ projectId,
+ title: projectId,
+ workspaceRoot: path.join(root, projectId),
+ defaultModelSelection: {
+ instanceId: ProviderInstanceId.make("codex"),
+ model: "gpt-5.6",
+ },
+ createdAt: NOW,
+ });
+ }
+ yield* engine.dispatch({
+ type: "bot.create",
+ commandId: CommandId.make("create-inbound-bot"),
+ botId: BOT_ID,
+ name: "Scout",
+ title: "Agent",
+ avatar: { kind: "dither", seed: "scout" },
+ engine: null,
+ sandbox: "local",
+ runtimeMode: "full-access",
+ usageCap: null,
+ groupId: null,
+ createdAt: NOW,
+ });
+});
+
+const readReceipt = Effect.fn("readReceipt")(function* (commandId: CommandId) {
+ const receipts = yield* OrchestrationCommandReceiptRepository;
+ return Option.getOrThrow(yield* receipts.getByCommandId({ commandId }));
+});
+
+describe("channel inbound persistence across restart", () => {
+ for (const provider of CHANNEL_PROVIDERS) {
+ it.effect(
+ `${provider} suppresses redelivery after reconstruction and accepts distinct messages in the selected project`,
+ () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "akeru-channel-inbound-" });
+ const dbPath = path.join(root, "state.sqlite");
+ yield* Effect.addFinalizer(() => Effect.promise(shutdownAllChannels));
+ const input = {
+ botId: BOT_ID,
+ projectId: TARGET_PROJECT_ID,
+ provider,
+ externalThreadId: "external-conversation",
+ externalMessageId: "external-message-1",
+ externalSenderId: "sender-1",
+ externalSenderName: "External sender",
+ text: "Work in the selected project",
+ };
+
+ const original = yield* Effect.gen(function* () {
+ const before = yield* makeDependencies(NOW);
+ yield* seedProjectsAndBot(root);
+ yield* Effect.promise(() => dispatchInboundChannelMessage(before, input));
+
+ const originalEvents = yield* Stream.runCollect(before.engine.readEvents(0));
+ const originalTurns = originalEvents.filter(
+ (event) => event.type === "thread.turn-start-requested",
+ );
+ expect(originalTurns).toHaveLength(1);
+ const originalTurn = originalTurns[0]!;
+ const commandId = originalTurn.commandId!;
+ const threadId = originalTurn.payload.threadId;
+ const originalReceipt = yield* readReceipt(commandId);
+ expect(originalReceipt).toMatchObject({
+ status: "accepted",
+ aggregateKind: "thread",
+ aggregateId: threadId,
+ });
+ const originalThread = yield* Effect.promise(() => before.readThread(threadId));
+ expect(originalThread).toMatchObject({ projectId: TARGET_PROJECT_ID, botId: BOT_ID });
+ expect(
+ originalThread?.messages.filter((message) => message.role === "user"),
+ ).toHaveLength(1);
+ const expectedOrigin = {
+ provider,
+ externalThreadId: input.externalThreadId,
+ externalMessageId: input.externalMessageId,
+ externalSenderId: input.externalSenderId,
+ };
+ expect(originalThread?.messages[0]).toMatchObject({
+ channelOrigin: expectedOrigin,
+ authorDisplayName: input.externalSenderName,
+ });
+ const snapshots = yield* ProjectionSnapshotQuery;
+ const fullSnapshot = yield* snapshots.getSnapshot();
+ expect(
+ fullSnapshot.threads.find((entry) => entry.id === threadId)?.messages[0],
+ ).toMatchObject({
+ channelOrigin: expectedOrigin,
+ authorDisplayName: input.externalSenderName,
+ });
+ const windowed = Option.getOrThrow(
+ yield* snapshots.getThreadDetailSnapshot(threadId, { turnLimit: 1 }),
+ );
+ expect(windowed.thread.messages[0]).toMatchObject({
+ channelOrigin: expectedOrigin,
+ authorDisplayName: input.externalSenderName,
+ });
+ const originalSequence = yield* before.engine.latestSequence;
+ yield* Effect.promise(shutdownAllChannels);
+ return {
+ before,
+ commandId,
+ threadId,
+ originalReceipt,
+ originalThread,
+ originalEvents,
+ originalSequence,
+ };
+ }).pipe(Effect.provide(makeLayer(dbPath)), Effect.scoped);
+
+ // The first scope closes its SQLite connection before the second layer opens it.
+ yield* Effect.gen(function* () {
+ const {
+ before,
+ commandId,
+ threadId,
+ originalReceipt,
+ originalThread,
+ originalEvents,
+ originalSequence,
+ } = original;
+ const after = yield* makeDependencies(LATER);
+ expect(after.engine).not.toBe(before.engine);
+ expect(after.deliveryStore).not.toBe(before.deliveryStore);
+ expect(yield* readReceipt(commandId)).toEqual(originalReceipt);
+ expect(yield* Effect.promise(() => after.readThread(threadId))).toEqual(originalThread);
+
+ yield* Effect.promise(() => dispatchInboundChannelMessage(after, input));
+
+ expect(yield* after.engine.latestSequence).toBe(originalSequence);
+ expect(yield* readReceipt(commandId)).toEqual(originalReceipt);
+ expect(yield* Stream.runCollect(after.engine.readEvents(0))).toEqual(originalEvents);
+ expect(yield* Effect.promise(() => after.readThread(threadId))).toEqual(originalThread);
+
+ yield* Effect.promise(() =>
+ dispatchInboundChannelMessage(after, {
+ ...input,
+ externalMessageId: "external-message-2",
+ }),
+ );
+
+ const events = yield* Stream.runCollect(after.engine.readEvents(0));
+ const turns = events.filter((event) => event.type === "thread.turn-start-requested");
+ expect(turns).toHaveLength(2);
+ expect(new Set(turns.map((event) => event.commandId)).size).toBe(2);
+ expect(turns.map((event) => event.payload.threadId)).toEqual([threadId, threadId]);
+ const messageEvents = events
+ .filter((event) => event.type === "thread.message-sent")
+ .filter((event) => event.payload.role === "user");
+ expect(messageEvents).toHaveLength(2);
+ expect(
+ messageEvents.map((event) => event.payload.channelOrigin?.externalMessageId),
+ ).toEqual([input.externalMessageId, "external-message-2"]);
+ const thread = yield* Effect.promise(() => after.readThread(threadId));
+ expect(thread).toMatchObject({ projectId: TARGET_PROJECT_ID, botId: BOT_ID });
+ const messages = thread?.messages.filter((message) => message.role === "user") ?? [];
+ expect(messages.map((message) => message.id)).toEqual(
+ messageEvents.map((event) => event.payload.messageId),
+ );
+ expect(messages.map((message) => message.text)).toEqual([input.text, input.text]);
+ expect(new Set(messages.map((message) => message.id)).size).toBe(2);
+ expect(
+ (yield* Effect.promise(after.readModel)).threads.map((entry) => entry.projectId),
+ ).toEqual([TARGET_PROJECT_ID]);
+ expect(yield* readReceipt(turns[1]!.commandId!)).toMatchObject({
+ status: "accepted",
+ aggregateId: threadId,
+ });
+ }).pipe(Effect.provide(makeLayer(dbPath)), Effect.scoped);
+ }).pipe(Effect.provide(NodeServices.layer)),
+ );
+ }
+});
diff --git a/apps/server/src/channels/ChannelRuntime.test.ts b/apps/server/src/channels/ChannelRuntime.test.ts
index 48322073a..2254a80ab 100644
--- a/apps/server/src/channels/ChannelRuntime.test.ts
+++ b/apps/server/src/channels/ChannelRuntime.test.ts
@@ -19,7 +19,13 @@ import {
type OrchestrationThread,
} from "@t3tools/contracts";
import type { iMessageAdapter } from "@photon-ai/chat-adapter-imessage";
-import { Message as ChatMessage, parseMarkdown, type Adapter, type ChatInstance } from "chat";
+import {
+ Message as ChatMessage,
+ parseMarkdown,
+ type Adapter,
+ type ChatInstance,
+ type Thread,
+} from "chat";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Stream from "effect/Stream";
@@ -33,6 +39,31 @@ const photon = vi.hoisted(() => ({
subscriptionAttempts: [] as string[],
}));
+const externalAdapters = vi.hoisted(() => ({
+ slackAdapter: null as Adapter | null,
+ slackChat: null as ChatInstance | null,
+ slackDisconnects: 0,
+ slackIdentityAvailable: true,
+ slackInitializationFails: false,
+ slackSubscriptions: [] as string[],
+ slackRestoredBeforeInitialize: false,
+ slackResponses: [] as Array<
+ { status: number; data: unknown; headers?: Record<string, string> } | Error
+ >,
+ slackPostRequests: 0,
+ slackRetryOptions: {} as {
+ retries?: number | undefined;
+ rejectRateLimitedCalls?: boolean | undefined;
+ },
+ discordAdapter: null as Adapter | null,
+ discordChat: null as ChatInstance | null,
+ discordGatewayStarts: 0,
+ discordIdentityFails: false,
+ discordDisconnects: 0,
+ discordSubscriptions: [] as string[],
+ reactions: [] as string[],
+}));
+
vi.mock("@photon-ai/chat-adapter-imessage", async (importOriginal) => {
const actual = await importOriginal<typeof import("@photon-ai/chat-adapter-imessage")>();
return {
@@ -45,7 +76,15 @@ vi.mock("@photon-ai/chat-adapter-imessage", async (importOriginal) => {
photon.adapter = adapter;
photon.chat = chat;
};
- adapter.startGatewayListener = async () => new Response(null, { status: 200 });
+ adapter.startGatewayListener = async ({ waitUntil }, _durationMs, signal) => {
+ waitUntil?.(
+ new Promise<void>((resolve) => {
+ if (signal?.aborted) return resolve();
+ signal?.addEventListener("abort", () => resolve(), { once: true });
+ }),
+ );
+ return new Response(null, { status: 200 });
+ };
adapter.onThreadSubscribe = async (threadId) => {
photon.subscriptionAttempts.push(threadId);
if (threadId === photon.failedSubscription) throw new Error("invalid group GUID");
@@ -56,25 +95,136 @@ vi.mock("@photon-ai/chat-adapter-imessage", async (importOriginal) => {
};
});
+vi.mock("@chat-adapter/slack", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@chat-adapter/slack")>();
+ return {
+ ...actual,
+ createSlackAdapter: (options: Parameters<typeof actual.createSlackAdapter>[0] = {}) => {
+ externalAdapters.slackRetryOptions = {
+ retries: options.webClientOptions?.retryConfig?.retries,
+ rejectRateLimitedCalls: options.webClientOptions?.rejectRateLimitedCalls,
+ };
+ const adapter = actual.createSlackAdapter({
+ ...options,
+ webClientOptions: {
+ ...options.webClientOptions,
+ adapter: async (config) => {
+ if (config.url !== "https://slack.com/api/chat.postMessage") {
+ throw new Error("Unexpected Slack API request");
+ }
+ externalAdapters.slackPostRequests += 1;
+ const response = externalAdapters.slackResponses.shift();
+ if (response instanceof Error) throw response;
+ if (!response) throw new Error("Missing Slack API response");
+ return {
+ ...response,
+ headers: response.headers ?? {},
+ statusText: "",
+ config,
+ request: { path: "/api/chat.postMessage" },
+ };
+ },
+ },
+ }) as ReturnType<typeof actual.createSlackAdapter> & Adapter;
+ adapter.initialize = async (chat) => {
+ if (externalAdapters.slackIdentityAvailable) {
+ Object.assign(adapter, { _botUserId: "U-AKERU" });
+ }
+ externalAdapters.slackAdapter = adapter;
+ externalAdapters.slackChat = chat;
+ externalAdapters.slackRestoredBeforeInitialize = await chat
+ .getState()
+ .isSubscribed("slack:C1:1");
+ if (externalAdapters.slackInitializationFails) throw new Error("Socket startup failed");
+ };
+ adapter.addReaction = async (threadId, messageId, emoji) => {
+ externalAdapters.reactions.push(`add:${threadId}:${messageId}:${String(emoji)}`);
+ };
+ adapter.removeReaction = async (threadId, messageId, emoji) => {
+ externalAdapters.reactions.push(`remove:${threadId}:${messageId}:${String(emoji)}`);
+ };
+ adapter.onThreadSubscribe = async (threadId) => {
+ externalAdapters.slackSubscriptions.push(threadId);
+ };
+ adapter.disconnect = async () => {
+ externalAdapters.slackDisconnects += 1;
+ };
+ return adapter;
+ },
+ };
+});
+
+vi.mock("@chat-adapter/discord", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@chat-adapter/discord")>();
+ return {
+ ...actual,
+ createDiscordAdapter: (options: Parameters<typeof actual.createDiscordAdapter>[0]) => {
+ const adapter = actual.createDiscordAdapter(options) as ReturnType<
+ typeof actual.createDiscordAdapter
+ > &
+ Adapter;
+ adapter.initialize = async (chat) => {
+ externalAdapters.discordAdapter = adapter;
+ externalAdapters.discordChat = chat;
+ };
+ adapter.getUser = async (userId) => {
+ if (externalAdapters.discordIdentityFails) throw new Error("Discord identity failed");
+ return { userId, userName: "akeru-discord", fullName: "Akeru Discord", isBot: true };
+ };
+ adapter.disconnect = async () => {
+ externalAdapters.discordDisconnects += 1;
+ };
+ adapter.addReaction = async (threadId, messageId, emoji) => {
+ externalAdapters.reactions.push(`add:${threadId}:${messageId}:${String(emoji)}`);
+ };
+ adapter.removeReaction = async (threadId, messageId, emoji) => {
+ externalAdapters.reactions.push(`remove:${threadId}:${messageId}:${String(emoji)}`);
+ };
+ adapter.onThreadSubscribe = async (threadId) => {
+ externalAdapters.discordSubscriptions.push(threadId);
+ };
+ adapter.startGatewayListener = async ({ waitUntil }, _durationMs, signal) => {
+ externalAdapters.discordGatewayStarts += 1;
+ waitUntil?.(
+ new Promise<void>((resolve) => {
+ if (signal?.aborted) return resolve();
+ signal?.addEventListener("abort", () => resolve(), { once: true });
+ }),
+ );
+ return new Response(null, { status: 200 });
+ };
+ return adapter;
+ },
+ };
+});
+
import type { ServerSecretStore } from "../auth/ServerSecretStore.ts";
import { createEmptyReadModel } from "../orchestration/projector.ts";
import type { OrchestrationEngineShape } from "../orchestration/Services/OrchestrationEngine.ts";
import { makeMemoryChannelDeliveryStore } from "./ChannelDeliveryStore.ts";
import {
attachChannelConnection,
+ defaultProjectIdForBot,
+ CHANNEL_SENT_MESSAGE_RECOVERY_LIMIT,
+ ChannelPostRejectedError,
channelBindingsForRuntime,
channelThreadId,
connectChannel,
deleteChannelConnection,
+ detachChannelConnection,
disconnectChannel,
dispatchInboundChannelMessage,
+ finishChannelTurn,
+ clearChannelThreadStatuses,
handleWhatsAppWebhook,
+ mentionWithContext,
reconnectChannel,
saveChannelConnection,
restoreConnectedChannels,
sendCompletedChannelReply,
sendChannelMessage,
shutdownAllChannels,
+ startRenewingGateway,
stopArchivedBotChannels,
stopChannelsForBot,
type ChannelRuntimeDependencies,
@@ -83,6 +233,8 @@ import {
const NOW = "2026-08-27T20:00:00.000Z";
const BOT_ID = BotId.make("bot-1");
const PROJECT_ID = ProjectId.make("project-1");
+const SECOND_PROJECT_ID = ProjectId.make("project-2");
+const MISSING_PROJECT_ID = ProjectId.make("project-missing");
function makeBot(
id: BotId,
@@ -132,6 +284,19 @@ function makeModel(bots: ReadonlyArray<OrchestrationBot>): OrchestrationReadMode
updatedAt: NOW,
deletedAt: null,
},
+ {
+ id: SECOND_PROJECT_ID,
+ title: "Second project",
+ workspaceRoot: "/tmp/project-2",
+ defaultModelSelection: {
+ instanceId: ProviderInstanceId.make("codex"),
+ model: "gpt-5.6",
+ },
+ scripts: [],
+ createdAt: NOW,
+ updatedAt: NOW,
+ deletedAt: null,
+ },
],
};
}
@@ -154,7 +319,13 @@ function makeMessage(
};
}
-function makeChatSdkMessage(threadId: string, id: string, text: string, senderId: string) {
+function makeChatSdkMessage(
+ threadId: string,
+ id: string,
+ text: string,
+ senderId: string,
+ isMention = false,
+) {
return new ChatMessage({
id,
threadId,
@@ -171,7 +342,7 @@ function makeChatSdkMessage(threadId: string, id: string, text: string, senderId
// @effect-diagnostics-next-line globalDate:off - Chat SDK Message requires a Date fixture.
metadata: { dateSent: new Date(NOW), edited: false },
attachments: [],
- isMention: false,
+ isMention,
});
}
@@ -233,6 +404,7 @@ function makeHarness(input: {
readonly settings?: ChannelRuntimeDependencies["settings"];
readonly startTransport?: ChannelRuntimeDependencies["startTransport"] | null;
readonly failBotUpdate?: (updateIndex: number) => Error | undefined;
+ readonly commandModelOmitsMessages?: boolean;
}) {
let model = makeModel(input.bots ?? [makeBot(BOT_ID)]);
let settings = DEFAULT_SERVER_SETTINGS;
@@ -284,7 +456,12 @@ function makeHarness(input: {
}),
},
deliveryStore: input.deliveryStore ?? makeMemoryChannelDeliveryStore(),
- readModel: async () => ({ ...model, threads }),
+ readModel: async () => ({
+ ...model,
+ threads: input.commandModelOmitsMessages
+ ? threads.map((thread) => ({ ...thread, messages: [] }))
+ : threads,
+ }),
readThread: async (threadId) => threads.find((thread) => thread.id === threadId) ?? null,
nowIso: async () => NOW,
randomUuid: async () => `uuid-${commands.length}`,
@@ -305,10 +482,67 @@ function makeHarness(input: {
return { commands, dependencies, secrets, readModel: () => model, readSettings: () => settings };
}
+function makeAdapterDeliveryHarness(
+ provider: ChannelBinding["provider"],
+ externalThreadId: string,
+ text = "Reply",
+) {
+ const messageId = MessageId.make(`adapter-reply-${provider}`);
+ const threadId = ThreadId.make(`adapter-thread-${provider}`);
+ const harness = makeHarness({
+ startTransport: null,
+ threads: [
+ makeThread(threadId, BOT_ID, [
+ makeMessage(MessageId.make(`adapter-inbound-${provider}`), "user", "Question", {
+ provider,
+ externalThreadId,
+ }),
+ makeMessage(messageId, "assistant", text),
+ ]),
+ ],
+ });
+ return { harness, input: { botId: BOT_ID, threadId, messageId } };
+}
+
+function mockTelegramDelivery(responses: Array<Response | Error>) {
+ const sends = vi.fn(async () => {
+ const response = responses.shift();
+ if (response instanceof Error) throw response;
+ if (!response) throw new Error("Missing Telegram response");
+ return response;
+ });
+ vi.stubGlobal(
+ "fetch",
+ vi.fn<(...args: Parameters<typeof globalThis.fetch>) => Promise<Response>>(
+ async (input, init) => {
+ const method = String(input).split("/").at(-1);
+ if (method === "sendMessage") return sends();
+ if (method === "getMe")
+ return Response.json({
+ ok: true,
+ result: { id: 1, is_bot: true, first_name: "Akeru", username: "akeru" },
+ });
+ if (method === "deleteWebhook" || method === "deleteMyCommands") {
+ return Response.json({ ok: true, result: true });
+ }
+ if (method === "getUpdates")
+ return new Promise<Response>((_resolve, reject) => {
+ const abort = () => reject(new DOMException("Aborted", "AbortError"));
+ if (init?.signal?.aborted) abort();
+ else init?.signal?.addEventListener("abort", abort, { once: true });
+ });
+ throw new Error(`Unexpected Telegram method: ${method}`);
+ },
+ ),
+ );
+ return sends;
+}
+
const telegramConnect = (botId: BotId, token = "telegram-token") => ({
type: "channel.connect" as const,
commandId: CommandId.make(`connect-${botId}`),
botId,
+ targetProjectId: PROJECT_ID,
provider: "telegram" as const,
token,
});
@@ -317,6 +551,7 @@ const imessageConnect = (botId: BotId) => ({
type: "channel.connect" as const,
commandId: CommandId.make(`connect-imessage-${botId}`),
botId,
+ targetProjectId: PROJECT_ID,
provider: "imessage" as const,
mode: "hosted" as const,
projectId: "photon-project",
@@ -327,6 +562,7 @@ const whatsappConnect = (botId: BotId) => ({
type: "channel.connect" as const,
commandId: CommandId.make(`connect-whatsapp-${botId}`),
botId,
+ targetProjectId: PROJECT_ID,
provider: "whatsapp" as const,
accessToken: "access-token",
appSecret: "app-secret",
@@ -334,6 +570,27 @@ const whatsappConnect = (botId: BotId) => ({
verifyToken: "verify-token",
});
+const slackConnect = (botId: BotId) => ({
+ type: "channel.connect" as const,
+ commandId: CommandId.make(`connect-slack-${botId}`),
+ botId,
+ targetProjectId: PROJECT_ID,
+ provider: "slack" as const,
+ botToken: "xoxb-token",
+ appToken: "xapp-token",
+});
+
+const discordConnect = (botId: BotId) => ({
+ type: "channel.connect" as const,
+ commandId: CommandId.make(`connect-discord-${botId}`),
+ botId,
+ targetProjectId: PROJECT_ID,
+ provider: "discord" as const,
+ botToken: "discord-token",
+ applicationId: "discord-app",
+ publicKey: "discord-public-key",
+});
+
const signedWhatsAppRequest = (body: string) =>
new Request(`https://akeru.example/api/channels/whatsapp/${BOT_ID}/webhook`, {
method: "POST",
@@ -350,15 +607,304 @@ afterEach(async () => {
photon.chat = null;
photon.failedSubscription = null;
photon.subscriptionAttempts.length = 0;
+ externalAdapters.slackAdapter = null;
+ externalAdapters.slackChat = null;
+ externalAdapters.slackDisconnects = 0;
+ externalAdapters.slackIdentityAvailable = true;
+ externalAdapters.slackInitializationFails = false;
+ externalAdapters.slackSubscriptions.length = 0;
+ externalAdapters.slackResponses.length = 0;
+ externalAdapters.slackPostRequests = 0;
+ externalAdapters.slackRetryOptions = {};
+ vi.unstubAllGlobals();
+ externalAdapters.discordAdapter = null;
+ externalAdapters.discordChat = null;
+ externalAdapters.discordGatewayStarts = 0;
+ externalAdapters.discordIdentityFails = false;
+ externalAdapters.discordDisconnects = 0;
+ externalAdapters.discordSubscriptions.length = 0;
+ externalAdapters.reactions.length = 0;
});
describe("channel runtime", () => {
+ it.each(["slack", "discord"] as const)(
+ "cleans persisted and terminal %s reactions through adapter APIs",
+ async (provider) => {
+ const externalThreadId = provider === "slack" ? "slack:C1:1" : "discord:guild-1:channel-1";
+ const threadId = channelThreadId(BOT_ID, PROJECT_ID, provider, externalThreadId);
+ const turnId = TurnId.make("reaction-turn");
+ const requestMessageId = MessageId.make("reaction-request");
+ const thread: OrchestrationThread = {
+ ...makeThread(threadId, BOT_ID, [
+ makeMessage(requestMessageId, "user", "Question", {
+ provider,
+ externalThreadId,
+ externalMessageId: "external-request",
+ }),
+ ]),
+ latestTurn: {
+ turnId,
+ state: "completed",
+ requestedAt: NOW,
+ startedAt: NOW,
+ completedAt: NOW,
+ assistantMessageId: null,
+ requestMessageId,
+ respondingBotId: BOT_ID,
+ },
+ };
+ const harness = makeHarness({
+ startTransport: null,
+ threads: [thread],
+ commandModelOmitsMessages: true,
+ });
+ await connectChannel(
+ harness.dependencies,
+ provider === "slack" ? slackConnect(BOT_ID) : discordConnect(BOT_ID),
+ );
+ const prefix = `${externalThreadId}:external-request`;
+ expect(externalAdapters.reactions).toEqual([
+ `remove:${prefix}:eyes`,
+ `remove:${prefix}:white_check_mark`,
+ `remove:${prefix}:x`,
+ ]);
+ await finishChannelTurn(harness.dependencies, threadId, turnId, "completed");
+ expect(externalAdapters.reactions.at(-1)).toBe(`add:${prefix}:white_check_mark`);
+ const count = externalAdapters.reactions.length;
+ await finishChannelTurn(harness.dependencies, threadId, turnId, "completed");
+ expect(externalAdapters.reactions).toHaveLength(count);
+ await clearChannelThreadStatuses(threadId);
+ expect(externalAdapters.reactions.slice(-3)).toEqual([
+ `remove:${prefix}:eyes`,
+ `remove:${prefix}:white_check_mark`,
+ `remove:${prefix}:x`,
+ ]);
+ await finishChannelTurn(harness.dependencies, threadId, turnId, "failed");
+ expect(externalAdapters.reactions.at(-1)).toBe(`add:${prefix}:x`);
+ await disconnectChannel(harness.dependencies, BOT_ID, provider);
+ expect(externalAdapters.reactions.slice(-3)).toEqual([
+ `remove:${prefix}:eyes`,
+ `remove:${prefix}:white_check_mark`,
+ `remove:${prefix}:x`,
+ ]);
+ externalAdapters.reactions.length = 0;
+ await reconnectChannel(harness.dependencies, BOT_ID, provider);
+ expect(externalAdapters.reactions).toEqual([
+ `remove:${prefix}:eyes`,
+ `remove:${prefix}:white_check_mark`,
+ `remove:${prefix}:x`,
+ ]);
+ },
+ );
+
+ it("exposes gateway failure in runtime channel health", async () => {
+ const failed = Promise.withResolvers<void>();
+ const gateway = await startRenewingGateway(async (waitUntil) => {
+ waitUntil(failed.promise);
+ return new Response(null, { status: 200 });
+ }, "Test gateway");
+ const harness = makeHarness({
+ startTransport: async () => ({
+ externalIdentity: "test",
+ runtime: { post: async () => {}, shutdown: gateway.shutdown, isHealthy: gateway.isHealthy },
+ }),
+ });
+ await connectChannel(harness.dependencies, discordConnect(BOT_ID));
+ const bindings = harness.readModel().bots[0]!.channelBindings;
+ expect(channelBindingsForRuntime(bindings)[0]?.status).toBe("connected");
+ failed.reject(new Error("Gateway disconnected"));
+ await gateway.settled;
+ expect(channelBindingsForRuntime(bindings)[0]?.status).toBe("needs-reconnect");
+ });
+
+ it("attaches to the bot's default project when the client names none", async () => {
+ const connectionId = ChannelConnectionId.make("channel-default-project");
+ const harness = makeHarness({
+ startTransport: async () => ({
+ externalIdentity: "@bot",
+ runtime: { post: async () => {}, shutdown: async () => {} },
+ }),
+ });
+ await saveChannelConnection(harness.dependencies, {
+ type: "channel.connection.save",
+ commandId: CommandId.make("save-default-project"),
+ connectionId,
+ name: "Default project line",
+ provider: "telegram",
+ token: "telegram-token",
+ });
+
+ await attachChannelConnection(
+ harness.dependencies,
+ BOT_ID,
+ connectionId,
+ undefined,
+ "telegram",
+ );
+
+ expect(harness.readModel().bots[0]?.channelBindings?.[0]).toMatchObject({
+ connectionId,
+ status: "connected",
+ projectId: defaultProjectIdForBot(harness.readModel(), BOT_ID),
+ });
+ });
+
+ it("resolves a bot's default project from its own recent chats before global activity", () => {
+ const model = makeHarness({}).readModel();
+ const otherBot = BotId.make("other-bot");
+ const base = makeThread(ThreadId.make("t"), BOT_ID, []);
+ const withThreads = {
+ ...model,
+ threads: [
+ {
+ ...base,
+ id: ThreadId.make("bot-old"),
+ projectId: SECOND_PROJECT_ID,
+ updatedAt: "2026-01-01T00:00:00.000Z",
+ },
+ {
+ ...base,
+ id: ThreadId.make("bot-new"),
+ projectId: PROJECT_ID,
+ updatedAt: "2026-02-01T00:00:00.000Z",
+ },
+ {
+ ...base,
+ id: ThreadId.make("other"),
+ botId: otherBot,
+ projectId: SECOND_PROJECT_ID,
+ updatedAt: "2026-03-01T00:00:00.000Z",
+ },
+ ],
+ };
+ expect(defaultProjectIdForBot(withThreads, BOT_ID)).toBe(PROJECT_ID);
+ expect(defaultProjectIdForBot(withThreads, otherBot)).toBe(SECOND_PROJECT_ID);
+ expect(defaultProjectIdForBot(withThreads, BotId.make("fresh-bot"))).toBe(SECOND_PROJECT_ID);
+ expect(defaultProjectIdForBot({ ...model, threads: [] }, BOT_ID)).toBe(PROJECT_ID);
+ expect(defaultProjectIdForBot({ ...model, projects: [], threads: [] }, BOT_ID)).toBeNull();
+ });
+
it("gives each external conversation a stable isolated thread", () => {
- const first = channelThreadId(BOT_ID, "telegram", "telegram:123");
+ const first = channelThreadId(BOT_ID, PROJECT_ID, "telegram", "telegram:123");
+
+ expect(channelThreadId(BOT_ID, PROJECT_ID, "telegram", "telegram:123")).toBe(first);
+ expect(channelThreadId(BOT_ID, PROJECT_ID, "telegram", "telegram:456")).not.toBe(first);
+ expect(channelThreadId(BOT_ID, PROJECT_ID, "imessage", "telegram:123")).not.toBe(first);
+ });
+
+ it("routes an inbound message to the selected project instead of the first project", async () => {
+ const harness = makeHarness({});
+
+ await dispatchInboundChannelMessage(harness.dependencies, {
+ botId: BOT_ID,
+ projectId: SECOND_PROJECT_ID,
+ provider: "telegram",
+ externalThreadId: "chat-project-2",
+ externalMessageId: "message-project-2",
+ text: "Work in project two",
+ });
+
+ expect(harness.commands.find((command) => command.type === "thread.create")).toMatchObject({
+ projectId: SECOND_PROJECT_ID,
+ });
+ });
+
+ it("marks the binding failed when its selected project is unavailable", async () => {
+ const binding: ChannelBinding = {
+ botId: BOT_ID,
+ projectId: MISSING_PROJECT_ID,
+ provider: "telegram",
+ status: "connected",
+ externalIdentity: "@akeru",
+ connectedAt: NOW,
+ sentMessageIds: [],
+ };
+ const harness = makeHarness({ bots: [makeBot(BOT_ID, { channelBindings: [binding] })] });
+
+ await expect(
+ dispatchInboundChannelMessage(harness.dependencies, {
+ botId: BOT_ID,
+ projectId: MISSING_PROJECT_ID,
+ provider: "telegram",
+ externalThreadId: "chat-missing-project",
+ externalMessageId: "message-missing-project",
+ text: "Work",
+ }),
+ ).rejects.toThrow("project is unavailable");
+ expect(harness.readModel().bots[0]?.channelBindings[0]).toMatchObject({
+ status: "failed",
+ lastError: "The selected project is unavailable. Choose another project.",
+ });
+ });
+
+ it("starts a new thread when the legacy conversation belongs to another project", async () => {
+ const externalThreadId = "telegram:legacy-other-project";
+ const legacyThreadId = ThreadId.make(
+ `channel-${NodeCrypto.createHash("sha256")
+ .update(`${BOT_ID}\0telegram\0${externalThreadId}`)
+ .digest("hex")}`,
+ );
+ const harness = makeHarness({ threads: [makeThread(legacyThreadId, BOT_ID, [])] });
+
+ await dispatchInboundChannelMessage(harness.dependencies, {
+ botId: BOT_ID,
+ projectId: SECOND_PROJECT_ID,
+ provider: "telegram",
+ externalThreadId,
+ externalMessageId: "new-project-message",
+ text: "Use the selected project",
+ });
+
+ const created = harness.commands.find((command) => command.type === "thread.create");
+ expect(created).toMatchObject({ projectId: SECOND_PROJECT_ID });
+ expect(created?.threadId).not.toBe(legacyThreadId);
+ expect(harness.commands.find((command) => command.type === "thread.turn.start")).toMatchObject({
+ threadId: created?.threadId,
+ });
+ });
+
+ it("continues a channel thread created before project-aware thread IDs", async () => {
+ const externalThreadId = "telegram:legacy-chat";
+ const legacyThreadId = ThreadId.make(
+ `channel-${NodeCrypto.createHash("sha256")
+ .update(`${BOT_ID}\0telegram\0${externalThreadId}`)
+ .digest("hex")}`,
+ );
+ const harness = makeHarness({ threads: [makeThread(legacyThreadId, BOT_ID, [])] });
+
+ await dispatchInboundChannelMessage(harness.dependencies, {
+ botId: BOT_ID,
+ projectId: PROJECT_ID,
+ provider: "telegram",
+ externalThreadId,
+ externalMessageId: "legacy-message",
+ text: "Continue here",
+ });
+
+ expect(harness.commands.some((command) => command.type === "thread.create")).toBe(false);
+ expect(harness.commands.find((command) => command.type === "thread.turn.start")).toMatchObject({
+ threadId: legacyThreadId,
+ });
+ });
+
+ it("derives stable command and message identities from the provider message", async () => {
+ const harness = makeHarness({});
+ const input = {
+ botId: BOT_ID,
+ projectId: PROJECT_ID,
+ provider: "telegram" as const,
+ externalThreadId: "chat-dedupe",
+ externalMessageId: "provider-message-1",
+ text: "Only once",
+ };
+
+ await dispatchInboundChannelMessage(harness.dependencies, input);
+ await dispatchInboundChannelMessage(harness.dependencies, input);
- expect(channelThreadId(BOT_ID, "telegram", "telegram:123")).toBe(first);
- expect(channelThreadId(BOT_ID, "telegram", "telegram:456")).not.toBe(first);
- expect(channelThreadId(BOT_ID, "imessage", "telegram:123")).not.toBe(first);
+ const turns = harness.commands.filter((command) => command.type === "thread.turn.start");
+ expect(turns).toHaveLength(2);
+ expect(turns[0]?.commandId).toBe(turns[1]?.commandId);
+ expect(turns[0]?.message.messageId).toBe(turns[1]?.message.messageId);
});
it("preserves the inbound provider, thread, and sender on the turn command", async () => {
@@ -366,6 +912,7 @@ describe("channel runtime", () => {
await dispatchInboundChannelMessage(harness.dependencies, {
botId: BOT_ID,
+ projectId: PROJECT_ID,
provider: "telegram",
externalThreadId: "chat-a",
externalSenderId: "sender-7",
@@ -457,22 +1004,18 @@ describe("channel runtime", () => {
expect(turn.message.channelOrigin).toEqual({
provider: "whatsapp",
externalThreadId: "whatsapp:phone-number-id:15551234567",
+ externalMessageId: "wamid.1",
externalSenderId: "15551234567",
});
});
- it("keeps DMs automatic and requires the exact bot mention in iMessage groups", async () => {
+ it("accepts iMessage direct messages and ignores group messages", async () => {
let directMessage:
| Parameters<NonNullable<ChannelRuntimeDependencies["startTransport"]>>[1]
| undefined;
- let transportContext:
- | Parameters<NonNullable<ChannelRuntimeDependencies["startTransport"]>>[2]
- | undefined;
const harness = makeHarness({
- bots: [makeBot(BOT_ID, { name: "Build Bot" })],
- startTransport: async (_input, onDirectMessage, context) => {
+ startTransport: async (_input, onDirectMessage) => {
directMessage = onDirectMessage;
- transportContext = context;
return {
externalIdentity: "Photon hosted",
runtime: { post: async () => undefined, shutdown: async () => undefined },
@@ -483,246 +1026,341 @@ describe("channel runtime", () => {
await directMessage?.({
externalThreadId: "imessage:iMessage;-;+15551234567",
+ externalMessageId: "direct-1",
externalSenderId: "+15551234567",
+ externalSenderName: "Alice",
text: "DM without a mention",
});
- await transportContext?.onIMessageGroupMessage({
- externalThreadId: "imessage:opaque-family-chat",
- externalSenderId: "+15557654321",
- text: "Build Bot should ignore this",
- });
- await transportContext?.onIMessageGroupMessage({
- externalThreadId: "imessage:opaque-family-chat",
- externalSenderId: "+15557654321",
- text: "@Build Botany should also be ignored",
+
+ const turns = harness.commands.filter((command) => command.type === "thread.turn.start");
+ expect(turns).toHaveLength(1);
+ expect(turns[0]?.message.channelOrigin).toMatchObject({
+ provider: "imessage",
+ externalMessageId: "direct-1",
+ externalThreadId: "imessage:iMessage;-;+15551234567",
});
+ });
- expect(harness.commands.filter((command) => command.type === "thread.turn.start")).toHaveLength(
- 1,
+ it("bounds first-mention context and preserves sender attribution", async () => {
+ const threadId = "slack:C123:1710000000.000001";
+ const history = Array.from({ length: 12 }, (_, index) =>
+ makeChatSdkMessage(threadId, `history-${index}`, `context ${index}`, `U${index}`),
);
+ const current = makeChatSdkMessage(
+ threadId,
+ "mention-current",
+ "@Akeru investigate",
+ "U-current",
+ true,
+ );
+ const thread = {
+ id: threadId,
+ recentMessages: [...history, current],
+ refresh: async () => undefined,
+ } as unknown as Thread;
+
+ const normalized = await mentionWithContext(thread, current);
+
+ expect(normalized.text).not.toContain("U0: context 0\n");
+ expect(normalized.text).not.toContain("U1: context 1\n");
+ expect(normalized.text.split("\n")).toHaveLength(11);
+ expect(normalized.externalSenderName).toBe("U-current");
+ expect(normalized.externalMessageId).toBe("mention-current");
+ });
- await transportContext?.onIMessageGroupMessage({
- externalThreadId: "imessage:opaque-family-chat",
- externalSenderId: "+15557654321",
- text: "@build bot check the build",
- });
+ it("limits large prior context without truncating the current mention", async () => {
+ const threadId = "slack:C123:large-context";
+ const current = makeChatSdkMessage(
+ threadId,
+ "current",
+ "@Akeru investigate",
+ "U-current",
+ true,
+ );
+ const thread = {
+ id: threadId,
+ recentMessages: [
+ makeChatSdkMessage(threadId, "earlier", "x".repeat(20_000), "U1"),
+ makeChatSdkMessage(threadId, "latest", "Latest detail", "U2"),
+ current,
+ ],
+ refresh: async () => undefined,
+ } as unknown as Thread;
- const turns = harness.commands.filter((command) => command.type === "thread.turn.start");
- expect(turns).toHaveLength(2);
- expect(
- harness.commands.find(
- (command) => command.type === "thread.create" && command.threadId === turns[1]?.threadId,
- ),
- ).toMatchObject({ botId: BOT_ID, groupId: null });
- expect(turns[1]?.message.channelOrigin).toEqual({
- provider: "imessage",
- externalThreadId: "imessage:opaque-family-chat",
- externalSenderId: "+15557654321",
- });
- expect(turns[1]?.message.text).toBe(
- [
- "+15557654321: Build Bot should ignore this",
- "+15557654321: @Build Botany should also be ignored",
- "+15557654321: @build bot check the build",
- ].join("\n"),
+ const normalized = await mentionWithContext(thread, current);
+
+ expect(normalized.text.length).toBe(8_000 + 1 + current.text.length);
+ expect(normalized.text).toContain("U2: Latest detail");
+ expect(normalized.text.endsWith(`\n${current.text}`)).toBe(true);
+ });
+
+ it("shuts down an adapter when chat initialization fails", async () => {
+ externalAdapters.slackInitializationFails = true;
+ const harness = makeHarness({ startTransport: null });
+
+ await expect(connectChannel(harness.dependencies, slackConnect(BOT_ID))).rejects.toThrow(
+ "Socket startup failed",
);
- await transportContext?.onIMessageGroupMessage({
- externalThreadId: "imessage:opaque-family-chat",
- externalSenderId: "+15557654321",
- text: "@build bot check again",
- });
+ expect(externalAdapters.slackDisconnects).toBe(1);
+ expect(harness.readModel().bots[0]?.channelBindings).toEqual([]);
+ expect(harness.secrets.size).toBe(0);
+ });
+
+ it("rejects Slack credentials that cannot resolve the bot identity", async () => {
+ externalAdapters.slackIdentityAvailable = false;
+ const harness = makeHarness({ startTransport: null });
+
+ await expect(connectChannel(harness.dependencies, slackConnect(BOT_ID))).rejects.toThrow(
+ "Slack bot credentials are invalid",
+ );
+ expect(harness.readModel().bots[0]?.channelBindings).toEqual([]);
+ });
+
+ it("routes Slack direct messages and subscribed mention threads", async () => {
+ const harness = makeHarness({ startTransport: null });
+ await connectChannel(harness.dependencies, slackConnect(BOT_ID));
+ if (!externalAdapters.slackChat || !externalAdapters.slackAdapter) {
+ throw new Error("Expected the Slack Chat runtime.");
+ }
- const turnsAfterSecondMention = harness.commands.filter(
- (command) => command.type === "thread.turn.start",
+ const directThreadId = "slack:D123:";
+ await externalAdapters.slackChat.processMessage(
+ externalAdapters.slackAdapter,
+ directThreadId,
+ makeChatSdkMessage(directThreadId, "slack-dm-1", "Direct work", "U1"),
+ );
+ const channelThreadId = "slack:C123:1710000000.000001";
+ await externalAdapters.slackChat.processMessage(
+ externalAdapters.slackAdapter,
+ channelThreadId,
+ makeChatSdkMessage(channelThreadId, "slack-mention-1", "@Akeru investigate", "U2", true),
);
- expect(turnsAfterSecondMention.map((turn) => turn.message.text)).toEqual([
- "DM without a mention",
- turns[1]?.message.text,
- "@build bot check again",
+ await externalAdapters.slackChat.processMessage(
+ externalAdapters.slackAdapter,
+ channelThreadId,
+ makeChatSdkMessage(channelThreadId, "slack-followup-1", "One more detail", "U3"),
+ );
+
+ const turns = harness.commands.filter((command) => command.type === "thread.turn.start");
+ expect(turns.map((turn) => turn.message.channelOrigin?.externalMessageId)).toEqual([
+ "slack-dm-1",
+ "slack-mention-1",
+ "slack-followup-1",
]);
+ expect(turns[1]?.threadId).toBe(turns[2]?.threadId);
+
+ await disconnectChannel(harness.dependencies, BOT_ID, "slack");
+ expect(externalAdapters.slackDisconnects).toBeGreaterThan(0);
});
- it("keeps recent iMessage context separate by group", async () => {
- let transportContext:
- | Parameters<NonNullable<ChannelRuntimeDependencies["startTransport"]>>[2]
- | undefined;
+ it("restores Slack and Discord platform-thread subscriptions", async () => {
+ const slackThreadId = ThreadId.make("thread-slack-restored");
+ const discordThreadId = ThreadId.make("thread-discord-restored");
const harness = makeHarness({
- bots: [makeBot(BOT_ID, { name: "Build Bot" })],
- startTransport: async (_input, _onDirectMessage, context) => {
- transportContext = context;
- return {
- externalIdentity: "Photon hosted",
- runtime: { post: async () => undefined, shutdown: async () => undefined },
- };
- },
+ startTransport: null,
+ commandModelOmitsMessages: true,
+ threads: [
+ makeThread(slackThreadId, BOT_ID, [
+ makeMessage(MessageId.make("slack-origin"), "user", "Mention", {
+ provider: "slack",
+ externalThreadId: "slack:C1:1",
+ }),
+ ]),
+ makeThread(discordThreadId, BOT_ID, [
+ makeMessage(MessageId.make("discord-origin"), "user", "Mention", {
+ provider: "discord",
+ externalThreadId: "discord:G1:C1:T1",
+ }),
+ ]),
+ ],
});
- await connectChannel(harness.dependencies, imessageConnect(BOT_ID));
- await transportContext?.onIMessageGroupMessage({
- externalThreadId: "imessage:group-a",
- externalSenderId: "alice",
- text: "A context",
- });
- await transportContext?.onIMessageGroupMessage({
- externalThreadId: "imessage:group-b",
- externalSenderId: "bob",
- text: "B context",
- });
- await transportContext?.onIMessageGroupMessage({
- externalThreadId: "imessage:group-a",
- externalSenderId: "carol",
- text: "@build bot answer A",
+ await connectChannel(harness.dependencies, slackConnect(BOT_ID));
+ await connectChannel(harness.dependencies, discordConnect(BOT_ID));
+
+ expect(externalAdapters.slackRestoredBeforeInitialize).toBe(true);
+ expect(externalAdapters.slackSubscriptions).toContain("slack:C1:1");
+ expect(externalAdapters.discordSubscriptions).toContain("discord:G1:C1:T1");
+ });
+
+ it("owns and aborts renewable Gateway listeners", async () => {
+ let capturedSignal: AbortSignal | undefined;
+ let capturedDuration = 0;
+ const gateway = await startRenewingGateway(async (waitUntil, durationMs, signal) => {
+ capturedSignal = signal;
+ capturedDuration = durationMs;
+ waitUntil(
+ new Promise<void>((resolve) => {
+ signal.addEventListener("abort", () => resolve(), { once: true });
+ }),
+ );
+ return new Response(null, { status: 200 });
+ }, "Test gateway");
+
+ expect(capturedDuration).toBeGreaterThan(3 * 60 * 1_000);
+ expect(capturedSignal?.aborted).toBe(false);
+ await gateway.shutdown();
+ expect(capturedSignal?.aborted).toBe(true);
+ });
+
+ it("waits for gateway cleanup before shutdown completes", async () => {
+ let finishCleanup: (() => void) | undefined;
+ const cleanup = new Promise<void>((resolve) => {
+ finishCleanup = resolve;
});
- await transportContext?.onIMessageGroupMessage({
- externalThreadId: "imessage:group-b",
- externalSenderId: "dave",
- text: "@build bot answer B",
+ const gateway = await startRenewingGateway(async (waitUntil, _duration, signal) => {
+ waitUntil(
+ new Promise<void>((resolve) => {
+ signal.addEventListener(
+ "abort",
+ () => {
+ void cleanup.then(resolve);
+ },
+ { once: true },
+ );
+ }),
+ );
+ return new Response(null, { status: 200 });
+ }, "Test gateway");
+ let stopped = false;
+ const shutdown = gateway.shutdown().then(() => {
+ stopped = true;
});
+ await Promise.resolve();
+ expect(stopped).toBe(false);
+ expect(gateway.isHealthy()).toBe(false);
+ finishCleanup?.();
+ await shutdown;
+ expect(stopped).toBe(true);
+ });
- const turns = harness.commands.filter((command) => command.type === "thread.turn.start");
- expect(turns.map((turn) => turn.message.text)).toEqual([
- "alice: A context\ncarol: @build bot answer A",
- "bob: B context\ndave: @build bot answer B",
- ]);
- expect(turns.map((turn) => turn.message.channelOrigin?.externalThreadId)).toEqual([
- "imessage:group-a",
- "imessage:group-b",
- ]);
+ it("marks an early gateway exit unhealthy instead of restarting it", async () => {
+ let starts = 0;
+ const gateway = await startRenewingGateway(async (waitUntil) => {
+ starts += 1;
+ waitUntil(Promise.resolve());
+ return new Response(null, { status: 200 });
+ }, "Test gateway");
+ await gateway.settled;
+ expect(gateway.isHealthy()).toBe(false);
+ expect(starts).toBe(1);
+ await gateway.shutdown();
});
- it("bounds buffered iMessage group chatter", async () => {
- let transportContext:
+ it("routes normalized Discord direct messages and mention-thread continuation", async () => {
+ let directMessage:
+ | Parameters<NonNullable<ChannelRuntimeDependencies["startTransport"]>>[1]
+ | undefined;
+ let context:
| Parameters<NonNullable<ChannelRuntimeDependencies["startTransport"]>>[2]
| undefined;
const harness = makeHarness({
- bots: [makeBot(BOT_ID, { name: "Build Bot" })],
- startTransport: async (_input, _onDirectMessage, context) => {
- transportContext = context;
+ startTransport: async (_input, onDirectMessage, transportContext) => {
+ directMessage = onDirectMessage;
+ context = transportContext;
return {
- externalIdentity: "Photon hosted",
+ externalIdentity: "akeru-discord",
runtime: { post: async () => undefined, shutdown: async () => undefined },
};
},
});
- await connectChannel(harness.dependencies, imessageConnect(BOT_ID));
+ await connectChannel(harness.dependencies, discordConnect(BOT_ID));
- for (let index = 0; index < 21; index += 1) {
- await transportContext?.onIMessageGroupMessage({
- externalThreadId: "imessage:busy-group",
- externalSenderId: "alice",
- text: `context ${index}`,
- });
- }
- await transportContext?.onIMessageGroupMessage({
- externalThreadId: "imessage:busy-group",
- externalSenderId: "bob",
- text: "@build bot summarize",
+ await directMessage?.({
+ externalThreadId: "discord:@me:dm-channel",
+ externalMessageId: "discord-dm-1",
+ externalSenderId: "D1",
+ text: "Direct work",
+ });
+ await context?.onMention({
+ externalThreadId: "discord:guild-1:channel-1:thread-1",
+ externalMessageId: "discord-mention-1",
+ externalSenderId: "D2",
+ text: "@Akeru investigate",
+ });
+ await context?.onSubscribedMessage({
+ externalThreadId: "discord:guild-1:channel-1:thread-1",
+ externalMessageId: "discord-followup-1",
+ externalSenderId: "D3",
+ text: "One more detail",
});
- const turn = harness.commands.find((command) => command.type === "thread.turn.start");
- expect(turn?.type).toBe("thread.turn.start");
- if (turn?.type !== "thread.turn.start") throw new Error("Expected a turn command.");
- expect(turn.message.text).not.toContain("context 0\n");
- expect(turn.message.text.split("\n")).toHaveLength(21);
+ const turns = harness.commands.filter((command) => command.type === "thread.turn.start");
+ expect(turns.map((turn) => turn.message.channelOrigin?.externalMessageId)).toEqual([
+ "discord-dm-1",
+ "discord-mention-1",
+ "discord-followup-1",
+ ]);
+ expect(turns[1]?.threadId).toBe(turns[2]?.threadId);
});
- it("routes initial and subscribed iMessage group mentions through Chat SDK", async () => {
- const groupId = "imessage:opaque-group";
- const harness = makeHarness({
- bots: [makeBot(BOT_ID, { name: "Build Bot" })],
- startTransport: null,
- });
- await connectChannel(harness.dependencies, imessageConnect(BOT_ID));
- if (!photon.chat || !photon.adapter) throw new Error("Expected the Photon Chat runtime.");
+ it("shuts down Discord when credential validation fails", async () => {
+ externalAdapters.discordIdentityFails = true;
+ const harness = makeHarness({ startTransport: null });
- await photon.chat.processMessage(
- photon.adapter,
- groupId,
- makeChatSdkMessage(groupId, "group-1", "@build bot status", "+15551110000"),
- );
- await photon.chat.processMessage(
- photon.adapter,
- groupId,
- makeChatSdkMessage(groupId, "group-2", "background chatter", "+15552220000"),
- );
- await photon.chat.processMessage(
- photon.adapter,
- groupId,
- makeChatSdkMessage(groupId, "group-2b", "@Build Bot-dev ignore", "+15552220000"),
- );
- await photon.chat.processMessage(
- photon.adapter,
- groupId,
- makeChatSdkMessage(groupId, "group-3", "@BUILD BOT continue", "+15552220000"),
+ await expect(connectChannel(harness.dependencies, discordConnect(BOT_ID))).rejects.toThrow(
+ "Discord identity failed",
);
- const turns = harness.commands.filter((command) => command.type === "thread.turn.start");
- expect(turns).toHaveLength(2);
- expect(photon.subscriptionAttempts).toEqual([groupId]);
- expect(turns.map((turn) => turn.message.text)).toEqual([
- "@build bot status",
- "+15552220000: background chatter\n+15552220000: @Build Bot-dev ignore\n+15552220000: @BUILD BOT continue",
- ]);
+ expect(externalAdapters.discordDisconnects).toBe(1);
+ expect(externalAdapters.discordGatewayStarts).toBe(0);
+ expect(harness.readModel().bots[0]?.channelBindings).toEqual([]);
+ expect(harness.secrets.size).toBe(0);
});
- it("restores durable iMessage group subscriptions for the bot channel", async () => {
- const groupId = "imessage:opaque-release-team";
- const badGroupId = "imessage:stale-release-team";
- const threadId = channelThreadId(BOT_ID, "imessage", groupId);
- const badThreadId = channelThreadId(BOT_ID, "imessage", badGroupId);
- const harness = makeHarness({
- startTransport: null,
- threads: [
- makeThread(threadId, BOT_ID, [
- makeMessage(MessageId.make("group-inbound"), "user", "@Build Bot status", {
- provider: "imessage",
- externalThreadId: groupId,
- externalSenderId: "+15552223333",
- }),
- ]),
- makeThread(badThreadId, BOT_ID, [
- makeMessage(MessageId.make("bad-group-inbound"), "user", "@Build Bot status", {
- provider: "imessage",
- externalThreadId: badGroupId,
- externalSenderId: "+15553334444",
- }),
- ]),
- ],
- });
- photon.failedSubscription = badGroupId;
+ it("starts and stops the supervised Discord Gateway", async () => {
+ const harness = makeHarness({ startTransport: null });
+ await connectChannel(harness.dependencies, discordConnect(BOT_ID));
- await connectChannel(harness.dependencies, imessageConnect(BOT_ID));
- await stopChannelsForBot(BOT_ID);
- await expect(restoreConnectedChannels(harness.dependencies)).resolves.toEqual([]);
+ expect(externalAdapters.discordGatewayStarts).toBe(1);
+ expect(harness.readModel().bots[0]?.channelBindings[0]).toMatchObject({
+ projectId: PROJECT_ID,
+ provider: "discord",
+ status: "connected",
+ });
- expect(photon.subscriptionAttempts.filter((id) => id === groupId)).toHaveLength(2);
- expect(photon.subscriptionAttempts.filter((id) => id === badGroupId)).toHaveLength(2);
+ await disconnectChannel(harness.dependencies, BOT_ID, "discord");
+ expect(harness.readModel().bots[0]?.channelBindings[0]?.status).toBe("disconnected");
});
- it("replies to the same iMessage group GUID", async () => {
- const groupId = "imessage:iMessage;+;project-chat~+15550001111";
- const messageId = MessageId.make("group-reply");
- const threadId = channelThreadId(BOT_ID, "imessage", groupId);
- const posts: Array<{ readonly externalThreadId: string; readonly text: string }> = [];
+ it("ignores callbacks from a disconnected or replaced transport", async () => {
+ const callbacks: Array<
+ Parameters<NonNullable<ChannelRuntimeDependencies["startTransport"]>>[1]
+ > = [];
const harness = makeHarness({
- threads: [
- makeThread(threadId, BOT_ID, [
- makeMessage(MessageId.make("group-question"), "user", "@bot-1 status", {
- provider: "imessage",
- externalThreadId: groupId,
- externalSenderId: "+15554445555",
- }),
- makeMessage(messageId, "assistant", "Build is green"),
- ]),
- ],
- post: async (externalThreadId, text) => void posts.push({ externalThreadId, text }),
+ startTransport: async (_input, onDirectMessage) => {
+ callbacks.push(onDirectMessage);
+ return {
+ externalIdentity: "@akeru",
+ runtime: {
+ post: async () => undefined,
+ shutdown: async () => undefined,
+ },
+ };
+ },
});
- await connectChannel(harness.dependencies, imessageConnect(BOT_ID));
-
- await sendChannelMessage(harness.dependencies, { botId: BOT_ID, threadId, messageId });
+ await connectChannel(harness.dependencies, telegramConnect(BOT_ID));
+ await disconnectChannel(harness.dependencies, BOT_ID, "telegram");
+ const message = {
+ externalThreadId: "telegram:retired",
+ externalMessageId: "late",
+ text: "Late event",
+ };
+ await callbacks[0]?.(message);
+ expect(harness.commands.filter((command) => command.type === "thread.turn.start")).toHaveLength(
+ 0,
+ );
- expect(posts).toEqual([{ externalThreadId: groupId, text: "Build is green" }]);
+ await connectChannel(harness.dependencies, telegramConnect(BOT_ID));
+ await callbacks[0]?.(message);
+ expect(harness.commands.filter((command) => command.type === "thread.turn.start")).toHaveLength(
+ 0,
+ );
+ await callbacks[1]?.({ ...message, externalMessageId: "current" });
+ expect(harness.commands.filter((command) => command.type === "thread.turn.start")).toHaveLength(
+ 1,
+ );
});
it("rejects inbound messages for archived bots", async () => {
@@ -731,6 +1369,7 @@ describe("channel runtime", () => {
await expect(
dispatchInboundChannelMessage(harness.dependencies, {
botId: BOT_ID,
+ projectId: PROJECT_ID,
provider: "telegram",
externalThreadId: "chat-a",
text: "Hello",
@@ -780,6 +1419,30 @@ describe("channel runtime", () => {
expect(starts).toBe(0);
});
+ it("records a truthful failed state when restore cannot start the transport", async () => {
+ const binding: ChannelBinding = {
+ botId: BOT_ID,
+ projectId: PROJECT_ID,
+ provider: "telegram",
+ status: "connected",
+ externalIdentity: "@akeru",
+ connectedAt: NOW,
+ sentMessageIds: [],
+ };
+ const harness = makeHarness({
+ bots: [makeBot(BOT_ID, { channelBindings: [binding] })],
+ startTransport: async () => {
+ throw new Error("invalid secret value must not be stored in health");
+ },
+ });
+
+ await expect(restoreConnectedChannels(harness.dependencies)).resolves.toHaveLength(1);
+ expect(harness.readModel().bots[0]?.channelBindings[0]).toMatchObject({
+ status: "failed",
+ lastError: "Connection restore failed. Reconnect with updated credentials.",
+ });
+ });
+
it.effect("stops every live transport on bot archive events without stopping restored bots", () =>
Effect.gen(function* () {
let stops = 0;
@@ -846,6 +1509,8 @@ describe("channel runtime", () => {
expect(starts).toBe(3);
expect(stops).toBe(3);
expect(harness.readModel().bots[0]?.channelBindings?.[0]?.status).toBe("disconnected");
+ expect(harness.secrets.size).toBe(1);
+ await detachChannelConnection(harness.dependencies, BOT_ID, "telegram");
expect(harness.secrets.size).toBe(0);
});
@@ -861,7 +1526,13 @@ describe("channel runtime", () => {
provider: "telegram",
token: "telegram-token",
});
- await attachChannelConnection(harness.dependencies, BOT_ID, connectionId, "telegram");
+ await attachChannelConnection(
+ harness.dependencies,
+ BOT_ID,
+ connectionId,
+ PROJECT_ID,
+ "telegram",
+ );
expect(harness.readSettings().channelConnections).toEqual([
{
id: connectionId,
@@ -885,17 +1556,20 @@ describe("channel runtime", () => {
provider: "telegram",
token: "changed-token",
}),
- ).rejects.toThrow("Disconnect this channel before editing it");
+ ).rejects.toThrow("Unassign this channel before editing it");
await expect(deleteChannelConnection(harness.dependencies, connectionId)).rejects.toThrow(
- "Disconnect this channel",
+ "Unassign this channel",
);
await stopChannelsForBot(BOT_ID);
await reconnectChannel(harness.dependencies, BOT_ID, "telegram");
await disconnectChannel(harness.dependencies, BOT_ID, "telegram");
- await expect(reconnectChannel(harness.dependencies, BOT_ID, "telegram")).rejects.toThrow(
- "No active telegram channel",
+ await reconnectChannel(harness.dependencies, BOT_ID, "telegram");
+ await disconnectChannel(harness.dependencies, BOT_ID, "telegram");
+ await expect(deleteChannelConnection(harness.dependencies, connectionId)).rejects.toThrow(
+ "Unassign this channel before deleting it",
);
+ await detachChannelConnection(harness.dependencies, BOT_ID, "telegram");
expect(harness.secrets.size).toBe(1);
await deleteChannelConnection(harness.dependencies, connectionId);
expect(harness.secrets.size).toBe(0);
@@ -1027,7 +1701,7 @@ describe("channel runtime", () => {
it("sends an approved WhatsApp reply to the inbound DM", async () => {
const messageId = MessageId.make("whatsapp-reply");
const externalThreadId = "whatsapp:phone-number-id:15551234567";
- const threadId = channelThreadId(BOT_ID, "whatsapp", externalThreadId);
+ const threadId = channelThreadId(BOT_ID, PROJECT_ID, "whatsapp", externalThreadId);
const posts: Array<{ readonly externalThreadId: string; readonly text: string }> = [];
const harness = makeHarness({
threads: [
@@ -1100,6 +1774,33 @@ describe("channel runtime", () => {
expect(posts).toBe(1);
});
+ it("rejects a reply after its channel moves to another project", async () => {
+ const threadId = ThreadId.make("old-project-reply");
+ const messageId = MessageId.make("old-project-assistant");
+ let posts = 0;
+ const harness = makeHarness({
+ threads: [
+ makeThread(threadId, BOT_ID, [
+ makeMessage(MessageId.make("old-project-request"), "user", "Question", {
+ provider: "telegram",
+ externalThreadId: "telegram:old-project-chat",
+ }),
+ makeMessage(messageId, "assistant", "Answer"),
+ ]),
+ ],
+ post: async () => void (posts += 1),
+ });
+ await connectChannel(harness.dependencies, {
+ ...telegramConnect(BOT_ID),
+ targetProjectId: SECOND_PROJECT_ID,
+ });
+
+ await expect(
+ sendChannelMessage(harness.dependencies, { botId: BOT_ID, threadId, messageId }),
+ ).rejects.toThrow("previous channel project assignment");
+ expect(posts).toBe(0);
+ });
+
it("does not send a local turn to an earlier channel conversation", async () => {
const turnId = TurnId.make("turn-local-after-channel");
const inboundMessageId = MessageId.make("inbound-before-local-turn");
@@ -1183,7 +1884,7 @@ describe("channel runtime", () => {
await connectChannel(harness.dependencies, telegramConnect(BOT_ID));
failRemove = true;
- await expect(disconnectChannel(harness.dependencies, BOT_ID, "telegram")).rejects.toThrow(
+ await expect(detachChannelConnection(harness.dependencies, BOT_ID, "telegram")).rejects.toThrow(
"secret remove failed",
);
@@ -1194,6 +1895,26 @@ describe("channel runtime", () => {
expect(stops).toBe(0);
});
+ it("restores the direct credential when unassign persistence fails", async () => {
+ let stops = 0;
+ const harness = makeHarness({
+ failBotUpdate: (index) => (index === 2 ? new Error("binding write failed") : undefined),
+ shutdown: async () => void (stops += 1),
+ });
+ await connectChannel(harness.dependencies, telegramConnect(BOT_ID));
+ const credentials = [...harness.secrets.entries()];
+
+ await expect(detachChannelConnection(harness.dependencies, BOT_ID, "telegram")).rejects.toThrow(
+ "binding write failed",
+ );
+
+ expect([...harness.secrets.entries()]).toEqual(credentials);
+ const binding = harness.readModel().bots[0]?.channelBindings[0];
+ expect(binding?.status).toBe("connected");
+ expect(binding && channelBindingsForRuntime([binding])).toEqual([binding]);
+ expect(stops).toBe(0);
+ });
+
it("rejects one Telegram token bound to two active bots", async () => {
const secondId = BotId.make("bot-2");
const harness = makeHarness({ bots: [makeBot(BOT_ID), makeBot(secondId)] });
@@ -1233,7 +1954,257 @@ describe("channel runtime", () => {
).toHaveLength(1);
});
- it("releases a failed post so explicit approval can retry", async () => {
+ it.each([
+ { status: 200, data: { ok: false, error: "missing_scope", detail: "secret-token" } },
+ { status: 200, data: { ok: false, error: "channel_not_found" } },
+ { status: 200, data: { ok: false, error: "invalid_auth" } },
+ { status: 200, data: { ok: false, error: "ratelimited" } },
+ { status: 429, data: {}, headers: { "retry-after": "1" } },
+ ])(
+ "retries a verified Slack API rejection through the shipped post wrapper: %j",
+ async (response) => {
+ const { harness, input } = makeAdapterDeliveryHarness("slack", "slack:C123:1");
+ externalAdapters.slackResponses.push(response, { status: 200, data: { ok: true, ts: "2" } });
+ await connectChannel(harness.dependencies, slackConnect(BOT_ID));
+ expect(externalAdapters.slackRetryOptions).toEqual({
+ retries: 0,
+ rejectRateLimitedCalls: true,
+ });
+ const failedPost = sendChannelMessage(harness.dependencies, input);
+ await expect(failedPost).rejects.toMatchObject({
+ name: "ChannelPostRejectedError",
+ message: "The channel rejected this reply. Correct the channel problem, then retry.",
+ });
+ await expect(failedPost).rejects.not.toHaveProperty("cause");
+ expect(harness.readModel().bots[0]?.channelBindings[0]?.lastError).not.toContain(
+ "secret-token",
+ );
+ await sendChannelMessage(harness.dependencies, input);
+ await sendChannelMessage(harness.dependencies, input);
+ expect(externalAdapters.slackPostRequests).toBe(2);
+ expect(harness.readModel().bots[0]?.channelBindings[0]?.lastError).toBeUndefined();
+ },
+ );
+
+ it.each([
+ new Error("timeout with secret-token; channel_not_found"),
+ { status: 200, data: { ok: false, error: "internal_error", detail: "secret-token" } },
+ { status: 200, data: { ok: false, error: "request_timeout" } },
+ { status: 503, data: "secret-token" },
+ ])("retains an ambiguous Slack post without SDK retries: %j", async (response) => {
+ const { harness, input } = makeAdapterDeliveryHarness("slack", "slack:C123:1");
+ externalAdapters.slackResponses.push(response);
+ await connectChannel(harness.dependencies, slackConnect(BOT_ID));
+ const failedPost = sendChannelMessage(harness.dependencies, input);
+ await expect(failedPost).rejects.toMatchObject({
+ message:
+ "This channel reply has an unfinished delivery attempt. Check the channel before sending another reply.",
+ });
+ await expect(failedPost).rejects.not.toHaveProperty("cause");
+ await disconnectChannel(harness.dependencies, BOT_ID, "slack");
+ expect(harness.readModel().bots[0]?.channelBindings[0]?.lastError).toContain(
+ "Check the channel",
+ );
+ await reconnectChannel(harness.dependencies, BOT_ID, "slack");
+ expect(harness.readModel().bots[0]?.channelBindings[0]?.lastError).toContain(
+ "Check the channel",
+ );
+ await expect(sendChannelMessage(harness.dependencies, input)).rejects.toThrow(
+ "unfinished delivery attempt",
+ );
+ expect(externalAdapters.slackPostRequests).toBe(1);
+ expect(harness.readModel().bots[0]?.channelBindings[0]?.sentMessageIds).toEqual([]);
+ });
+
+ it.each([
+ { status: 400, code: 50035 },
+ { status: 401, code: 50014 },
+ { status: 403, code: 50013 },
+ { status: 404, code: 10003 },
+ { status: 429, code: 20028 },
+ ])(
+ "retries a verified Discord API rejection through the shipped post wrapper: %j",
+ async ({ status, code }) => {
+ const { harness, input } = makeAdapterDeliveryHarness("discord", "discord:123:456");
+ const fetch = vi
+ .fn<typeof globalThis.fetch>()
+ .mockResolvedValueOnce(Response.json({ code, message: "secret-token" }, { status }))
+ .mockResolvedValueOnce(Response.json({ id: "discord-sent" }));
+ vi.stubGlobal("fetch", fetch);
+ await connectChannel(harness.dependencies, discordConnect(BOT_ID));
+ await expect(sendChannelMessage(harness.dependencies, input)).rejects.toThrow(
+ ChannelPostRejectedError,
+ );
+ expect(harness.readModel().bots[0]?.channelBindings[0]?.lastError).not.toContain(
+ "secret-token",
+ );
+ await sendChannelMessage(harness.dependencies, input);
+ await sendChannelMessage(harness.dependencies, input);
+ expect(fetch).toHaveBeenCalledTimes(2);
+ expect(fetch.mock.calls[0]?.[0]).toBe("https://discord.com/api/v10/channels/456/messages");
+ },
+ );
+
+ it.each([
+ new Error("timeout secret-token; DiscordApiError 403"),
+ { status: 503, body: { code: 50013, message: "secret-token" } },
+ { status: 403, body: { message: "secret-token" } },
+ { status: 400, body: { code: 99999, message: "secret-token" } },
+ { status: 408, body: { code: 50035, message: "secret-token" } },
+ ])(
+ "retains an unverified Discord failure through the shipped post wrapper: %j",
+ async (failure) => {
+ const { harness, input } = makeAdapterDeliveryHarness("discord", "discord:123:456");
+ const fetch = vi.fn<typeof globalThis.fetch>();
+ if (failure instanceof Error) fetch.mockRejectedValue(failure);
+ else fetch.mockResolvedValue(Response.json(failure.body, { status: failure.status }));
+ vi.stubGlobal("fetch", fetch);
+ await connectChannel(harness.dependencies, discordConnect(BOT_ID));
+ await expect(sendChannelMessage(harness.dependencies, input)).rejects.toThrow(
+ "This channel reply has an unfinished delivery attempt. Check the channel before sending another reply.",
+ );
+ await expect(sendChannelMessage(harness.dependencies, input)).rejects.toThrow(
+ "unfinished delivery attempt",
+ );
+ expect(fetch).toHaveBeenCalledTimes(1);
+ expect(harness.readModel().bots[0]?.channelBindings[0]?.sentMessageIds).toEqual([]);
+ },
+ );
+
+ it.each([401, 403, 404, 429])(
+ "retries a verified Telegram %i rejection through the shipped post wrapper",
+ async (status) => {
+ const { harness, input } = makeAdapterDeliveryHarness("telegram", "telegram:123");
+ const sends = mockTelegramDelivery([
+ Response.json({ ok: false, error_code: status, description: "secret-token" }, { status }),
+ Response.json({
+ ok: true,
+ result: {
+ message_id: 101,
+ date: 1,
+ chat: { id: 123, type: "private" },
+ text: "Reply",
+ from: { id: 1, is_bot: true, first_name: "Akeru" },
+ },
+ }),
+ ]);
+ await connectChannel(harness.dependencies, telegramConnect(BOT_ID));
+ await expect(sendChannelMessage(harness.dependencies, input)).rejects.toThrow(
+ ChannelPostRejectedError,
+ );
+ expect(harness.readModel().bots[0]?.channelBindings[0]?.lastError).not.toContain(
+ "secret-token",
+ );
+ await sendChannelMessage(harness.dependencies, input);
+ await sendChannelMessage(harness.dependencies, input);
+ expect(sends).toHaveBeenCalledTimes(2);
+ },
+ );
+
+ it.each([
+ new Error("network timeout secret-token"),
+ Response.json({ ok: false, error_code: 500, description: "secret-token" }, { status: 500 }),
+ Response.json({ ok: false, error_code: 400, description: "secret-token" }, { status: 400 }),
+ ])(
+ "retains an unverified Telegram failure through the shipped post wrapper: %j",
+ async (response) => {
+ const { harness, input } = makeAdapterDeliveryHarness("telegram", "telegram:123");
+ const sends = mockTelegramDelivery([response]);
+ await connectChannel(harness.dependencies, telegramConnect(BOT_ID));
+ await expect(sendChannelMessage(harness.dependencies, input)).rejects.toThrow(
+ "This channel reply has an unfinished delivery attempt. Check the channel before sending another reply.",
+ );
+ await expect(sendChannelMessage(harness.dependencies, input)).rejects.toThrow(
+ "unfinished delivery attempt",
+ );
+ expect(sends).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ it("retains a partial WhatsApp post when a later chunk is rejected", async () => {
+ const { harness, input } = makeAdapterDeliveryHarness(
+ "whatsapp",
+ "whatsapp:phone-number-id:15551234567",
+ "x".repeat(5000),
+ );
+ const fetch = vi
+ .fn<typeof globalThis.fetch>()
+ .mockResolvedValueOnce(Response.json({ messages: [{ id: "first-chunk" }] }))
+ .mockResolvedValueOnce(
+ Response.json({ error: { code: 190, message: "secret-token" } }, { status: 401 }),
+ );
+ vi.stubGlobal("fetch", fetch);
+ await connectChannel(harness.dependencies, whatsappConnect(BOT_ID));
+ await expect(sendChannelMessage(harness.dependencies, input)).rejects.toThrow(
+ "This channel reply has an unfinished delivery attempt. Check the channel before sending another reply.",
+ );
+ await expect(sendChannelMessage(harness.dependencies, input)).rejects.toThrow(
+ "unfinished delivery attempt",
+ );
+ expect(fetch).toHaveBeenCalledTimes(2);
+ expect(harness.readModel().bots[0]?.channelBindings[0]?.sentMessageIds).toEqual([]);
+ });
+
+ it("retries a definite provider rejection and serializes concurrent approvals", async () => {
+ const messageId = MessageId.make("message-definite-rejection");
+ const threadId = ThreadId.make("thread-definite-rejection");
+ let posts = 0;
+ const harness = makeHarness({
+ threads: [
+ makeThread(threadId, BOT_ID, [
+ makeMessage(MessageId.make("inbound-definite-rejection"), "user", "Question", {
+ provider: "telegram",
+ externalThreadId: "chat-definite-rejection",
+ }),
+ makeMessage(messageId, "assistant", "Send once"),
+ ]),
+ ],
+ post: async () => {
+ posts += 1;
+ if (posts === 1) throw new ChannelPostRejectedError("provider rejected secret-token");
+ },
+ });
+ await connectChannel(harness.dependencies, telegramConnect(BOT_ID));
+ const input = { botId: BOT_ID, threadId, messageId };
+ await expect(sendChannelMessage(harness.dependencies, input)).rejects.toThrow(
+ ChannelPostRejectedError,
+ );
+ expect(harness.readModel().bots[0]?.channelBindings[0]?.lastError).toBe(
+ "The channel rejected this reply. Correct the channel problem, then retry.",
+ );
+ await Promise.all(
+ Array.from({ length: 8 }, () => sendChannelMessage(harness.dependencies, input)),
+ );
+ expect(posts).toBe(2);
+ expect(harness.readModel().bots[0]?.channelBindings[0]?.sentMessageIds).toEqual([messageId]);
+ });
+
+ it("serializes normal concurrent approvals with the delivery store as the authority", async () => {
+ const messageId = MessageId.make("message-concurrent");
+ const threadId = ThreadId.make("thread-concurrent");
+ let posts = 0;
+ const harness = makeHarness({
+ threads: [
+ makeThread(threadId, BOT_ID, [
+ makeMessage(MessageId.make("inbound-concurrent"), "user", "Question", {
+ provider: "telegram",
+ externalThreadId: "chat-concurrent",
+ }),
+ makeMessage(messageId, "assistant", "Send once"),
+ ]),
+ ],
+ post: async () => void (posts += 1),
+ });
+ await connectChannel(harness.dependencies, telegramConnect(BOT_ID));
+ const input = { botId: BOT_ID, threadId, messageId };
+ await Promise.all(
+ Array.from({ length: 8 }, () => sendChannelMessage(harness.dependencies, input)),
+ );
+ expect(posts).toBe(1);
+ expect(harness.readModel().bots[0]?.channelBindings[0]?.sentMessageIds).toEqual([messageId]);
+ });
+
+ it("retains an ambiguous post after reconnect so explicit approval cannot repost", async () => {
const messageId = MessageId.make("message-retry");
const threadId = ThreadId.make("thread-retry");
let posts = 0;
@@ -1249,21 +2220,63 @@ describe("channel runtime", () => {
],
post: async () => {
posts += 1;
- if (posts === 1) throw new Error("transport unavailable");
+ throw new Error("timeout after remote acceptance");
},
});
await connectChannel(harness.dependencies, telegramConnect(BOT_ID));
await expect(
sendChannelMessage(harness.dependencies, { botId: BOT_ID, threadId, messageId }),
- ).rejects.toThrow("transport unavailable");
+ ).rejects.toThrow("timeout after remote acceptance");
+ expect(harness.readModel().bots[0]?.channelBindings[0]).toMatchObject({
+ status: "connected",
+ lastAttemptAt: NOW,
+ lastError:
+ "This channel reply has an unfinished delivery attempt. Check the channel before sending another reply.",
+ });
+ await shutdownAllChannels();
+ await reconnectChannel(harness.dependencies, BOT_ID, "telegram");
await expect(
sendChannelMessage(harness.dependencies, { botId: BOT_ID, threadId, messageId }),
- ).resolves.toBeGreaterThan(0);
- expect(posts).toBe(2);
+ ).rejects.toThrow("unfinished delivery attempt");
+ expect(harness.readModel().bots[0]?.channelBindings[0]?.lastError).toContain(
+ "Check the channel",
+ );
+ expect(posts).toBe(1);
+ expect(harness.readModel().bots[0]?.channelBindings[0]?.sentMessageIds).not.toContain(
+ messageId,
+ );
});
- it("does not mark or repost an unresolved failed delivery", async () => {
+ it("releases a pre-transport failure so approval can retry after reconnect", async () => {
+ const messageId = MessageId.make("message-before-transport");
+ const threadId = ThreadId.make("thread-before-transport");
+ let posts = 0;
+ const harness = makeHarness({
+ threads: [
+ makeThread(threadId, BOT_ID, [
+ makeMessage(MessageId.make("inbound-before-transport"), "user", "Question", {
+ provider: "telegram",
+ externalThreadId: "chat-before-transport",
+ }),
+ makeMessage(messageId, "assistant", "Send once"),
+ ]),
+ ],
+ post: async () => void (posts += 1),
+ });
+ await connectChannel(harness.dependencies, telegramConnect(BOT_ID));
+ await shutdownAllChannels();
+
+ await expect(
+ sendChannelMessage(harness.dependencies, { botId: BOT_ID, threadId, messageId }),
+ ).rejects.toThrow("needs reconnect");
+ expect(posts).toBe(0);
+ await reconnectChannel(harness.dependencies, BOT_ID, "telegram");
+ await sendChannelMessage(harness.dependencies, { botId: BOT_ID, threadId, messageId });
+ expect(posts).toBe(1);
+ });
+
+ it("does not mark, release, or repost an unresolved failed delivery", async () => {
const messageId = MessageId.make("message-release-failed");
const threadId = ThreadId.make("thread-release-failed");
let status: "requested" | "sent" | undefined;
@@ -1299,7 +2312,7 @@ describe("channel runtime", () => {
await expect(
sendChannelMessage(harness.dependencies, { botId: BOT_ID, threadId, messageId }),
- ).rejects.toThrow("release failed");
+ ).rejects.toThrow("post failed");
await expect(
sendChannelMessage(harness.dependencies, { botId: BOT_ID, threadId, messageId }),
).rejects.toThrow("unfinished delivery attempt");
@@ -1354,6 +2367,46 @@ describe("channel runtime", () => {
expect(markAttempts).toBe(2);
});
+ it.effect("repairs a missing delivery record from sent binding evidence without reposting", () =>
+ Effect.gen(function* () {
+ const messageId = MessageId.make("message-sent-evidence");
+ const threadId = ThreadId.make("thread-sent-evidence");
+ let posts = 0;
+ const harness = makeHarness({
+ threads: [
+ makeThread(threadId, BOT_ID, [
+ makeMessage(MessageId.make("inbound-sent-evidence"), "user", "Question", {
+ provider: "telegram",
+ externalThreadId: "chat-sent-evidence",
+ }),
+ makeMessage(messageId, "assistant", "Send once"),
+ ]),
+ ],
+ post: async () => void (posts += 1),
+ });
+ yield* Effect.promise(() => connectChannel(harness.dependencies, telegramConnect(BOT_ID)));
+ yield* Effect.promise(() =>
+ sendChannelMessage(harness.dependencies, { botId: BOT_ID, threadId, messageId }),
+ );
+ const deliveryStore = makeMemoryChannelDeliveryStore();
+ const restored = { ...harness.dependencies, deliveryStore };
+ yield* Effect.promise(() =>
+ sendChannelMessage(restored, { botId: BOT_ID, threadId, messageId }),
+ );
+ expect(posts).toBe(1);
+ expect(
+ yield* deliveryStore.claim({
+ messageId,
+ botId: BOT_ID,
+ threadId,
+ provider: "telegram",
+ externalThreadId: "chat-sent-evidence",
+ requestedAt: NOW,
+ }),
+ ).toBe("sent");
+ }),
+ );
+
it("fills the sent binding on retry after binding persistence fails", async () => {
const messageId = MessageId.make("message-binding-retry");
const threadId = ThreadId.make("thread-binding-retry");
@@ -1384,4 +2437,45 @@ describe("channel runtime", () => {
expect(posts).toBe(1);
expect(harness.readModel().bots[0]?.channelBindings[0]?.sentMessageIds).toContain(messageId);
});
+
+ it("bounds sent-message recovery metadata", async () => {
+ const threadId = ThreadId.make("thread-recovery-bound");
+ const messages: OrchestrationMessage[] = [];
+ const assistantIds: MessageId[] = [];
+ for (let index = 0; index < CHANNEL_SENT_MESSAGE_RECOVERY_LIMIT + 2; index += 1) {
+ messages.push(
+ makeMessage(MessageId.make(`inbound-${index}`), "user", `Question ${index}`, {
+ provider: "telegram",
+ externalThreadId: "chat-recovery-bound",
+ }),
+ );
+ const assistantId = MessageId.make(`assistant-${index}`);
+ assistantIds.push(assistantId);
+ messages.push(makeMessage(assistantId, "assistant", `Answer ${index}`));
+ }
+ let posts = 0;
+ const harness = makeHarness({
+ threads: [makeThread(threadId, BOT_ID, messages)],
+ post: async () => void (posts += 1),
+ });
+ await connectChannel(harness.dependencies, telegramConnect(BOT_ID));
+
+ for (const messageId of assistantIds) {
+ await sendChannelMessage(harness.dependencies, { botId: BOT_ID, threadId, messageId });
+ }
+
+ const sent = harness.readModel().bots[0]?.channelBindings[0]?.sentMessageIds ?? [];
+ expect(sent).toHaveLength(CHANNEL_SENT_MESSAGE_RECOVERY_LIMIT);
+ expect(sent).not.toContain(assistantIds[0]);
+ expect(sent).toContain(assistantIds.at(-1));
+ await sendChannelMessage(harness.dependencies, {
+ botId: BOT_ID,
+ threadId,
+ messageId: assistantIds[0]!,
+ });
+ expect(posts).toBe(assistantIds.length);
+ expect(harness.readModel().bots[0]?.channelBindings[0]?.sentMessageIds).toHaveLength(
+ CHANNEL_SENT_MESSAGE_RECOVERY_LIMIT,
+ );
+ });
});
diff --git a/apps/server/src/channels/ChannelRuntime.ts b/apps/server/src/channels/ChannelRuntime.ts
index bb83c6cc6..2d0a9926e 100644
--- a/apps/server/src/channels/ChannelRuntime.ts
+++ b/apps/server/src/channels/ChannelRuntime.ts
@@ -1,14 +1,18 @@
import * as NodeCrypto from "node:crypto";
+import { createDiscordAdapter } from "@chat-adapter/discord";
+import { createSlackAdapter } from "@chat-adapter/slack";
import { createMemoryState } from "@chat-adapter/state-memory";
import { createWhatsAppAdapter } from "@chat-adapter/whatsapp";
import { TelegramProvider } from "@mastra/telegram";
import { createiMessageAdapter } from "@photon-ai/chat-adapter-imessage";
import {
BotId,
+ CHANNEL_PROVIDERS,
ChannelConnectionId,
CommandId,
MessageId,
+ ProjectId,
ProviderInstanceId,
ThreadId,
TurnId,
@@ -20,7 +24,7 @@ import {
type OrchestrationReadModel,
type OrchestrationThread,
} from "@t3tools/contracts";
-import { type Adapter, Chat } from "chat";
+import { type Adapter, Chat, type Message, type Thread } from "chat";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import type * as Option from "effect/Option";
@@ -33,10 +37,133 @@ import type { ServerSettingsService } from "../serverSettings.ts";
import type * as OrchestrationEngine from "../orchestration/Services/OrchestrationEngine.ts";
import type { ChannelDeliveryStoreShape } from "./ChannelDeliveryStore.ts";
+/** Transport adapters must confirm that no part of the reply was accepted before using this error. */
+export class ChannelPostRejectedError extends Error {
+ override readonly name = "ChannelPostRejectedError";
+}
+
+const channelDeliveryUnknownError =
+ "This channel reply has an unfinished delivery attempt. Check the channel before sending another reply.";
+const channelDeliveryRejectedError =
+ "The channel rejected this reply. Correct the channel problem, then retry.";
+
+const isSlackPostRejection = Schema.is(
+ Schema.Union([
+ Schema.Struct({
+ code: Schema.Literal("slack_webapi_platform_error"),
+ data: Schema.Struct({
+ ok: Schema.Literal(false),
+ error: Schema.Literals([
+ "channel_not_found",
+ "not_in_channel",
+ "is_archived",
+ "missing_scope",
+ "no_permission",
+ "invalid_auth",
+ "not_authed",
+ "token_revoked",
+ "account_inactive",
+ "msg_too_long",
+ "no_text",
+ "restricted_action",
+ ]),
+ }),
+ }),
+ Schema.Struct({ code: Schema.Literal("slack_webapi_rate_limited_error") }),
+ Schema.Struct({
+ name: Schema.Literal("AdapterRateLimitError"),
+ adapter: Schema.Literal("slack"),
+ code: Schema.Literal("RATE_LIMITED"),
+ }),
+ ]),
+);
+
+const isDiscordPostRejection = Schema.is(
+ Schema.Struct({
+ name: Schema.Literal("NetworkError"),
+ adapter: Schema.Literal("discord"),
+ code: Schema.Literal("NETWORK_ERROR"),
+ originalError: Schema.Struct({
+ name: Schema.Literal("DiscordApiError"),
+ status: Schema.Literals([400, 401, 403, 404, 429]),
+ code: Schema.Literals([10003, 10008, 50001, 50013, 50014, 50035, 20028, 20029]),
+ }),
+ }),
+);
+
+const isTelegramPostRejection = Schema.is(
+ Schema.Union([
+ Schema.Struct({
+ name: Schema.Literal("AuthenticationError"),
+ adapter: Schema.Literal("telegram"),
+ code: Schema.Literal("AUTH_FAILED"),
+ }),
+ Schema.Struct({
+ name: Schema.Literal("PermissionError"),
+ adapter: Schema.Literal("telegram"),
+ code: Schema.Literal("PERMISSION_DENIED"),
+ action: Schema.Literal("sendMessage"),
+ }),
+ Schema.Struct({
+ name: Schema.Literal("ResourceNotFoundError"),
+ adapter: Schema.Literal("telegram"),
+ code: Schema.Literal("NOT_FOUND"),
+ resourceType: Schema.Literal("sendMessage"),
+ }),
+ Schema.Struct({
+ name: Schema.Literal("AdapterRateLimitError"),
+ adapter: Schema.Literal("telegram"),
+ code: Schema.Literal("RATE_LIMITED"),
+ }),
+ ]),
+);
+
+async function postChannelText(
+ chat: Chat,
+ provider: ChannelProvider,
+ threadId: string,
+ text: string,
+) {
+ const outcome = await chat
+ .thread(threadId)
+ .post(text)
+ .then(
+ () => "sent" as const,
+ (cause: unknown) => {
+ // These classifiers cover text-only posts, not partial attachment batches.
+ const rejected =
+ cause instanceof Error &&
+ (provider === "slack"
+ ? isSlackPostRejection(cause)
+ : provider === "discord"
+ ? isDiscordPostRejection(cause)
+ : provider === "telegram"
+ ? isTelegramPostRejection(cause)
+ : false);
+ return rejected ? ("rejected" as const) : ("unknown" as const);
+ },
+ );
+ // Provider errors can contain credentials. Do not retain their messages or causes.
+ if (outcome === "rejected") throw new ChannelPostRejectedError(channelDeliveryRejectedError);
+ if (outcome === "unknown") throw new Error(channelDeliveryUnknownError);
+}
+
interface ChannelRuntimeEntry {
readonly post: (externalThreadId: string, text: string) => Promise<void>;
readonly shutdown: () => Promise<void>;
readonly webhook?: (request: Request) => Promise<Response>;
+ readonly react?: (
+ externalThreadId: string,
+ externalMessageId: string,
+ emoji: string,
+ ) => Promise<void>;
+ readonly removeReaction?: (
+ externalThreadId: string,
+ externalMessageId: string,
+ emoji: string,
+ ) => Promise<void>;
+ readonly clearThreadStatus?: (threadId: ThreadId) => Promise<void>;
+ readonly isHealthy?: () => boolean;
}
interface StartedChannel {
@@ -46,14 +173,17 @@ interface StartedChannel {
interface InboundChannelMessage {
readonly externalThreadId: string;
+ readonly externalMessageId?: string;
readonly externalSenderId?: string;
+ readonly externalSenderName?: string;
readonly text: string;
}
interface ChannelTransportContext {
readonly botName: string;
- readonly subscribedIMessageGroupIds: ReadonlyArray<string>;
- readonly onIMessageGroupMessage: (input: InboundChannelMessage) => Promise<void>;
+ readonly subscribedThreadIds: ReadonlyArray<string>;
+ readonly onMention: (input: InboundChannelMessage) => Promise<void>;
+ readonly onSubscribedMessage: (input: InboundChannelMessage) => Promise<void>;
}
type LiveProvider = ChannelProvider;
@@ -86,7 +216,10 @@ const runtimes = new Map<string, ChannelRuntimeEntry>();
const inboundQueues = new Map<string, Promise<void>>();
const bindingQueues = new Map<string, Promise<void>>();
const operationQueues = new Map<string, Promise<void>>();
-const iMessageGroupContextLimit = 20;
+export const CHANNEL_SENT_MESSAGE_RECOVERY_LIMIT = 128;
+export const CHANNEL_MENTION_CONTEXT_LIMIT = 10;
+export const CHANNEL_MENTION_CONTEXT_CHARACTER_LIMIT = 8_000;
+const gatewayRenewalDurationMs = 60 * 60 * 1_000;
const encoder = new TextEncoder();
const decoder = new TextDecoder();
@@ -108,6 +241,17 @@ const StoredChannelSecret = Schema.Union([
phoneNumberId: Schema.String,
verifyToken: Schema.String,
}),
+ Schema.Struct({
+ provider: Schema.Literal("slack"),
+ botToken: Schema.String,
+ appToken: Schema.String,
+ }),
+ Schema.Struct({
+ provider: Schema.Literal("discord"),
+ botToken: Schema.String,
+ applicationId: Schema.String,
+ publicKey: Schema.String,
+ }),
]);
type StoredChannelSecret = typeof StoredChannelSecret.Type;
const decodeStoredChannelSecret = Schema.decodeUnknownEffect(StoredChannelSecret);
@@ -121,13 +265,43 @@ const connectionSecretName = (connectionId: ChannelConnectionId) =>
export const channelThreadId = (
botId: BotId,
+ projectId: ProjectId,
provider: LiveProvider,
externalThreadId: string,
): ThreadId =>
ThreadId.make(
- `channel-${NodeCrypto.createHash("sha256").update(`${botId}\0${provider}\0${externalThreadId}`).digest("hex")}`,
+ `channel-${NodeCrypto.createHash("sha256")
+ .update(`${botId}\0${projectId}\0${provider}\0${externalThreadId}`)
+ .digest("hex")}`,
);
+const legacyChannelThreadId = (
+ botId: BotId,
+ provider: LiveProvider,
+ externalThreadId: string,
+): ThreadId =>
+ ThreadId.make(
+ `channel-${NodeCrypto.createHash("sha256")
+ .update(`${botId}\0${provider}\0${externalThreadId}`)
+ .digest("hex")}`,
+ );
+
+const deterministicChannelId = (
+ prefix: string,
+ input: {
+ readonly botId: BotId;
+ readonly projectId: ProjectId;
+ readonly provider: ChannelProvider;
+ readonly externalThreadId: string;
+ readonly externalMessageId: string;
+ },
+) =>
+ `${prefix}-${NodeCrypto.createHash("sha256")
+ .update(
+ `${input.botId}\0${input.projectId}\0${input.provider}\0${input.externalThreadId}\0${input.externalMessageId}`,
+ )
+ .digest("hex")}`;
+
export const WHATSAPP_WEBHOOK_PATH = "/api/channels/whatsapp/:botId/webhook";
export async function handleWhatsAppWebhook(botId: BotId, request: Request): Promise<Response> {
@@ -154,28 +328,68 @@ export const whatsAppWebhookRouteLayer = Layer.merge(
HttpRouter.add("POST", WHATSAPP_WEBHOOK_PATH, whatsAppWebhookHttpHandler),
);
-const isIMessageDirectThread = (externalThreadId: string) => externalThreadId.includes(";-;");
-
-const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+const normalizedInboundMessage = (
+ thread: Thread,
+ message: Message,
+ text = message.text,
+): InboundChannelMessage => ({
+ externalThreadId: thread.id,
+ externalMessageId: message.id,
+ externalSenderId: message.author.userId,
+ externalSenderName: message.author.fullName || message.author.userName,
+ text,
+});
-const iMessageGroupTrigger = (botName: string) =>
- new RegExp(`(?:^|[^\\p{L}\\p{N}_])@${escapeRegExp(botName)}(?=$|[^\\p{L}\\p{N}_-])`, "iu");
+export async function mentionWithContext(
+ thread: Thread,
+ message: Message,
+): Promise<InboundChannelMessage> {
+ await thread.refresh().catch(() => undefined);
+ const context = thread.recentMessages
+ .filter(
+ (candidate) =>
+ candidate.id !== message.id &&
+ candidate.author.isBot !== true &&
+ candidate.author.isMe !== true &&
+ candidate.text.trim(),
+ )
+ .slice(-CHANNEL_MENTION_CONTEXT_LIMIT)
+ .map(
+ (candidate) =>
+ `${candidate.author.fullName || candidate.author.userName || candidate.author.userId}: ${candidate.text}`,
+ );
+ const boundedContext = context.join("\n").slice(-CHANNEL_MENTION_CONTEXT_CHARACTER_LIMIT);
+ return normalizedInboundMessage(
+ thread,
+ message,
+ boundedContext.length === 0 ? message.text : `${boundedContext}\n${message.text}`,
+ );
+}
-function subscribedIMessageGroupIds(
+async function subscribedExternalThreadIds(
+ dependencies: ChannelRuntimeDependencies,
model: OrchestrationReadModel,
botId: BotId,
-): ReadonlyArray<string> {
+ projectId: ProjectId,
+ provider: ChannelProvider,
+): Promise<ReadonlyArray<string>> {
+ const candidateIds = model.threads.flatMap((thread) =>
+ thread.botId === botId &&
+ thread.projectId === projectId &&
+ thread.groupId === null &&
+ thread.deletedAt === null
+ ? [thread.id]
+ : [],
+ );
+ const threads = await Promise.all(
+ candidateIds.map((threadId) => dependencies.readThread(threadId)),
+ );
const ids = new Set<string>();
- for (const thread of model.threads) {
- if (thread.botId !== botId || thread.groupId !== null || thread.deletedAt !== null) continue;
+ for (const thread of threads) {
+ if (!thread) continue;
for (const message of thread.messages) {
- const origin = message.channelOrigin;
- if (
- origin?.provider === "imessage" &&
- !isIMessageDirectThread(origin.externalThreadId) &&
- thread.id === channelThreadId(botId, "imessage", origin.externalThreadId)
- ) {
- ids.add(origin.externalThreadId);
+ if (message.channelOrigin?.provider === provider) {
+ ids.add(message.channelOrigin.externalThreadId);
}
}
}
@@ -184,8 +398,10 @@ function subscribedIMessageGroupIds(
export function channelBindingsForRuntime(
bindings: ReadonlyArray<ChannelBinding>,
- isRunning: (botId: BotId, provider: ChannelProvider) => boolean = (botId, provider) =>
- runtimes.has(runtimeKey(botId, provider)),
+ isRunning: (botId: BotId, provider: ChannelProvider) => boolean = (botId, provider) => {
+ const runtime = runtimes.get(runtimeKey(botId, provider));
+ return runtime !== undefined && (runtime.isHealthy?.() ?? true);
+ },
): ReadonlyArray<ChannelBinding> {
return bindings.map((binding) =>
binding.status === "connected" && !isRunning(binding.botId, binding.provider)
@@ -197,6 +413,17 @@ export function channelBindingsForRuntime(
const randomId = async (dependencies: ChannelRuntimeDependencies, prefix: string) =>
`${prefix}-${await dependencies.randomUuid()}`;
+const channelProviderName = (provider: ChannelProvider) =>
+ provider === "imessage"
+ ? "iMessage"
+ : provider === "whatsapp"
+ ? "WhatsApp"
+ : provider === "telegram"
+ ? "Telegram"
+ : provider === "slack"
+ ? "Slack"
+ : "Discord";
+
async function loadSecret(
dependencies: ChannelRuntimeDependencies,
botId: BotId,
@@ -222,83 +449,133 @@ async function loadConnectionSecret(
const storedSecretFromInput = (
input: ChannelConnectInput | ChannelConnectionSaveInput,
-): StoredChannelSecret =>
- input.provider === "telegram"
- ? { provider: "telegram", token: input.token }
- : input.provider === "whatsapp"
- ? {
- provider: "whatsapp",
- accessToken: input.accessToken,
- appSecret: input.appSecret,
- phoneNumberId: input.phoneNumberId,
- verifyToken: input.verifyToken,
- }
- : input.mode === "hosted"
- ? {
- provider: "imessage",
- mode: "hosted",
- projectId: input.projectId,
- projectSecret: input.projectSecret,
- }
- : {
- provider: "imessage",
- mode: "self-hosted",
- serverUrl: input.serverUrl,
- apiKey: input.apiKey,
- ...(input.phone ? { phone: input.phone } : {}),
- };
+): StoredChannelSecret => {
+ if (input.provider === "telegram") return { provider: "telegram", token: input.token };
+ if (input.provider === "whatsapp") {
+ return {
+ provider: "whatsapp",
+ accessToken: input.accessToken,
+ appSecret: input.appSecret,
+ phoneNumberId: input.phoneNumberId,
+ verifyToken: input.verifyToken,
+ };
+ }
+ if (input.provider === "slack") {
+ return { provider: "slack", botToken: input.botToken, appToken: input.appToken };
+ }
+ if (input.provider === "discord") {
+ return {
+ provider: "discord",
+ botToken: input.botToken,
+ applicationId: input.applicationId,
+ publicKey: input.publicKey,
+ };
+ }
+ return input.mode === "hosted"
+ ? {
+ provider: "imessage",
+ mode: "hosted",
+ projectId: input.projectId,
+ projectSecret: input.projectSecret,
+ }
+ : {
+ provider: "imessage",
+ mode: "self-hosted",
+ serverUrl: input.serverUrl,
+ apiKey: input.apiKey,
+ ...(input.phone ? { phone: input.phone } : {}),
+ };
+};
const connectInputFromSecret = (
botId: BotId,
+ targetProjectId: ProjectId,
commandId: CommandId,
secret: StoredChannelSecret,
-): ChannelConnectInput =>
- secret.provider === "telegram"
- ? { type: "channel.connect", commandId, botId, provider: "telegram", token: secret.token }
- : secret.provider === "whatsapp"
- ? {
- type: "channel.connect",
- commandId,
- botId,
- provider: "whatsapp",
- accessToken: secret.accessToken,
- appSecret: secret.appSecret,
- phoneNumberId: secret.phoneNumberId,
- verifyToken: secret.verifyToken,
- }
- : secret.mode === "hosted" && secret.projectId && secret.projectSecret
- ? {
- type: "channel.connect",
- commandId,
- botId,
- provider: "imessage",
- mode: "hosted",
- projectId: secret.projectId,
- projectSecret: secret.projectSecret,
- }
- : secret.mode === "self-hosted" && secret.serverUrl && secret.apiKey
- ? {
- type: "channel.connect",
- commandId,
- botId,
- provider: "imessage",
- mode: "self-hosted",
- serverUrl: secret.serverUrl,
- apiKey: secret.apiKey,
- ...(secret.phone ? { phone: secret.phone } : {}),
- }
- : (() => {
- throw new Error("Saved channel credentials are incomplete.");
- })();
-
-const channelSecretIdentity = (secret: StoredChannelSecret): string =>
- secret.provider === "telegram"
- ? `telegram:${secret.token}`
- : secret.provider === "whatsapp"
- ? `whatsapp:${secret.phoneNumberId}`
- : secret.mode === "hosted"
- ? `imessage:hosted:${secret.projectId ?? ""}`
- : `imessage:self-hosted:${secret.serverUrl ?? ""}:${secret.phone ?? ""}`;
+): ChannelConnectInput => {
+ if (secret.provider === "telegram") {
+ return {
+ type: "channel.connect",
+ commandId,
+ botId,
+ targetProjectId,
+ provider: "telegram",
+ token: secret.token,
+ };
+ }
+ if (secret.provider === "whatsapp") {
+ return {
+ type: "channel.connect",
+ commandId,
+ botId,
+ targetProjectId,
+ provider: "whatsapp",
+ accessToken: secret.accessToken,
+ appSecret: secret.appSecret,
+ phoneNumberId: secret.phoneNumberId,
+ verifyToken: secret.verifyToken,
+ };
+ }
+ if (secret.provider === "slack") {
+ return {
+ type: "channel.connect",
+ commandId,
+ botId,
+ targetProjectId,
+ provider: "slack",
+ botToken: secret.botToken,
+ appToken: secret.appToken,
+ };
+ }
+ if (secret.provider === "discord") {
+ return {
+ type: "channel.connect",
+ commandId,
+ botId,
+ targetProjectId,
+ provider: "discord",
+ botToken: secret.botToken,
+ applicationId: secret.applicationId,
+ publicKey: secret.publicKey,
+ };
+ }
+ if (secret.mode === "hosted" && secret.projectId && secret.projectSecret) {
+ return {
+ type: "channel.connect",
+ commandId,
+ botId,
+ targetProjectId,
+ provider: "imessage",
+ mode: "hosted",
+ projectId: secret.projectId,
+ projectSecret: secret.projectSecret,
+ };
+ }
+ if (secret.mode === "self-hosted" && secret.serverUrl && secret.apiKey) {
+ return {
+ type: "channel.connect",
+ commandId,
+ botId,
+ targetProjectId,
+ provider: "imessage",
+ mode: "self-hosted",
+ serverUrl: secret.serverUrl,
+ apiKey: secret.apiKey,
+ ...(secret.phone ? { phone: secret.phone } : {}),
+ };
+ }
+ throw new Error("Saved channel credentials are incomplete.");
+};
+
+const channelSecretIdentity = (secret: StoredChannelSecret): string => {
+ if (secret.provider === "telegram") return `telegram:${secret.token}`;
+ if (secret.provider === "whatsapp") return `whatsapp:${secret.phoneNumberId}`;
+ if (secret.provider === "slack") return `slack:${secret.botToken}`;
+ if (secret.provider === "discord") return `discord:${secret.applicationId}`;
+ return secret.mode === "hosted"
+ ? `imessage:hosted:${secret.projectId ?? ""}`
+ : `imessage:self-hosted:${secret.serverUrl ?? ""}:${secret.phone ?? ""}`;
+};
async function assertChannelIdentityAvailable(
dependencies: ChannelRuntimeDependencies,
@@ -309,7 +586,10 @@ async function assertChannelIdentityAvailable(
for (const bot of model.bots) {
if (bot.id === botId || bot.archivedAt !== null) continue;
for (const binding of bot.channelBindings ?? []) {
- if (binding.provider !== candidateSecret.provider || binding.status === "disconnected") {
+ if (
+ binding.provider !== candidateSecret.provider ||
+ (binding.status === "disconnected" && !binding.connectionId)
+ ) {
continue;
}
const secret = binding.connectionId
@@ -326,14 +606,22 @@ export async function dispatchInboundChannelMessage(
dependencies: ChannelRuntimeDependencies,
input: {
readonly botId: BotId;
+ readonly projectId: ProjectId;
readonly provider: LiveProvider;
readonly externalThreadId: string;
+ readonly externalMessageId?: string;
readonly externalSenderId?: string;
+ readonly externalSenderName?: string;
readonly text: string;
},
): Promise<void> {
- const threadId = channelThreadId(input.botId, input.provider, input.externalThreadId);
- const previous = inboundQueues.get(threadId) ?? Promise.resolve();
+ const preferredThreadId = channelThreadId(
+ input.botId,
+ input.projectId,
+ input.provider,
+ input.externalThreadId,
+ );
+ const previous = inboundQueues.get(preferredThreadId) ?? Promise.resolve();
const next = previous
.catch(() => undefined)
.then(async () => {
@@ -342,8 +630,23 @@ export async function dispatchInboundChannelMessage(
(candidate) => candidate.id === input.botId && candidate.archivedAt === null,
);
if (!bot) throw new Error(`Bot '${input.botId}' is unavailable.`);
- const project = model.projects.find((candidate) => candidate.deletedAt === null);
- if (!project) throw new Error("A project is required before a channel can start a turn.");
+ const project = model.projects.find(
+ (candidate) => candidate.id === input.projectId && candidate.deletedAt === null,
+ );
+ if (!project) {
+ const binding = bot.channelBindings.find(
+ (entry) => entry.provider === input.provider && entry.projectId === input.projectId,
+ );
+ if (binding) {
+ await replaceBinding(dependencies, {
+ ...binding,
+ status: "failed",
+ lastAttemptAt: await dependencies.nowIso(),
+ lastError: "The selected project is unavailable. Choose another project.",
+ }).catch(() => undefined);
+ }
+ throw new Error("The channel project is unavailable.");
+ }
const modelSelection = bot.engine
? {
instanceId: ProviderInstanceId.make(bot.engine.provider),
@@ -354,15 +657,24 @@ export async function dispatchInboundChannelMessage(
if (!modelSelection)
throw new Error(`Bot '${bot.name}' needs a model before channel messages.`);
+ const legacyThreadId = legacyChannelThreadId(
+ input.botId,
+ input.provider,
+ input.externalThreadId,
+ );
const existing = model.threads.find(
- (thread) => thread.id === threadId && thread.deletedAt === null,
+ (thread) =>
+ (thread.id === preferredThreadId || thread.id === legacyThreadId) &&
+ thread.projectId === input.projectId &&
+ thread.deletedAt === null,
);
+ const threadId = existing?.id ?? preferredThreadId;
const createdAt = await dependencies.nowIso();
if (!existing) {
await Effect.runPromise(
dependencies.engine.dispatch({
type: "thread.create",
- commandId: CommandId.make(await randomId(dependencies, "channel-create")),
+ commandId: CommandId.make(`channel-create-${threadId}`),
threadId,
projectId: project.id,
botId: bot.id,
@@ -376,26 +688,51 @@ export async function dispatchInboundChannelMessage(
createdAt,
}),
);
- } else if (existing.botId !== bot.id || existing.groupId != null) {
+ } else if (
+ existing.botId !== bot.id ||
+ existing.groupId != null ||
+ existing.projectId !== project.id
+ ) {
throw new Error(`Channel thread '${threadId}' belongs to another owner.`);
}
+ const deterministicInput = input.externalMessageId
+ ? {
+ botId: input.botId,
+ projectId: input.projectId,
+ provider: input.provider,
+ externalThreadId: input.externalThreadId,
+ externalMessageId: input.externalMessageId,
+ }
+ : null;
+ const commandId = CommandId.make(
+ deterministicInput
+ ? deterministicChannelId("channel-turn", deterministicInput)
+ : await randomId(dependencies, "channel-turn"),
+ );
+ const messageId = MessageId.make(
+ deterministicInput
+ ? deterministicChannelId("channel-message", deterministicInput)
+ : await randomId(dependencies, "channel-message"),
+ );
await Effect.runPromise(
dependencies.engine.dispatch({
type: "thread.turn.start",
- commandId: CommandId.make(await randomId(dependencies, "channel-turn")),
+ commandId,
threadId,
message: {
- messageId: MessageId.make(await randomId(dependencies, "channel-message")),
+ messageId,
role: "user",
text: input.text,
attachments: [],
channelOrigin: {
provider: input.provider,
externalThreadId: input.externalThreadId,
+ ...(input.externalMessageId ? { externalMessageId: input.externalMessageId } : {}),
...(input.externalSenderId ? { externalSenderId: input.externalSenderId } : {}),
},
},
+ ...(input.externalSenderName ? { senderDisplayName: input.externalSenderName } : {}),
modelSelection,
runtimeMode: bot.runtimeMode,
interactionMode: "default",
@@ -403,14 +740,17 @@ export async function dispatchInboundChannelMessage(
}),
);
});
- inboundQueues.set(threadId, next);
+ inboundQueues.set(preferredThreadId, next);
try {
await next;
} finally {
- if (inboundQueues.get(threadId) === next) inboundQueues.delete(threadId);
+ if (inboundQueues.get(preferredThreadId) === next) inboundQueues.delete(preferredThreadId);
}
}
+const boundedSentMessageIds = (messageIds: ReadonlyArray<MessageId>) =>
+ messageIds.slice(-CHANNEL_SENT_MESSAGE_RECOVERY_LIMIT);
+
async function replaceBinding(
dependencies: ChannelRuntimeDependencies,
binding: ChannelBinding,
@@ -427,10 +767,18 @@ async function replaceBinding(
);
const nextBinding = {
...binding,
- sentMessageIds:
- binding.sentMessageIds.length > 0
+ ...(binding.projectId &&
+ binding.projectId === previousBinding?.projectId &&
+ previousBinding.lastError === channelDeliveryUnknownError
+ ? { lastError: channelDeliveryUnknownError }
+ : {}),
+ sentMessageIds: boundedSentMessageIds(
+ binding.status === "disconnected" && !binding.connectionId
? binding.sentMessageIds
- : (previousBinding?.sentMessageIds ?? []),
+ : binding.sentMessageIds.length > 0
+ ? binding.sentMessageIds
+ : (previousBinding?.sentMessageIds ?? []),
+ ),
};
const receipt = await Effect.runPromise(
dependencies.engine.dispatch({
@@ -524,26 +872,60 @@ async function stopRuntime(botId: BotId, provider: ChannelProvider): Promise<voi
export async function stopChannelsForBot(botId: BotId): Promise<void> {
await Promise.allSettled(
- (["telegram", "imessage", "whatsapp"] as const).map((provider) =>
+ CHANNEL_PROVIDERS.map((provider) =>
withChannelOperation(botId, provider, () => stopRuntime(botId, provider)),
),
);
}
+export async function clearChannelThreadStatuses(threadId: ThreadId): Promise<void> {
+ await Promise.allSettled(
+ [...runtimes.entries()].map(([key, runtime]) => {
+ const separator = key.lastIndexOf(":");
+ const botId = BotId.make(key.slice(0, separator));
+ const provider = CHANNEL_PROVIDERS.find((value) => value === key.slice(separator + 1));
+ return provider
+ ? withChannelOperation(botId, provider, async () => {
+ if (runtimes.get(key) === runtime) await runtime.clearThreadStatus?.(threadId);
+ })
+ : Promise.resolve();
+ }),
+ );
+}
+
export const stopArchivedBotChannels = (events: Stream.Stream<OrchestrationEvent>) =>
Stream.runForEach(events, (event) =>
event.type === "bot.archived"
? Effect.promise(() => stopChannelsForBot(event.payload.botId))
- : Effect.void,
+ : event.type === "thread.deleted" || event.type === "thread.archived"
+ ? Effect.promise(() => clearChannelThreadStatuses(event.payload.threadId))
+ : Effect.void,
);
export async function shutdownAllChannels(): Promise<void> {
- const entries = [...runtimes.values()];
- runtimes.clear();
- inboundQueues.clear();
- bindingQueues.clear();
- operationQueues.clear();
- await Promise.allSettled(entries.map((entry) => entry.shutdown()));
+ await Promise.allSettled(
+ [...runtimes.entries()].map(([key, entry]) => {
+ const separator = key.lastIndexOf(":");
+ const botId = BotId.make(key.slice(0, separator));
+ const provider = CHANNEL_PROVIDERS.find((value) => value === key.slice(separator + 1));
+ return provider
+ ? withChannelOperation(botId, provider, async () => {
+ if (runtimes.get(key) !== entry) return;
+ runtimes.delete(key);
+ await entry.shutdown();
+ })
+ : Promise.resolve();
+ }),
+ );
+}
+
+async function initializeChannelChat(chat: Chat): Promise<void> {
+ try {
+ await chat.initialize();
+ } catch (cause) {
+ await chat.shutdown().catch(() => undefined);
+ throw cause;
+ }
}
async function startTelegram(
@@ -557,23 +939,21 @@ async function startTelegram(
const installation = await provider.getInstallation(botId);
const adapter = provider.getAdapter(connected.installationId);
if (!installation || !adapter) throw new Error("Telegram did not create an active adapter.");
- if (!adapter.botUserId) throw new Error("Telegram did not identify the connected bot.");
- const activeAdapter = Object.assign(adapter, { botUserId: adapter.botUserId });
const chat = new Chat({
userName: installation.username ?? "Akeru Bot",
- adapters: { telegram: activeAdapter },
+ adapters: { telegram: adapter as Adapter },
state: createMemoryState(),
});
chat.onDirectMessage(async (thread, message) => {
if (!message.text.trim()) return;
- await onDirectMessage({
- externalThreadId: thread.id,
- externalSenderId: message.author.userId,
- text: message.text,
- });
+ await onDirectMessage(normalizedInboundMessage(thread, message));
});
try {
- await chat.initialize();
+ await initializeChannelChat(chat);
+ if (!adapter.botUserId) {
+ await chat.shutdown();
+ throw new Error("Telegram did not identify the connected bot.");
+ }
} catch (cause) {
await provider.disconnect(botId).catch(() => undefined);
throw cause;
@@ -581,7 +961,7 @@ async function startTelegram(
return {
externalIdentity: installation.username ? `@${installation.username}` : botId,
runtime: {
- post: async (externalThreadId, text) => void (await chat.thread(externalThreadId).post(text)),
+ post: (externalThreadId, text) => postChannelText(chat, "telegram", externalThreadId, text),
shutdown: async () => {
await chat.shutdown();
await provider.disconnect(botId).catch(() => undefined);
@@ -590,6 +970,75 @@ async function startTelegram(
};
}
+export async function startRenewingGateway(
+ start: (
+ waitUntil: (task: Promise<unknown>) => void,
+ durationMs: number,
+ signal: AbortSignal,
+ ) => Promise<Response>,
+ label: string,
+): Promise<{
+ readonly shutdown: () => Promise<void>;
+ readonly isHealthy: () => boolean;
+ readonly settled: Promise<void>;
+}> {
+ const abort = new AbortController();
+ let healthy = true;
+ let activeTask: Promise<unknown> | undefined;
+ let startedAt = 0;
+ const launch = async () => {
+ activeTask = undefined;
+ startedAt = performance.now();
+ const response = await start(
+ (task) => {
+ activeTask = task;
+ },
+ gatewayRenewalDurationMs,
+ abort.signal,
+ );
+ if (!response.ok || !activeTask) {
+ throw new Error(`${label} failed with status ${response.status}.`);
+ }
+ return { task: activeTask };
+ };
+ const firstTask = (await launch()).task;
+ const supervisor = (async () => {
+ let task = firstTask;
+ while (!abort.signal.aborted) {
+ await task;
+ if (!abort.signal.aborted) {
+ if (performance.now() - startedAt < gatewayRenewalDurationMs) {
+ throw new Error(`${label} stopped before its renewal deadline.`);
+ }
+ task = (await launch()).task;
+ }
+ }
+ })().catch(() => {
+ healthy = false;
+ });
+ return {
+ isHealthy: () => healthy,
+ settled: supervisor,
+ shutdown: async () => {
+ healthy = false;
+ abort.abort();
+ await supervisor;
+ },
+ };
+}
+
+function registerThreadedHandlers(chat: Chat, context: ChannelTransportContext) {
+ chat.onNewMention(async (thread, message) => {
+ if (!message.text.trim()) return;
+ await thread.subscribe();
+ await context.onMention(await mentionWithContext(thread, message));
+ });
+ chat.onSubscribedMessage(async (thread, message) => {
+ if (!message.text.trim()) return;
+ await context.onSubscribedMessage(normalizedInboundMessage(thread, message));
+ });
+}
+
async function startIMessage(
input: Extract<ChannelConnectInput, { readonly provider: "imessage" }>,
context: ChannelTransportContext,
@@ -611,46 +1060,17 @@ async function startIMessage(
});
chat.onDirectMessage(async (thread, message) => {
if (!message.text.trim()) return;
- await onDirectMessage({
- externalThreadId: thread.id,
- externalSenderId: message.author.userId,
- text: message.text,
- });
- });
- const onGroupMessage = async (
- thread: Parameters<Parameters<typeof chat.onSubscribedMessage>[0]>[0],
- message: Parameters<Parameters<typeof chat.onSubscribedMessage>[0]>[1],
- ) => {
- if (adapter.isDM(thread.id) || !message.text.trim()) return;
- await context.onIMessageGroupMessage({
- externalThreadId: thread.id,
- externalSenderId: message.author.userId,
- text: message.text,
- });
- };
- chat.onNewMention(async (thread, message) => {
- if (adapter.isDM(thread.id)) return;
- await thread.subscribe();
- await onGroupMessage(thread, message);
+ await onDirectMessage(normalizedInboundMessage(thread, message));
});
- chat.onSubscribedMessage(onGroupMessage);
- await chat.initialize();
- await Promise.allSettled(
- context.subscribedIMessageGroupIds.map((externalThreadId) =>
- chat.thread(externalThreadId).subscribe(),
- ),
- );
- const abort = new AbortController();
- const response = await adapter.startGatewayListener(
- { waitUntil: (task) => void task },
- undefined,
- abort.signal,
- );
- if (!response.ok) {
- abort.abort();
+ await initializeChannelChat(chat);
+ const gateway = await startRenewingGateway(
+ (waitUntil, durationMs, signal) =>
+ adapter.startGatewayListener({ waitUntil }, durationMs, signal),
+ "Photon gateway",
+ ).catch(async (cause) => {
await chat.shutdown();
- throw new Error(`Photon gateway failed with status ${response.status}.`);
- }
+ throw cause;
+ });
return {
externalIdentity:
input.mode === "self-hosted" && input.phone
@@ -659,9 +1079,10 @@ async function startIMessage(
? "Photon hosted"
: "Photon self-hosted",
runtime: {
- post: async (externalThreadId, text) => void (await chat.thread(externalThreadId).post(text)),
+ post: (externalThreadId, text) => postChannelText(chat, "imessage", externalThreadId, text),
+ isHealthy: gateway.isHealthy,
shutdown: async () => {
- abort.abort();
+ await gateway.shutdown();
await chat.shutdown();
},
},
@@ -687,17 +1108,13 @@ async function startWhatsApp(
});
chat.onDirectMessage(async (thread, message) => {
if (!message.text.trim()) return;
- await onDirectMessage({
- externalThreadId: thread.id,
- externalSenderId: message.author.userId,
- text: message.text,
- });
+ await onDirectMessage(normalizedInboundMessage(thread, message));
});
- await chat.initialize();
+ await initializeChannelChat(chat);
return {
externalIdentity: input.phoneNumberId,
runtime: {
- post: async (externalThreadId, text) => void (await chat.thread(externalThreadId).post(text)),
+ post: (externalThreadId, text) => postChannelText(chat, "whatsapp", externalThreadId, text),
shutdown: () => chat.shutdown(),
webhook: async (request) => {
const tasks: Promise<unknown>[] = [];
@@ -718,6 +1135,212 @@ async function startWhatsApp(
};
}
+async function startSlack(
+ input: Extract<ChannelConnectInput, { readonly provider: "slack" }>,
+ context: ChannelTransportContext,
+ onDirectMessage: Parameters<NonNullable<ChannelRuntimeDependencies["startTransport"]>>[1],
+): Promise<{ readonly externalIdentity: string; readonly runtime: ChannelRuntimeEntry }> {
+ const adapter = createSlackAdapter({
+ mode: "socket",
+ botToken: input.botToken,
+ appToken: input.appToken,
+ // An internal retry could hide an accepted request behind a later rejection.
+ webClientOptions: { retryConfig: { retries: 0 }, rejectRateLimitedCalls: true },
+ });
+ const state = createMemoryState();
+ await state.connect();
+ await Promise.all(context.subscribedThreadIds.map((threadId) => state.subscribe(threadId)));
+ const chat = new Chat({
+ userName: context.botName,
+ adapters: { slack: adapter as Adapter },
+ state,
+ });
+ chat.onDirectMessage(async (thread, message) => {
+ if (!message.text.trim()) return;
+ await onDirectMessage(normalizedInboundMessage(thread, message));
+ });
+ registerThreadedHandlers(chat, context);
+ await initializeChannelChat(chat);
+ if (!adapter.botUserId) {
+ await chat.shutdown();
+ throw new Error("Slack bot credentials are invalid.");
+ }
+ await Promise.allSettled(
+ context.subscribedThreadIds.map((externalThreadId) =>
+ chat.thread(externalThreadId).subscribe(),
+ ),
+ );
+ return {
+ externalIdentity: adapter.botUserId,
+ runtime: {
+ react: (externalThreadId, externalMessageId, emoji) =>
+ adapter.addReaction(externalThreadId, externalMessageId, emoji),
+ removeReaction: (externalThreadId, externalMessageId, emoji) =>
+ adapter.removeReaction(externalThreadId, externalMessageId, emoji),
+ post: (externalThreadId, text) => postChannelText(chat, "slack", externalThreadId, text),
+ shutdown: () => chat.shutdown(),
+ },
+ };
+}
+
+async function startDiscord(
+ input: Extract<ChannelConnectInput, { readonly provider: "discord" }>,
+ context: ChannelTransportContext,
+ onDirectMessage: Parameters<NonNullable<ChannelRuntimeDependencies["startTransport"]>>[1],
+): Promise<{ readonly externalIdentity: string; readonly runtime: ChannelRuntimeEntry }> {
+ const adapter = createDiscordAdapter({
+ applicationId: input.applicationId,
+ botToken: input.botToken,
+ publicKey: input.publicKey,
+ });
+ const chat = new Chat({
+ userName: context.botName,
+ adapters: { discord: adapter as Adapter },
+ state: createMemoryState(),
+ });
+ chat.onDirectMessage(async (thread, message) => {
+ if (!message.text.trim()) return;
+ await onDirectMessage(normalizedInboundMessage(thread, message));
+ });
+ registerThreadedHandlers(chat, context);
+ await initializeChannelChat(chat);
+ const identity = await adapter.getUser(input.applicationId).catch(async (cause) => {
+ await chat.shutdown().catch(() => undefined);
+ throw cause;
+ });
+ if (!identity) {
+ await chat.shutdown();
+ throw new Error("Discord credentials are invalid.");
+ }
+ await Promise.allSettled(
+ context.subscribedThreadIds.map((externalThreadId) =>
+ chat.thread(externalThreadId).subscribe(),
+ ),
+ );
+ const gateway = await startRenewingGateway(
+ (waitUntil, durationMs, signal) =>
+ adapter.startGatewayListener({ waitUntil }, durationMs, signal),
+ "Discord gateway",
+ ).catch(async (cause) => {
+ await chat.shutdown();
+ throw cause;
+ });
+ return {
+ externalIdentity: `${identity.userName} (${identity.userId})`,
+ runtime: {
+ post: (externalThreadId, text) => postChannelText(chat, "discord", externalThreadId, text),
+ react: (externalThreadId, externalMessageId, emoji) =>
+ adapter.addReaction(externalThreadId, externalMessageId, emoji),
+ removeReaction: (externalThreadId, externalMessageId, emoji) =>
+ adapter.removeReaction(externalThreadId, externalMessageId, emoji),
+ isHealthy: gateway.isHealthy,
+ shutdown: async () => {
+ await gateway.shutdown();
+ await chat.shutdown();
+ },
+ },
+ };
+}
+
+const channelStatusReactions = ["eyes", "white_check_mark", "x"] as const;
+type ChannelOrigin = NonNullable<OrchestrationThread["messages"][number]["channelOrigin"]>;
+type ChannelStatus = {
+ origin: ChannelOrigin;
+ status: (typeof channelStatusReactions)[number];
+ threadId?: ThreadId;
+};
+const channelStatuses = new WeakMap<ChannelRuntimeEntry, Map<string, ChannelStatus>>();
+
+async function updateChannelStatus(
+ runtime: ChannelRuntimeEntry,
+ origin: ChannelOrigin,
+ status?: (typeof channelStatusReactions)[number],
+ threadId?: ThreadId,
+): Promise<void> {
+ if (
+ (origin.provider !== "slack" && origin.provider !== "discord") ||
+ !origin.externalMessageId ||
+ !runtime.removeReaction ||
+ !runtime.react
+ )
+ return;
+ const statuses = channelStatuses.get(runtime) ?? new Map<string, ChannelStatus>();
+ channelStatuses.set(runtime, statuses);
+ const key = JSON.stringify([origin.externalThreadId, origin.externalMessageId]);
+ if (status && statuses.get(key)?.status === status) return;
+ statuses.delete(key);
+ for (const emoji of channelStatusReactions) {
+ await runtime
+ .removeReaction(origin.externalThreadId, origin.externalMessageId, emoji)
+ .catch(() => undefined);
+ }
+ if (status) {
+ if (statuses.size >= CHANNEL_SENT_MESSAGE_RECOVERY_LIMIT) {
+ const oldest = statuses.values().next().value;
+ if (oldest) await updateChannelStatus(runtime, oldest.origin);
+ }
+ await runtime
+ .react(origin.externalThreadId, origin.externalMessageId, status)
+ .catch(() => undefined);
+ statuses.set(key, { origin, status, ...(threadId ? { threadId } : {}) });
+ }
+}
+
+async function clearPersistedChannelStatuses(
+ dependencies: ChannelRuntimeDependencies,
+ runtime: ChannelRuntimeEntry,
+ botId: BotId,
+ provider: ChannelProvider,
+): Promise<void> {
+ if (provider !== "slack" && provider !== "discord") return;
+ const model = await dependencies.readModel();
+ for (const summary of model.threads) {
+ if (summary.botId !== botId) continue;
+ const thread = await dependencies.readThread(summary.id);
+ for (const message of thread?.messages ?? []) {
+ const origin = message.channelOrigin;
+ if (origin?.provider === provider) {
+ await updateChannelStatus(runtime, origin);
+ }
+ }
+ }
+}
+
+export async function finishChannelTurn(
+ dependencies: ChannelRuntimeDependencies,
+ threadId: ThreadId,
+ turnId: TurnId | undefined,
+ state: "completed" | "failed" | "cancelled",
+ requestMessageId?: MessageId,
+): Promise<void> {
+ const thread = await dependencies.readThread(threadId);
+ if (!thread?.botId) return;
+ const botId = thread.botId;
+ const request = requestMessageId
+ ? thread.messages.find((message) => message.id === requestMessageId)
+ : !turnId
+ ? thread.messages.findLast((message) => message.role === "user")
+ : thread.messages.find(
+ (message) =>
+ message.id === thread.latestTurn?.requestMessageId &&
+ thread.latestTurn?.turnId === turnId,
+ );
+ const origin = request?.channelOrigin;
+ if (!origin) return;
+ await withChannelOperation(botId, origin.provider, async () => {
+ const runtime = runtimes.get(runtimeKey(botId, origin.provider));
+ if (!runtime) return;
+ const current = await dependencies.readThread(threadId);
+ if (current?.messages.findLast((message) => message.role === "user")?.id !== request.id) return;
+ await updateChannelStatus(
+ runtime,
+ origin,
+ state === "completed" ? "white_check_mark" : "x",
+ threadId,
+ );
+ });
+}
+
async function startChannel(
dependencies: ChannelRuntimeDependencies,
input: ChannelConnectInput,
@@ -726,64 +1349,103 @@ async function startChannel(
const model = await dependencies.readModel();
const bot = model.bots.find((candidate) => candidate.id === input.botId);
if (!bot || bot.archivedAt !== null) throw new Error(`Bot '${input.botId}' is unavailable.`);
- const onDirectMessage = (message: InboundChannelMessage) =>
- dispatchInboundChannelMessage(dependencies, {
- ...message,
- botId: bot.id,
- provider: input.provider,
- });
- let iMessageGroupContext: ReadonlyArray<InboundChannelMessage> = [];
- const context: ChannelTransportContext = {
- botName: bot.name,
- subscribedIMessageGroupIds:
- input.provider === "imessage" ? subscribedIMessageGroupIds(model, bot.id) : [],
- onIMessageGroupMessage: async (message) => {
- if (input.provider !== "imessage" || isIMessageDirectThread(message.externalThreadId)) {
- return;
- }
- if (!iMessageGroupTrigger(bot.name).test(message.text)) {
- iMessageGroupContext = [...iMessageGroupContext, message].slice(-iMessageGroupContextLimit);
- return;
+ const project = model.projects.find(
+ (candidate) => candidate.id === input.targetProjectId && candidate.deletedAt === null,
+ );
+ if (!project) throw new Error("The selected channel project is unavailable.");
+ let runtime: ChannelRuntimeEntry | undefined;
+ const dispatch = (message: InboundChannelMessage) =>
+ withChannelOperation(bot.id, input.provider, async () => {
+ if (!runtime || runtimes.get(runtimeKey(bot.id, input.provider)) !== runtime) return;
+ const currentModel = await dependencies.readModel();
+ let duplicate = false;
+ if (message.externalMessageId) {
+ for (const summary of currentModel.threads) {
+ if (summary.botId !== bot.id || summary.projectId !== project.id) continue;
+ const thread = await dependencies.readThread(summary.id);
+ duplicate ||=
+ thread?.messages.some(
+ (entry) =>
+ entry.channelOrigin?.provider === input.provider &&
+ entry.channelOrigin.externalThreadId === message.externalThreadId &&
+ entry.channelOrigin.externalMessageId === message.externalMessageId,
+ ) ?? false;
+ }
}
- const recentMessages = iMessageGroupContext.filter(
- (candidate) => candidate.externalThreadId === message.externalThreadId,
- );
await dispatchInboundChannelMessage(dependencies, {
...message,
botId: bot.id,
- provider: "imessage",
- text:
- recentMessages.length === 0
- ? message.text
- : [...recentMessages, message]
- .map(
- (candidate) =>
- `${candidate.externalSenderId ?? "Unknown sender"}: ${candidate.text}`,
- )
- .join("\n"),
+ projectId: project.id,
+ provider: input.provider,
});
- const consumedMessages = new Set(recentMessages);
- iMessageGroupContext = iMessageGroupContext.filter(
- (candidate) => !consumedMessages.has(candidate),
- );
- },
+ if (!duplicate) {
+ for (const { origin } of channelStatuses.get(runtime)?.values() ?? []) {
+ if (origin.externalThreadId === message.externalThreadId)
+ await updateChannelStatus(runtime, origin);
+ }
+ await updateChannelStatus(runtime, { provider: input.provider, ...message }, "eyes");
+ }
+ });
+ const context: ChannelTransportContext = {
+ botName: bot.name,
+ subscribedThreadIds: await subscribedExternalThreadIds(
+ dependencies,
+ model,
+ bot.id,
+ project.id,
+ input.provider,
+ ),
+ onMention: dispatch,
+ onSubscribedMessage: dispatch,
};
const started = dependencies.startTransport
- ? await dependencies.startTransport(input, onDirectMessage, context)
+ ? await dependencies.startTransport(input, dispatch, context)
: input.provider === "telegram"
- ? await startTelegram(bot.id, input.token, onDirectMessage)
+ ? await startTelegram(bot.id, input.token, dispatch)
: input.provider === "imessage"
- ? await startIMessage(input, context, onDirectMessage)
- : await startWhatsApp(input, context, onDirectMessage);
+ ? await startIMessage(input, context, dispatch)
+ : input.provider === "whatsapp"
+ ? await startWhatsApp(input, context, dispatch)
+ : input.provider === "slack"
+ ? await startSlack(input, context, dispatch)
+ : await startDiscord(input, context, dispatch);
+ await clearPersistedChannelStatuses(dependencies, started.runtime, bot.id, input.provider);
+ const clearTrackedStatuses = async (threadId?: ThreadId) => {
+ if (!runtime) return;
+ for (const { origin, threadId: statusThreadId } of channelStatuses.get(runtime)?.values() ??
+ []) {
+ if (
+ !threadId ||
+ threadId === statusThreadId ||
+ channelThreadId(bot.id, project.id, input.provider, origin.externalThreadId) === threadId ||
+ legacyChannelThreadId(bot.id, input.provider, origin.externalThreadId) === threadId
+ ) {
+ await updateChannelStatus(runtime, origin);
+ }
+ }
+ };
+ runtime = {
+ ...started.runtime,
+ clearThreadStatus: clearTrackedStatuses,
+ shutdown: async () => {
+ try {
+ await clearTrackedStatuses();
+ } finally {
+ await started.runtime.shutdown();
+ }
+ },
+ };
return {
- runtime: started.runtime,
+ runtime,
binding: {
botId: bot.id,
...(connectionId ? { connectionId } : {}),
+ projectId: project.id,
provider: input.provider,
status: "connected",
externalIdentity: started.externalIdentity,
connectedAt: await dependencies.nowIso(),
+ lastAttemptAt: await dependencies.nowIso(),
sentMessageIds: [],
},
};
@@ -845,12 +1507,9 @@ export async function saveChannelConnection(
withConnectionOperation(input.connectionId, async () => {
const model = await dependencies.readModel();
const attached = model.bots.some((bot) =>
- (bot.channelBindings ?? []).some(
- (binding) =>
- binding.connectionId === input.connectionId && binding.status !== "disconnected",
- ),
+ (bot.channelBindings ?? []).some((binding) => binding.connectionId === input.connectionId),
);
- if (attached) throw new Error("Disconnect this channel before editing it.");
+ if (attached) throw new Error("Unassign this channel before editing it.");
const secretKey = connectionSecretName(input.connectionId);
const previousSecret = await Effect.runPromise(dependencies.secretStore.get(secretKey));
const settings = await Effect.runPromise(dependencies.settings.getSettings);
@@ -871,7 +1530,14 @@ export async function saveChannelConnection(
}
: {}),
}
- : {}),
+ : input.provider === "slack"
+ ? { managementUrl: "https://api.slack.com/apps" }
+ : input.provider === "discord"
+ ? {
+ externalIdentity: input.applicationId,
+ managementUrl: `https://discord.com/developers/applications/${encodeURIComponent(input.applicationId)}`,
+ }
+ : {}),
};
await Effect.runPromise(
dependencies.secretStore.set(
@@ -916,12 +1582,10 @@ export async function deleteChannelConnection(
const model = await dependencies.readModel();
if (
model.bots.some((bot) =>
- (bot.channelBindings ?? []).some(
- (binding) => binding.connectionId === connectionId && binding.status !== "disconnected",
- ),
+ (bot.channelBindings ?? []).some((binding) => binding.connectionId === connectionId),
)
) {
- throw new Error("Disconnect this channel before deleting it.");
+ throw new Error("Unassign this channel before deleting it.");
}
const secretKey = connectionSecretName(connectionId);
const previousSecret = await Effect.runPromise(dependencies.secretStore.get(secretKey));
@@ -948,22 +1612,56 @@ export async function deleteChannelConnection(
);
}
+/**
+ * The project a bot works in when a channel does not name one. Matches the in-app chat
+ * default: the project with the most recent live activity, then the most recently updated.
+ */
+export function defaultProjectIdForBot(
+ model: Pick<OrchestrationReadModel, "projects" | "threads">,
+ botId: BotId,
+): ProjectId | null {
+ const live = model.projects.filter((project) => project.deletedAt === null);
+ if (live.length === 0) return null;
+ const latestActivity = new Map<ProjectId, string>();
+ for (const thread of model.threads) {
+ if (thread.archivedAt !== null) continue;
+ const previous = latestActivity.get(thread.projectId);
+ if (!previous || thread.updatedAt > previous)
+ latestActivity.set(thread.projectId, thread.updatedAt);
+ }
+ const botThreads = model.threads.filter(
+ (thread) => thread.botId === botId && thread.archivedAt === null,
+ );
+ const botProject = botThreads
+ .toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt))
+ .map((thread) => live.find((project) => project.id === thread.projectId))
+ .find((project) => project !== undefined);
+ if (botProject) return botProject.id;
+ return live.toSorted(
+ (left, right) =>
+ (latestActivity.get(right.id) ?? right.updatedAt).localeCompare(
+ latestActivity.get(left.id) ?? left.updatedAt,
+ ) || left.title.localeCompare(right.title),
+ )[0]!.id;
+}
+
export async function attachChannelConnection(
dependencies: ChannelRuntimeDependencies,
botId: BotId,
connectionId: ChannelConnectionId,
+ requestedProjectId: ProjectId | undefined,
provider: ChannelProvider,
): Promise<number> {
return withConnectionOperation(connectionId, () =>
withChannelOperation(botId, provider, async () => {
const model = await dependencies.readModel();
+ const projectId = requestedProjectId ?? defaultProjectIdForBot(model, botId);
+ if (!projectId) throw new Error("Add a project before connecting a channel.");
const inUse = model.bots.some(
(bot) =>
bot.id !== botId &&
bot.archivedAt === null &&
- (bot.channelBindings ?? []).some(
- (binding) => binding.connectionId === connectionId && binding.status !== "disconnected",
- ),
+ (bot.channelBindings ?? []).some((binding) => binding.connectionId === connectionId),
);
if (inUse) throw new Error("This channel connection is attached to another bot.");
const secret = await loadConnectionSecret(dependencies, connectionId);
@@ -973,7 +1671,7 @@ export async function attachChannelConnection(
const commandId = CommandId.make(await randomId(dependencies, "channel-attach"));
const started = await startChannel(
dependencies,
- connectInputFromSecret(botId, commandId, secret),
+ connectInputFromSecret(botId, projectId, commandId, secret),
connectionId,
);
return commitStartedChannel(dependencies, started);
@@ -991,9 +1689,34 @@ export async function disconnectChannel(
const currentBinding = model.bots
.find((bot) => bot.id === botId)
?.channelBindings?.find((binding) => binding.provider === provider);
+ if (!currentBinding) throw new Error(`No ${provider} channel is assigned to this bot.`);
+ const sequence = await replaceBinding(dependencies, {
+ ...currentBinding,
+ status: "disconnected",
+ connectedAt: null,
+ lastAttemptAt: await dependencies.nowIso(),
+ });
+ await stopRuntime(botId, provider);
+ return sequence;
+ });
+}
+
+export async function detachChannelConnection(
+ dependencies: ChannelRuntimeDependencies,
+ botId: BotId,
+ provider: ChannelProvider,
+): Promise<number> {
+ return withChannelOperation(botId, provider, async () => {
+ const model = await dependencies.readModel();
+ const currentBinding = model.bots
+ .find((bot) => bot.id === botId)
+ ?.channelBindings?.find((binding) => binding.provider === provider);
+ if (!currentBinding) throw new Error(`No ${provider} channel is assigned to this bot.`);
const name = secretName(botId, provider);
- const previousSecret = await Effect.runPromise(dependencies.secretStore.get(name));
- if (!currentBinding?.connectionId) {
+ const previousSecret = currentBinding.connectionId
+ ? undefined
+ : await Effect.runPromise(dependencies.secretStore.get(name));
+ if (!currentBinding.connectionId) {
await Effect.runPromise(dependencies.secretStore.remove(name));
}
let sequence: number;
@@ -1007,7 +1730,7 @@ export async function disconnectChannel(
sentMessageIds: [],
});
} catch (cause) {
- if (previousSecret._tag === "Some") {
+ if (previousSecret?._tag === "Some") {
await Effect.runPromise(dependencies.secretStore.set(name, previousSecret.value)).catch(
() => undefined,
);
@@ -1029,17 +1752,18 @@ export async function reconnectChannel(
const binding = model.bots
.find((bot) => bot.id === botId)
?.channelBindings?.find((candidate) => candidate.provider === provider);
- if (!binding || binding.status === "disconnected") {
- throw new Error(`No active ${provider} channel to reconnect.`);
+ if (!binding) {
+ throw new Error(`No ${provider} channel is assigned to this bot.`);
}
const secret = binding?.connectionId
? await loadConnectionSecret(dependencies, binding.connectionId)
: await loadSecret(dependencies, botId, provider);
if (!secret || secret.provider !== provider)
throw new Error(`No saved ${provider} credentials.`);
+ if (!binding.projectId) throw new Error("Select a project before reconnecting this channel.");
await assertChannelIdentityAvailable(dependencies, botId, secret);
const commandId = CommandId.make(await randomId(dependencies, "channel-reconnect"));
- const input = connectInputFromSecret(botId, commandId, secret);
+ const input = connectInputFromSecret(botId, binding.projectId, commandId, secret);
const started = await startChannel(dependencies, input, binding?.connectionId);
return commitStartedChannel(dependencies, started);
});
@@ -1062,7 +1786,23 @@ export async function restoreConnectedChannels(
);
const results = await Promise.allSettled(
candidates.map(async (candidate) => {
- await reconnectChannel(dependencies, candidate.botId, candidate.provider);
+ try {
+ await reconnectChannel(dependencies, candidate.botId, candidate.provider);
+ } catch {
+ const latest = await dependencies.readModel();
+ const binding = latest.bots
+ .find((bot) => bot.id === candidate.botId)
+ ?.channelBindings?.find((entry) => entry.provider === candidate.provider);
+ if (binding) {
+ await replaceBinding(dependencies, {
+ ...binding,
+ status: "failed",
+ lastAttemptAt: await dependencies.nowIso(),
+ lastError: "Connection restore failed. Reconnect with updated credentials.",
+ }).catch(() => undefined);
+ }
+ throw new Error("Channel restore failed.");
+ }
}),
);
return results.flatMap((result, index) =>
@@ -1097,6 +1837,12 @@ export async function sendChannelMessage(
);
if (!bot || bot.archivedAt !== null || !binding)
throw new Error("Channel binding is unavailable.");
+ if (binding.projectId !== thread.projectId) {
+ throw new Error("This reply belongs to a previous channel project assignment.");
+ }
+ if (binding.status !== "connected") {
+ throw new Error("Reconnect this channel before sending a reply.");
+ }
const claim = await Effect.runPromise(
dependencies.deliveryStore.claim({
messageId: input.messageId,
@@ -1107,21 +1853,35 @@ export async function sendChannelMessage(
requestedAt: await dependencies.nowIso(),
}),
);
+ const unfinishedDeliveryError = channelDeliveryUnknownError;
if (claim === "requested" && !binding.sentMessageIds.includes(input.messageId)) {
- throw new Error("This channel reply has an unfinished delivery attempt.");
+ await replaceBinding(dependencies, {
+ ...binding,
+ lastAttemptAt: await dependencies.nowIso(),
+ lastError: unfinishedDeliveryError,
+ });
+ throw new Error(unfinishedDeliveryError);
}
- if (claim === "claimed") {
+ if (claim === "claimed" && !binding.sentMessageIds.includes(input.messageId)) {
const runtime = runtimes.get(runtimeKey(input.botId, origin.provider));
if (!runtime) {
await Effect.runPromise(dependencies.deliveryStore.releaseRequested(input.messageId));
throw new Error(
- `${origin.provider === "imessage" ? "iMessage" : origin.provider === "whatsapp" ? "WhatsApp" : "Telegram"} needs reconnect before this reply can send.`,
+ `${channelProviderName(origin.provider)} needs reconnect before this reply can send.`,
);
}
try {
await runtime.post(origin.externalThreadId, approvedMessage.text);
} catch (cause) {
- await Effect.runPromise(dependencies.deliveryStore.releaseRequested(input.messageId));
+ const rejected = cause instanceof ChannelPostRejectedError;
+ if (rejected) {
+ await Effect.runPromise(dependencies.deliveryStore.releaseRequested(input.messageId));
+ }
+ await replaceBinding(dependencies, {
+ ...binding,
+ lastAttemptAt: await dependencies.nowIso(),
+ lastError: rejected ? channelDeliveryRejectedError : unfinishedDeliveryError,
+ });
throw cause;
}
try {
@@ -1135,12 +1895,12 @@ export async function sendChannelMessage(
if (!binding.sentMessageIds.includes(input.messageId)) {
await replaceBinding(dependencies, {
...binding,
- sentMessageIds: [...binding.sentMessageIds, input.messageId],
+ sentMessageIds: boundedSentMessageIds([...binding.sentMessageIds, input.messageId]),
});
}
throw cause;
}
- } else if (claim === "requested") {
+ } else if (claim !== "sent") {
await Effect.runPromise(
dependencies.deliveryStore.markSent({
messageId: input.messageId,
@@ -1148,10 +1908,12 @@ export async function sendChannelMessage(
}),
);
}
+ const { lastError, ...sentBinding } = binding;
const sequence = binding.sentMessageIds.includes(input.messageId)
? model.snapshotSequence
: await replaceBinding(dependencies, {
- ...binding,
+ ...sentBinding,
+ ...(lastError && lastError !== channelDeliveryRejectedError ? { lastError } : {}),
sentMessageIds: [...binding.sentMessageIds, input.messageId],
});
return sequence;
diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts
index 9d91150cc..88a3fd87e 100644
--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts
+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts
@@ -1,5 +1,6 @@
import {
AkeruDelegationRecord,
+ AuthSessionId,
CheckpointRef,
EventId,
MessageId,
@@ -415,6 +416,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
id: asMessageId("message-1"),
role: "assistant",
text: "hello from projection",
+ authorPersonId: AuthSessionId.make("person-1"),
+ authorDisplayName: "Leo",
turnId: asTurnId("turn-1"),
respondingBotId: null,
reactions: [],
diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
index a7043a784..62cd23768 100644
--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
@@ -5,6 +5,7 @@ import {
BotId,
BotUsageCap,
ChannelBinding,
+ ChannelMessageOrigin,
ChatAttachment,
CheckpointRef,
GroupMembership,
@@ -115,6 +116,7 @@ const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
);
const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
Struct.assign({
+ channelOrigin: Schema.NullOr(Schema.fromJsonString(ChannelMessageOrigin)),
isStreaming: Schema.Number,
attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))),
reactions: Schema.fromJsonString(Schema.Array(OrchestrationMessageReaction)),
@@ -671,6 +673,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
responding_bot_id AS "respondingBotId",
author_person_id AS "authorPersonId",
author_display_name AS "authorDisplayName",
+ channel_origin_json AS "channelOrigin",
role,
text,
attachments_json AS "attachments",
@@ -1147,6 +1150,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
responding_bot_id AS "respondingBotId",
author_person_id AS "authorPersonId",
author_display_name AS "authorDisplayName",
+ channel_origin_json AS "channelOrigin",
role,
text,
attachments_json AS "attachments",
@@ -1398,6 +1402,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
responding_bot_id AS "respondingBotId",
author_person_id AS "authorPersonId",
author_display_name AS "authorDisplayName",
+ channel_origin_json AS "channelOrigin",
role,
text,
attachments_json AS "attachments",
@@ -1793,6 +1798,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
...(row.attachments !== null ? { attachments: row.attachments } : {}),
turnId: row.turnId,
respondingBotId: row.respondingBotId ?? null,
+ ...(row.authorPersonId ? { authorPersonId: row.authorPersonId } : {}),
+ ...(row.authorDisplayName ? { authorDisplayName: row.authorDisplayName } : {}),
+ ...(row.channelOrigin ? { channelOrigin: row.channelOrigin } : {}),
reactions: row.reactions,
streaming: row.isStreaming === 1,
createdAt: row.createdAt,
@@ -3030,6 +3038,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
text: row.text,
turnId: row.turnId,
respondingBotId: row.respondingBotId ?? null,
+ ...(row.authorPersonId ? { authorPersonId: row.authorPersonId } : {}),
+ ...(row.authorDisplayName ? { authorDisplayName: row.authorDisplayName } : {}),
+ ...(row.channelOrigin ? { channelOrigin: row.channelOrigin } : {}),
reactions: row.reactions,
streaming: row.isStreaming === 1,
createdAt: row.createdAt,
diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts
index c0f91d997..27e23d8fd 100644
--- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts
+++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts
@@ -15,6 +15,7 @@ import {
AkeruUsageReservationId,
BotId,
CommandId,
+ DelegationId,
DEFAULT_PROVIDER_INTERACTION_MODE,
EventId,
MessageId,
@@ -26,6 +27,12 @@ import {
ThreadId,
TurnId,
} from "@t3tools/contracts";
+import * as ChannelRuntime from "../../channels/ChannelRuntime.ts";
+import {
+ ChannelDeliveryStore,
+ ChannelDeliveryStoreLive,
+} from "../../channels/ChannelDeliveryStore.ts";
+import * as ServerSecretStore from "../../auth/ServerSecretStore.ts";
import * as Clock from "effect/Clock";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
@@ -55,6 +62,7 @@ import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import { ServerConfig } from "../../config.ts";
+import { forkParked } from "../../serverActivation.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { BotInboxService } from "../../bot-inbox/service.ts";
@@ -193,7 +201,10 @@ describe("ProviderRuntimeIngestion", () => {
| OrchestrationEngineService
| ProviderRuntimeIngestionService
| ProjectionSnapshotQuery
- | BotUsageLedger,
+ | BotUsageLedger
+ | ServerSecretStore.ServerSecretStore
+ | ServerSettingsService
+ | ChannelDeliveryStore,
unknown
> | null = null;
let scope: Scope.Closeable | null = null;
@@ -206,6 +217,7 @@ describe("ProviderRuntimeIngestion", () => {
}
afterEach(async () => {
+ await ChannelRuntime.shutdownAllChannels();
if (scope) {
await Effect.runPromise(Scope.close(scope, Exit.void));
}
@@ -250,6 +262,8 @@ describe("ProviderRuntimeIngestion", () => {
Layer.provideMerge(SqlitePersistenceMemory),
Layer.provideMerge(BotUsageLedgerLive.pipe(Layer.provide(SqlitePersistenceMemory))),
Layer.provideMerge(Layer.succeed(AgentController, provider.service)),
+ Layer.provideMerge(ChannelDeliveryStoreLive.pipe(Layer.provide(SqlitePersistenceMemory))),
+ Layer.provideMerge(ServerSecretStore.layer),
Layer.provideMerge(makeTestServerSettingsLayer(options?.serverSettings)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), workspaceRoot)),
Layer.provideMerge(NodeServices.layer),
@@ -339,6 +353,65 @@ describe("ProviderRuntimeIngestion", () => {
return {
engine,
dispatch,
+ connectChannel: async (
+ post: (externalThreadId: string, text: string) => Promise<void>,
+ channelProvider: "telegram" | "slack" | "discord" = "telegram",
+ reactions?: {
+ add: (threadId: string, messageId: string, emoji: string) => Promise<void>;
+ remove: (threadId: string, messageId: string, emoji: string) => Promise<void>;
+ },
+ ) => {
+ let nextId = 0;
+ let inbound:
+ | Parameters<NonNullable<ChannelRuntime.ChannelRuntimeDependencies["startTransport"]>>[1]
+ | undefined;
+ const dependencies: ChannelRuntime.ChannelRuntimeDependencies = {
+ engine,
+ secretStore: await runtime!.runPromise(
+ Effect.service(ServerSecretStore.ServerSecretStore),
+ ),
+ settings: await runtime!.runPromise(Effect.service(ServerSettingsService)),
+ deliveryStore: await runtime!.runPromise(Effect.service(ChannelDeliveryStore)),
+ readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()),
+ readThread: async (threadId) =>
+ (await Effect.runPromise(snapshotQuery.getSnapshot())).threads.find(
+ (thread) => thread.id === threadId,
+ ) ?? null,
+ nowIso: async () => createdAt,
+ randomUuid: async () => `channel-test-${++nextId}`,
+ startTransport: async (_input, onMessage) => {
+ inbound = onMessage;
+ return {
+ externalIdentity: "test-channel",
+ runtime: {
+ post,
+ shutdown: async () => {},
+ ...(reactions ? { react: reactions.add, removeReaction: reactions.remove } : {}),
+ },
+ };
+ },
+ };
+ await ChannelRuntime.connectChannel(dependencies, {
+ type: "channel.connect",
+ commandId: CommandId.make("cmd-channel-connect"),
+ botId: BotId.make("bot-akeru"),
+ targetProjectId: asProjectId("project-1"),
+ ...(channelProvider === "telegram"
+ ? ({ provider: "telegram", token: "test-token" } as const)
+ : channelProvider === "slack"
+ ? ({ provider: "slack", botToken: "test-token", appToken: "app-token" } as const)
+ : ({
+ provider: "discord",
+ botToken: "test-token",
+ applicationId: "test-app",
+ publicKey: "test-key",
+ } as const)),
+ });
+ return {
+ dependencies,
+ inbound: (message: Parameters<NonNullable<typeof inbound>>[0]) => inbound!(message),
+ };
+ },
readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()),
emit: provider.emit,
setProviderSession: provider.setSession,
@@ -375,6 +448,379 @@ describe("ProviderRuntimeIngestion", () => {
};
}
+ it.each(["slack", "discord"] as const)(
+ "serializes slow accepted updates before terminal %s status",
+ async (provider) => {
+ const harness = await createHarness({ botOwned: true });
+ const accepted = Promise.withResolvers<void>();
+ const releaseAccepted = Promise.withResolvers<void>();
+ const terminalPersisted = Promise.withResolvers<void>();
+ const signals = new Set<string>();
+ const channel = await harness.connectChannel(async () => {}, provider, {
+ add: async (_thread, _message, emoji) => {
+ if (emoji === "eyes") {
+ accepted.resolve();
+ await releaseAccepted.promise;
+ }
+ signals.add(emoji);
+ },
+ remove: async (_thread, _message, emoji) => {
+ signals.delete(emoji);
+ },
+ });
+ const threadId = ChannelRuntime.channelThreadId(
+ BotId.make("bot-akeru"),
+ asProjectId("project-1"),
+ provider,
+ `${provider}:race`,
+ );
+ await Effect.runPromise(
+ forkParked(
+ Stream.runForEach(harness.engine.streamDomainEvents, (event) =>
+ Effect.sync(() => {
+ if (
+ event.type === "thread.session-set" &&
+ event.payload.threadId === threadId &&
+ event.payload.session.status === "ready"
+ )
+ terminalPersisted.resolve();
+ }),
+ ),
+ ).pipe(Scope.provide(scope!)),
+ );
+ const inbound = channel.inbound({
+ externalThreadId: `${provider}:race`,
+ externalMessageId: "race-request",
+ text: "Question",
+ });
+ await accepted.promise;
+ const base = {
+ provider: ProviderDriverKind.make("codex"),
+ threadId,
+ turnId: asTurnId("race-turn"),
+ createdAt: "2026-01-01T00:00:02.000Z",
+ };
+ try {
+ harness.emit({
+ ...base,
+ eventId: asEventId("race-started"),
+ type: "turn.started",
+ payload: {},
+ });
+ await harness.drain();
+ harness.emit({
+ ...base,
+ eventId: asEventId("race-completed"),
+ type: "turn.completed",
+ payload: { state: "completed" },
+ });
+ await terminalPersisted.promise;
+ expect([...signals]).toEqual([]);
+ } finally {
+ releaseAccepted.resolve();
+ }
+ await inbound;
+ await harness.drain();
+ expect([...signals]).toEqual(["white_check_mark"]);
+ await ChannelRuntime.shutdownAllChannels();
+ expect([...signals]).toEqual([]);
+ },
+ );
+
+ it.each(
+ (["slack", "discord", "telegram"] as const).flatMap((provider) =>
+ (["completed", "failed", "cancelled", "aborted", "exited", "error", "stopped"] as const).map(
+ (state) => ({ provider, state }),
+ ),
+ ),
+ )(
+ "clears accepted status through shipped ingestion: $provider $state",
+ async ({ provider, state }) => {
+ const harness = await createHarness({ botOwned: true });
+ const signals = new Set<string>();
+ const calls: string[] = [];
+ const posts: string[] = [];
+ const channel = await harness.connectChannel(
+ async (_target, text) => {
+ posts.push(text);
+ },
+ provider,
+ {
+ add: async (_thread, _message, emoji) => {
+ signals.add(emoji);
+ calls.push(`add:${emoji}`);
+ },
+ remove: async (_thread, _message, emoji) => {
+ signals.delete(emoji);
+ calls.push(`remove:${emoji}`);
+ },
+ },
+ );
+ const message = {
+ externalThreadId: `${provider}:owner`,
+ externalMessageId: "request-1",
+ text: "Question",
+ };
+ await channel.inbound(message);
+ expect([...signals]).toEqual(provider === "telegram" ? [] : ["eyes"]);
+ const threadId = ChannelRuntime.channelThreadId(
+ BotId.make("bot-akeru"),
+ asProjectId("project-1"),
+ provider,
+ message.externalThreadId,
+ );
+ const turnId = asTurnId("status-turn");
+ const base = {
+ provider: ProviderDriverKind.make("codex"),
+ threadId,
+ turnId,
+ createdAt: "2026-01-01T00:00:02.000Z",
+ };
+ harness.emit({
+ ...base,
+ eventId: asEventId("status-started"),
+ type: "turn.started",
+ payload: {},
+ });
+ await harness.drain();
+ const terminal =
+ state === "aborted"
+ ? {
+ ...base,
+ eventId: asEventId("status-terminal"),
+ type: "turn.aborted" as const,
+ payload: {},
+ }
+ : state === "exited"
+ ? {
+ ...base,
+ eventId: asEventId("status-terminal"),
+ type: "session.exited" as const,
+ payload: {},
+ }
+ : state === "error" || state === "stopped"
+ ? {
+ ...base,
+ eventId: asEventId("status-terminal"),
+ type: "session.state.changed" as const,
+ payload: { state },
+ }
+ : {
+ ...base,
+ eventId: asEventId("status-terminal"),
+ type: "turn.completed" as const,
+ payload: { state },
+ };
+ harness.emit(terminal);
+ await harness.drain();
+ expect([...signals]).toEqual(
+ provider === "telegram" ? [] : [state === "completed" ? "white_check_mark" : "x"],
+ );
+ expect(posts).toEqual(
+ state === "completed" ? ["I finished without a text response. Please try again."] : [],
+ );
+ const completedCalls = [...calls];
+ harness.emit({ ...terminal, eventId: asEventId("status-terminal-replay") });
+ await harness.drain();
+ await channel.inbound(message);
+ expect(calls).toEqual(completedCalls);
+ await ChannelRuntime.disconnectChannel(
+ channel.dependencies,
+ BotId.make("bot-akeru"),
+ provider,
+ );
+ expect([...signals]).toEqual([]);
+ if (provider === "telegram") expect(calls).toEqual([]);
+ },
+ );
+
+ it.each([
+ ["completed", "completed"],
+ ["failed", "completed"],
+ ["cancelled", "completed"],
+ ["completed", "failed"],
+ ["completed", "cancelled"],
+ ] as const)(
+ "replies once only for a completed owner: child %s, owner %s",
+ async (childState, ownerState) => {
+ const harness = await createHarness({ botOwned: true });
+ const posts: Array<{ target: string; text: string }> = [];
+ await harness.connectChannel(async (target, text) => {
+ posts.push({ target, text });
+ });
+ const createdAt = "2026-01-01T00:00:01.000Z";
+ const ownerThreadId = asThreadId("thread-1");
+ const childThreadId = asThreadId("delegated-child");
+ const ownerTurnId = asTurnId("owner-turn");
+ const childTurnId = asTurnId("child-turn");
+ await harness.dispatch({
+ type: "bot.create",
+ commandId: CommandId.make("cmd-child-bot"),
+ botId: BotId.make("bot-child"),
+ name: "Child",
+ title: "Research bot",
+ avatar: { kind: "dither", seed: "child" },
+ engine: { provider: ProviderInstanceId.make("codex"), model: "gpt-5-codex" },
+ sandbox: null,
+ runtimeMode: "approval-required",
+ usageCap: null,
+ groupId: null,
+ createdAt,
+ });
+ await harness.dispatch({
+ type: "thread.create",
+ commandId: CommandId.make("cmd-child-create"),
+ threadId: childThreadId,
+ projectId: asProjectId("project-1"),
+ botId: BotId.make("bot-child"),
+ title: "Delegated work",
+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" },
+ interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
+ runtimeMode: "approval-required",
+ branch: null,
+ worktreePath: null,
+ createdAt,
+ });
+ await harness.dispatch({
+ type: "delegation.create",
+ commandId: CommandId.make("cmd-delegation-create"),
+ delegation: {
+ delegationId: DelegationId.make("channel-delegation"),
+ parentDelegationId: null,
+ parentBotId: BotId.make("bot-akeru"),
+ childBotId: BotId.make("bot-child"),
+ parentThreadId: ownerThreadId,
+ childThreadId,
+ parentTurnId: ownerTurnId,
+ childTurnId,
+ ancestorBotIds: [BotId.make("bot-akeru")],
+ depth: 1,
+ task: "Research the answer",
+ expectedResult: "A concise answer",
+ deadline: null,
+ access: {
+ allowedToolIds: ["Read"],
+ memoryScopes: [],
+ sandbox: "local",
+ runtimeMode: "approval-required",
+ hasUserComputer: false,
+ enabledMcpServerIds: [],
+ disabledMcpServerIds: [],
+ approvalCeiling: "send",
+ },
+ state: "queued",
+ billedBotId: BotId.make("bot-child"),
+ result: null,
+ failure: null,
+ keep: false,
+ createdAt,
+ updatedAt: createdAt,
+ startedAt: null,
+ completedAt: null,
+ },
+ });
+ for (const [threadId, turnId, text] of [
+ [ownerThreadId, ownerTurnId, "Owner answer"],
+ [childThreadId, childTurnId, "Child answer"],
+ ] as const) {
+ await harness.dispatch({
+ type: "thread.turn.start",
+ commandId: CommandId.make(`request-${turnId}`),
+ threadId,
+ message: {
+ messageId: asMessageId(`request-${turnId}`),
+ role: "user",
+ text: "Research",
+ attachments: [],
+ ...(threadId === ownerThreadId
+ ? {
+ channelOrigin: {
+ provider: "telegram" as const,
+ externalThreadId: "channel-owner",
+ },
+ }
+ : {}),
+ },
+ interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
+ runtimeMode: "approval-required",
+ createdAt,
+ });
+ const base = {
+ provider: ProviderDriverKind.make("codex"),
+ threadId,
+ turnId,
+ createdAt: "2026-01-01T00:00:02.000Z",
+ };
+ harness.emit({
+ ...base,
+ type: "turn.started",
+ eventId: asEventId(`start-${turnId}`),
+ payload: {},
+ });
+ harness.emit({
+ ...base,
+ type: "content.delta",
+ eventId: asEventId(`delta-${turnId}`),
+ itemId: asItemId(`item-${turnId}`),
+ payload: { streamKind: "assistant_text", delta: text },
+ });
+ harness.emit({
+ ...base,
+ type: "item.completed",
+ eventId: asEventId(`item-${turnId}`),
+ itemId: asItemId(`item-${turnId}`),
+ payload: { itemType: "assistant_message", status: "completed" },
+ });
+ await harness.drain();
+ }
+ const complete = (
+ threadId: ThreadId,
+ turnId: TurnId,
+ state: "completed" | "failed" | "cancelled",
+ suffix: string,
+ ) => {
+ harness.emit({
+ type: "turn.completed",
+ eventId: asEventId(`complete-${suffix}`),
+ provider: ProviderDriverKind.make("codex"),
+ threadId,
+ turnId,
+ createdAt: "2026-01-01T00:00:03.000Z",
+ payload: { state },
+ });
+ };
+ complete(childThreadId, childTurnId, childState, "child");
+ await harness.drain();
+ expect(posts).toEqual([]);
+ const child = (await harness.readModel()).threads.find(
+ (thread) => thread.id === childThreadId,
+ );
+ expect(child?.latestTurn?.state).toBe(childState === "failed" ? "error" : "completed");
+ complete(ownerThreadId, ownerTurnId, ownerState, "owner");
+ await harness.drain();
+ expect(
+ (await harness.readModel()).threads.find((thread) => thread.id === ownerThreadId)
+ ?.latestTurn,
+ ).toMatchObject({
+ turnId: ownerTurnId,
+ state: ownerState === "failed" ? "error" : "completed",
+ requestMessageId: asMessageId("request-owner-turn"),
+ assistantMessageId: asMessageId("assistant:item-owner-turn"),
+ });
+ const expectedPosts =
+ ownerState === "completed" ? [{ target: "channel-owner", text: "Owner answer" }] : [];
+ expect(posts).toEqual(expectedPosts);
+ complete(childThreadId, childTurnId, childState, "child-replay");
+ complete(ownerThreadId, ownerTurnId, ownerState, "owner-replay");
+ await harness.drain();
+ expect(posts).toEqual(expectedPosts);
+ expect(
+ (await harness.readModel()).bots.find((bot) => bot.id === "bot-akeru")?.channelBindings[0]
+ ?.sentMessageIds,
+ ).toEqual(ownerState === "completed" ? [asMessageId("assistant:item-owner-turn")] : []);
+ },
+ );
+
it("opens and resolves bot inbox approval incidents from runtime requests", async () => {
const harness = await createHarness({ botOwned: true, threadTitle: "Morning research" });
const base = {
@@ -3025,91 +3471,95 @@ describe("ProviderRuntimeIngestion", () => {
expect(message?.streaming).toBe(false);
});
- it("does not duplicate assistant completion when item.completed is followed by turn.completed", async () => {
- const harness = await createHarness();
- const now = "2026-01-01T00:00:00.000Z";
+ effectIt.effect(
+ "does not duplicate assistant completion when item.completed is followed by turn.completed",
+ () =>
+ Effect.gen(function* () {
+ const harness = yield* Effect.promise(() => createHarness());
+ const now = "2026-01-01T00:00:00.000Z";
- harness.emit({
- type: "turn.started",
- eventId: asEventId("evt-turn-started-for-complete-dedup"),
- provider: ProviderDriverKind.make("codex"),
- createdAt: now,
- threadId: asThreadId("thread-1"),
- turnId: asTurnId("turn-complete-dedup"),
- });
+ harness.emit({
+ type: "turn.started",
+ eventId: asEventId("evt-turn-started-for-complete-dedup"),
+ provider: ProviderDriverKind.make("codex"),
+ createdAt: now,
+ threadId: asThreadId("thread-1"),
+ turnId: asTurnId("turn-complete-dedup"),
+ });
- await waitForThread(
- harness.readModel,
- (thread) =>
- thread.session?.status === "running" &&
- thread.session?.activeTurnId === "turn-complete-dedup",
- );
+ yield* Effect.promise(() =>
+ waitForThread(
+ harness.readModel,
+ (thread) =>
+ thread.session?.status === "running" &&
+ thread.session?.activeTurnId === "turn-complete-dedup",
+ ),
+ );
- harness.emit({
- type: "content.delta",
- eventId: asEventId("evt-message-delta-for-complete-dedup"),
- provider: ProviderDriverKind.make("codex"),
- createdAt: now,
- threadId: asThreadId("thread-1"),
- turnId: asTurnId("turn-complete-dedup"),
- itemId: asItemId("item-complete-dedup"),
- payload: {
- streamKind: "assistant_text",
- delta: "done",
- },
- });
- harness.emit({
- type: "item.completed",
- eventId: asEventId("evt-message-completed-for-complete-dedup"),
- provider: ProviderDriverKind.make("codex"),
- createdAt: now,
- threadId: asThreadId("thread-1"),
- turnId: asTurnId("turn-complete-dedup"),
- itemId: asItemId("item-complete-dedup"),
- payload: {
- itemType: "assistant_message",
- status: "completed",
- },
- });
- harness.emit({
- type: "turn.completed",
- eventId: asEventId("evt-turn-completed-for-complete-dedup"),
- provider: ProviderDriverKind.make("codex"),
- createdAt: now,
- threadId: asThreadId("thread-1"),
- turnId: asTurnId("turn-complete-dedup"),
- payload: {
- state: "completed",
- },
- });
+ harness.emit({
+ type: "content.delta",
+ eventId: asEventId("evt-message-delta-for-complete-dedup"),
+ provider: ProviderDriverKind.make("codex"),
+ createdAt: now,
+ threadId: asThreadId("thread-1"),
+ turnId: asTurnId("turn-complete-dedup"),
+ itemId: asItemId("item-complete-dedup"),
+ payload: {
+ streamKind: "assistant_text",
+ delta: "done",
+ },
+ });
+ harness.emit({
+ type: "item.completed",
+ eventId: asEventId("evt-message-completed-for-complete-dedup"),
+ provider: ProviderDriverKind.make("codex"),
+ createdAt: now,
+ threadId: asThreadId("thread-1"),
+ turnId: asTurnId("turn-complete-dedup"),
+ itemId: asItemId("item-complete-dedup"),
+ payload: {
+ itemType: "assistant_message",
+ status: "completed",
+ },
+ });
+ harness.emit({
+ type: "turn.completed",
+ eventId: asEventId("evt-turn-completed-for-complete-dedup"),
+ provider: ProviderDriverKind.make("codex"),
+ createdAt: now,
+ threadId: asThreadId("thread-1"),
+ turnId: asTurnId("turn-complete-dedup"),
+ payload: {
+ state: "completed",
+ },
+ });
- await waitForThread(
- harness.readModel,
- (thread) =>
- thread.session?.status === "ready" &&
- thread.session?.activeTurnId === null &&
- thread.messages.some(
- (message: ProviderRuntimeTestMessage) =>
- message.id === "assistant:item-complete-dedup" && !message.streaming,
- ),
- );
+ yield* Effect.promise(() =>
+ waitForThread(
+ harness.readModel,
+ (thread) =>
+ thread.session?.status === "ready" &&
+ thread.session?.activeTurnId === null &&
+ thread.messages.some(
+ (message: ProviderRuntimeTestMessage) =>
+ message.id === "assistant:item-complete-dedup" && !message.streaming,
+ ),
+ ),
+ );
- const events = await Effect.runPromise(
- Stream.runCollect(harness.engine.readEvents(0)).pipe(
- Effect.map((chunk) => Array.from(chunk)),
- ),
- );
- const completionEvents = events.filter((event) => {
- if (event.type !== "thread.message-sent") {
- return false;
- }
- return (
- event.payload.messageId === "assistant:item-complete-dedup" &&
- event.payload.streaming === false
- );
- });
- expect(completionEvents).toHaveLength(1);
- });
+ const events = yield* Stream.runCollect(harness.engine.readEvents(0));
+ const completionEvents = events.filter((event) => {
+ if (event.type !== "thread.message-sent") {
+ return false;
+ }
+ return (
+ event.payload.messageId === "assistant:item-complete-dedup" &&
+ event.payload.streaming === false
+ );
+ });
+ expect(completionEvents).toHaveLength(1);
+ }),
+ );
it("maps canonical request events into approval activities with requestKind", async () => {
const harness = await createHarness();
diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
index f77a39ada..75fab6570 100644
--- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
+++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
@@ -148,10 +148,7 @@ function boundedApprovalArgs(toolName: string | undefined, args: unknown): unkno
return undefined;
}
-type TurnStartRequestedDomainEvent = Extract<
- OrchestrationEvent,
- { type: "thread.turn-start-requested" }
->;
+type ChannelSessionDomainEvent = Extract<OrchestrationEvent, { type: "thread.session-set" }>;
type RuntimeIngestionInput =
| {
@@ -160,7 +157,7 @@ type RuntimeIngestionInput =
}
| {
source: "domain";
- event: TurnStartRequestedDomainEvent;
+ event: ChannelSessionDomainEvent;
};
function toTurnId(value: TurnId | string | undefined): TurnId | undefined {
@@ -996,6 +993,25 @@ const make = Effect.gen(function* () {
randomUuid: () => Effect.runPromise(crypto.randomUUIDv4),
}
: null;
+ const channelStatusWorker = yield* makeDrainableWorker(
+ (input: {
+ threadId: ThreadId;
+ turnId: TurnId | undefined;
+ requestMessageId?: MessageId;
+ state: "completed" | "failed" | "cancelled";
+ }) =>
+ channelRuntimeDependencies
+ ? Effect.promise(() =>
+ ChannelRuntime.finishChannelTurn(
+ channelRuntimeDependencies,
+ input.threadId,
+ input.turnId,
+ input.state,
+ input.requestMessageId,
+ ),
+ ).pipe(Effect.catchCause(() => Effect.logWarning("failed to update channel turn status")))
+ : Effect.void,
+ );
const automaticChannelReplyWorker = yield* makeDrainableWorker(
(input: AutomaticChannelReplyTarget) => {
if (!channelRuntimeDependencies) {
@@ -1670,6 +1686,7 @@ const make = Effect.gen(function* () {
const conflictsWithActiveTurn =
activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId);
const needsPendingTurnStart =
+ event.type === "session.exited" ||
event.type === "session.started" ||
event.type === "session.state.changed" ||
event.type === "thread.started" ||
@@ -2307,6 +2324,34 @@ const make = Effect.gen(function* () {
),
).pipe(Effect.asVoid);
+ if (
+ shouldApplyThreadLifecycle &&
+ !conflictsWithActiveTurn &&
+ (event.type === "turn.completed" ||
+ event.type === "turn.aborted" ||
+ event.type === "session.exited" ||
+ (event.type === "session.state.changed" &&
+ (event.payload.state === "error" || event.payload.state === "stopped")))
+ ) {
+ yield* channelStatusWorker.enqueue({
+ threadId: thread.id,
+ turnId: eventTurnId ?? activeTurnId ?? undefined,
+ ...(activeTurnId === null && Option.isSome(pendingTurnStart)
+ ? { requestMessageId: pendingTurnStart.value.messageId }
+ : {}),
+ state:
+ event.type === "turn.completed"
+ ? event.payload.state === "completed"
+ ? "completed"
+ : event.payload.state === "failed"
+ ? "failed"
+ : "cancelled"
+ : event.type === "session.state.changed" && event.payload.state === "error"
+ ? "failed"
+ : "cancelled",
+ });
+ }
+
if (
event.type === "turn.completed" &&
event.payload.state === "completed" &&
@@ -2325,7 +2370,27 @@ const make = Effect.gen(function* () {
}
});
- const processDomainEvent = (_event: TurnStartRequestedDomainEvent) => Effect.void;
+ const processDomainEvent = Effect.fn("ProviderRuntimeIngestion.processChannelSession")(function* (
+ event: ChannelSessionDomainEvent,
+ ) {
+ const { session, threadId } = event.payload;
+ if (!channelRuntimeDependencies || (session.status !== "error" && session.status !== "stopped"))
+ return;
+ const thread = yield* resolveThreadDetail(threadId);
+ if (
+ thread?.session?.updatedAt !== session.updatedAt ||
+ thread.session.status !== session.status
+ )
+ return;
+ const request = thread.messages.findLast((message) => message.role === "user");
+ if (!request?.channelOrigin) return;
+ yield* channelStatusWorker.enqueue({
+ threadId,
+ turnId: undefined,
+ requestMessageId: request.id,
+ state: session.status === "error" ? "failed" : "cancelled",
+ });
+ });
const processInput = (input: RuntimeIngestionInput) =>
input.source === "runtime" ? processRuntimeEvent(input.event) : processDomainEvent(input.event);
@@ -2356,7 +2421,7 @@ const make = Effect.gen(function* () {
);
yield* forkParked(
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
- if (event.type !== "thread.turn-start-requested") {
+ if (event.type !== "thread.session-set") {
return Effect.void;
}
return worker.enqueue({ source: "domain", event });
@@ -2366,7 +2431,10 @@ const make = Effect.gen(function* () {
return {
start,
- drain: worker.drain.pipe(Effect.andThen(automaticChannelReplyWorker.drain)),
+ drain: worker.drain.pipe(
+ Effect.andThen(channelStatusWorker.drain),
+ Effect.andThen(automaticChannelReplyWorker.drain),
+ ),
} satisfies ProviderRuntimeIngestionShape;
});
diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts
index 125393627..3c3c32d63 100644
--- a/apps/server/src/persistence/Migrations.ts
+++ b/apps/server/src/persistence/Migrations.ts
@@ -76,6 +76,7 @@ import Migration0060 from "./Migrations/060_ProjectionMessageReactions.ts";
import Migration0061 from "./Migrations/061_ExternalChannels.ts";
import Migration0062 from "./Migrations/062_Routines.ts";
import Migration0063 from "./Migrations/063_RoutineTargetThreadRepair.ts";
+import Migration0064 from "./Migrations/064_ExternalChannelProviders.ts";
/**
* Migration loader with all migrations defined inline.
@@ -151,6 +152,7 @@ export const migrationEntries = [
[61, "ExternalChannels", Migration0061],
[62, "Routines", Migration0062],
[63, "RoutineTargetThreadRepair", Migration0063],
+ [64, "ExternalChannelProviders", Migration0064],
] as const;
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
diff --git a/apps/server/src/persistence/Migrations/064_ExternalChannelProviders.test.ts b/apps/server/src/persistence/Migrations/064_ExternalChannelProviders.test.ts
new file mode 100644
index 000000000..e500bcf32
--- /dev/null
+++ b/apps/server/src/persistence/Migrations/064_ExternalChannelProviders.test.ts
@@ -0,0 +1,52 @@
+import { assert, it } from "@effect/vitest";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as SqlClient from "effect/unstable/sql/SqlClient";
+
+import { runMigrations } from "../Migrations.ts";
+import * as NodeSqliteClient from "../NodeSqliteClient.ts";
+
+it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()))("064_ExternalChannelProviders", (it) => {
+ it.effect("preserves existing deliveries and accepts Slack and Discord", () =>
+ Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ yield* runMigrations({ toMigrationInclusive: 63 });
+ yield* sql`
+ INSERT INTO channel_deliveries (
+ message_id, bot_id, thread_id, provider, external_thread_id,
+ status, requested_at, sent_at
+ ) VALUES (
+ 'telegram-message', 'bot-1', 'thread-1', 'telegram', 'telegram:chat-1',
+ 'sent', '2026-09-04T12:00:00.000Z', '2026-09-04T12:01:00.000Z'
+ )
+ `;
+
+ yield* runMigrations({ toMigrationInclusive: 64 });
+ yield* sql`
+ INSERT INTO channel_deliveries (
+ message_id, bot_id, thread_id, provider, external_thread_id,
+ status, requested_at, sent_at
+ ) VALUES
+ ('slack-message', 'bot-1', 'thread-2', 'slack', 'slack:C1:1',
+ 'requested', '2026-09-04T12:02:00.000Z', NULL),
+ ('discord-message', 'bot-1', 'thread-3', 'discord', 'discord:G1:C1',
+ 'requested', '2026-09-04T12:03:00.000Z', NULL)
+ `;
+
+ const rows = yield* sql<{
+ readonly messageId: string;
+ readonly provider: string;
+ readonly status: string;
+ }>`
+ SELECT message_id AS "messageId", provider, status
+ FROM channel_deliveries
+ ORDER BY message_id
+ `;
+ assert.deepEqual(rows, [
+ { messageId: "discord-message", provider: "discord", status: "requested" },
+ { messageId: "slack-message", provider: "slack", status: "requested" },
+ { messageId: "telegram-message", provider: "telegram", status: "sent" },
+ ]);
+ }),
+ );
+});
diff --git a/apps/server/src/persistence/Migrations/064_ExternalChannelProviders.ts b/apps/server/src/persistence/Migrations/064_ExternalChannelProviders.ts
new file mode 100644
index 000000000..459a17f72
--- /dev/null
+++ b/apps/server/src/persistence/Migrations/064_ExternalChannelProviders.ts
@@ -0,0 +1,36 @@
+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 channel_deliveries RENAME TO channel_deliveries_legacy`;
+ yield* sql`DROP INDEX IF EXISTS idx_channel_deliveries_bot_provider`;
+ yield* sql`
+ CREATE TABLE channel_deliveries (
+ message_id TEXT PRIMARY KEY,
+ bot_id TEXT NOT NULL,
+ thread_id TEXT NOT NULL,
+ provider TEXT NOT NULL CHECK (
+ provider IN ('telegram', 'imessage', 'whatsapp', 'slack', 'discord')
+ ),
+ external_thread_id TEXT NOT NULL,
+ status TEXT NOT NULL CHECK (status IN ('requested', 'sent')),
+ requested_at TEXT NOT NULL,
+ sent_at TEXT
+ )
+ `;
+ yield* sql`
+ INSERT INTO channel_deliveries (
+ message_id, bot_id, thread_id, provider, external_thread_id, status, requested_at, sent_at
+ )
+ SELECT
+ message_id, bot_id, thread_id, provider, external_thread_id, status, requested_at, sent_at
+ FROM channel_deliveries_legacy
+ `;
+ yield* sql`DROP TABLE channel_deliveries_legacy`;
+ yield* sql`
+ CREATE INDEX idx_channel_deliveries_bot_provider
+ ON channel_deliveries (bot_id, provider, status)
+ `;
+});
diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx
index 6b067940c..4f7121404 100644
--- a/apps/web/src/components/AppSidebarLayout.tsx
+++ b/apps/web/src/components/AppSidebarLayout.tsx
@@ -14,6 +14,7 @@ import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings"
import { cn, isMacPlatform } from "../lib/utils";
import { primaryServerKeybindingsAtom } from "../state/server";
import BotRosterSidebar from "./roster/BotRosterSidebar";
+import { useServerRosterSync } from "./roster/useServerRoster";
import { openSettings } from "~/settingsDialogStore";
import { openProductFeedback } from "~/productFeedbackStore";
import {
@@ -140,6 +141,7 @@ function ProjectProjectionRetention() {
}
export function AppSidebarLayout({ children }: { children: ReactNode }) {
+ useServerRosterSync();
const stageArtworkVisible = false;
const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);
const [sidebarWidth, setSidebarWidth] = useState(readInitialThreadSidebarWidth);
diff --git a/apps/web/src/components/Icons.tsx b/apps/web/src/components/Icons.tsx
index e0574de73..531c1b2d1 100644
--- a/apps/web/src/components/Icons.tsx
+++ b/apps/web/src/components/Icons.tsx
@@ -705,3 +705,60 @@ export const PiAgentIcon: Icon = ({ className, ...props }) => (
<path fill="#fff" d="M517.36 400H634.72V634.72H517.36Z" />
</svg>
);
+
+export const SlackIcon: Icon = (props) => (
+ <svg {...props} viewBox="0 0 24 24" fill="none">
+ <path
+ d="M5.042 15.165a2.528 2.528 0 0 1-2.52 2.523A2.528 2.528 0 0 1 0 15.165a2.527 2.527 0 0 1 2.522-2.52h2.52v2.52zM6.313 15.165a2.527 2.527 0 0 1 2.521-2.52 2.527 2.527 0 0 1 2.521 2.52v6.313A2.528 2.528 0 0 1 8.834 24a2.528 2.528 0 0 1-2.521-2.522v-6.313z"
+ fill="#E01E5A"
+ />
+ <path
+ d="M8.834 5.042a2.528 2.528 0 0 1-2.521-2.52A2.528 2.528 0 0 1 8.834 0a2.528 2.528 0 0 1 2.521 2.522v2.52H8.834zM8.834 6.313a2.528 2.528 0 0 1 2.521 2.521 2.528 2.528 0 0 1-2.521 2.521H2.522A2.528 2.528 0 0 1 0 8.834a2.528 2.528 0 0 1 2.522-2.521h6.312z"
+ fill="#36C5F0"
+ />
+ <path
+ d="M18.956 8.834a2.528 2.528 0 0 1 2.522-2.521A2.528 2.528 0 0 1 24 8.834a2.528 2.528 0 0 1-2.522 2.521h-2.522V8.834zM17.688 8.834a2.528 2.528 0 0 1-2.523 2.521 2.527 2.527 0 0 1-2.52-2.521V2.522A2.527 2.527 0 0 1 15.165 0a2.528 2.528 0 0 1 2.523 2.522v6.312z"
+ fill="#2EB67D"
+ />
+ <path
+ d="M15.165 18.956a2.528 2.528 0 0 1 2.523 2.522A2.528 2.528 0 0 1 15.165 24a2.527 2.527 0 0 1-2.52-2.522v-2.522h2.52zM15.165 17.688a2.527 2.527 0 0 1-2.52-2.523 2.526 2.526 0 0 1 2.52-2.52h6.313A2.527 2.527 0 0 1 24 15.165a2.528 2.528 0 0 1-2.522 2.523h-6.313z"
+ fill="#ECB22E"
+ />
+ </svg>
+);
+
+export const DiscordIcon: Icon = (props) => (
+ <svg {...props} viewBox="0 0 24 24" fill="none">
+ <path
+ d="M20.317 4.3698a19.7913 19.7913 0 00-4.8851-1.5152.0741.0741 0 00-.0785.0371c-.211.3753-.4447.8648-.6083 1.2495-1.8447-.2762-3.68-.2762-5.4868 0-.1636-.3933-.4058-.8742-.6177-1.2495a.077.077 0 00-.0785-.037 19.7363 19.7363 0 00-4.8852 1.515.0699.0699 0 00-.0321.0277C.5334 9.0458-.319 13.5799.0992 18.0578a.0824.0824 0 00.0312.0561c2.0528 1.5076 4.0413 2.4228 5.9929 3.0294a.0777.0777 0 00.0842-.0276c.4616-.6304.8731-1.2952 1.226-1.9942a.076.076 0 00-.0416-.1057c-.6528-.2476-1.2743-.5495-1.8722-.8923a.077.077 0 01-.0076-.1277c.1258-.0943.2517-.1923.3718-.2914a.0743.0743 0 01.0776-.0105c3.9278 1.7933 8.18 1.7933 12.0614 0a.0739.0739 0 01.0785.0095c.1202.099.246.1981.3728.2924a.077.077 0 01-.0066.1276 12.2986 12.2986 0 01-1.873.8914.0766.0766 0 00-.0407.1067c.3604.698.7719 1.3628 1.225 1.9932a.076.076 0 00.0842.0286c1.961-.6067 3.9495-1.5219 6.0023-3.0294a.077.077 0 00.0313-.0552c.5004-5.177-.8382-9.6739-3.5485-13.6604a.061.061 0 00-.0312-.0286zM8.02 15.3312c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9555-2.4189 2.157-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.946 2.4189-2.1568 2.4189Z"
+ fill="currentColor"
+ />
+ </svg>
+);
+
+export const TelegramIcon: Icon = (props) => (
+ <svg {...props} viewBox="0 0 24 24" fill="none">
+ <path
+ d="M11.944 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.48.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z"
+ fill="currentColor"
+ />
+ </svg>
+);
+
+export const WhatsAppIcon: Icon = (props) => (
+ <svg {...props} viewBox="0 0 24 24" fill="none">
+ <path
+ d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"
+ fill="currentColor"
+ />
+ </svg>
+);
+
+export const IMessageIcon: Icon = (props) => (
+ <svg {...props} viewBox="0 0 24 24" fill="none">
+ <path
+ d="M5.285 0A5.273 5.273 0 0 0 0 5.285v13.43A5.273 5.273 0 0 0 5.285 24h13.43A5.273 5.273 0 0 0 24 18.715V5.285A5.273 5.273 0 0 0 18.715 0ZM12 4.154a8.809 7.337 0 0 1 8.809 7.338A8.809 7.337 0 0 1 12 18.828a8.809 7.337 0 0 1-2.492-.303A8.656 7.337 0 0 1 5.93 19.93a9.929 7.337 0 0 0 1.54-2.155 8.809 7.337 0 0 1-4.279-6.283A8.809 7.337 0 0 1 12 4.154"
+ fill="currentColor"
+ />
+ </svg>
+);
diff --git a/apps/web/src/components/roster/BotChannelsSheet.tsx b/apps/web/src/components/roster/BotChannelsSheet.tsx
index dcd89a58e..c02aa8cb4 100644
--- a/apps/web/src/components/roster/BotChannelsSheet.tsx
+++ b/apps/web/src/components/roster/BotChannelsSheet.tsx
@@ -30,16 +30,18 @@ const providerLabel = (provider: ChannelProvider) =>
? "Photon"
: provider === "whatsapp"
? "Meta Cloud API"
- : "Telegram Bot API";
+ : provider === "telegram"
+ ? "Telegram Bot API"
+ : provider === "slack"
+ ? "Slack Socket Mode"
+ : "Discord Gateway";
const assignedBotForConnection = (
connectionId: ChannelConnectionId,
bots: ReadonlyArray<Pick<OrchestrationBot, "id" | "name" | "channelBindings">>,
) =>
bots.find((candidate) =>
- (candidate.channelBindings ?? []).some(
- (binding) => binding.connectionId === connectionId && binding.status !== "disconnected",
- ),
+ (candidate.channelBindings ?? []).some((binding) => binding.connectionId === connectionId),
);
export function BotChannelsSheet({
@@ -60,6 +62,7 @@ export function BotChannelsSheet({
const disconnect = useAtomCommand(botEnvironment.channels.disconnect, {
reportFailure: false,
});
+ const detach = useAtomCommand(botEnvironment.channels.detach, { reportFailure: false });
const reconnect = useAtomCommand(botEnvironment.channels.reconnect, {
reportFailure: false,
});
@@ -78,12 +81,14 @@ export function BotChannelsSheet({
);
setBusyId(connection.id);
const result =
- binding?.status === "needs-reconnect"
+ binding?.status === "needs-reconnect" ||
+ binding?.status === "failed" ||
+ binding?.status === "disconnected"
? await reconnect({
environmentId,
input: { botId: BotId.make(bot.id), provider: connection.provider },
})
- : binding && binding.status !== "disconnected"
+ : binding
? await disconnect({
environmentId,
input: { botId: BotId.make(bot.id), provider: connection.provider },
@@ -102,6 +107,19 @@ export function BotChannelsSheet({
}
};
+ const unassign = async (connection: ChannelConnectionProfile) => {
+ if (!environmentId) return;
+ setBusyId(connection.id);
+ const result = await detach({
+ environmentId,
+ input: { botId: BotId.make(bot.id), provider: connection.provider },
+ });
+ setBusyId(null);
+ if (result._tag === "Failure") {
+ toastManager.add({ type: "error", title: "Could not unassign channel" });
+ }
+ };
+
const openChannelSettings = () => {
onOpenChange(false);
openSettings("channels", null, environmentId);
@@ -122,13 +140,11 @@ export function BotChannelsSheet({
</div>
) : access === "denied" ? (
<div className="py-8 text-sm text-muted-foreground">
- Open this environment on its host to manage channels.
+ This client does not have permission to manage channels.
</div>
) : connections.length === 0 ? (
<div className="space-y-3 py-4">
- <p className="text-sm text-muted-foreground">
- Set up Telegram, iMessage, or WhatsApp first.
- </p>
+ <p className="text-sm text-muted-foreground">Set up a channel connection first.</p>
<Button onClick={openChannelSettings}>Set up channels</Button>
</div>
) : (
@@ -142,44 +158,60 @@ export function BotChannelsSheet({
const action =
owner && !ownedByCurrentBot
? "Assigned"
- : binding?.status === "needs-reconnect"
+ : binding?.status === "needs-reconnect" ||
+ binding?.status === "failed" ||
+ binding?.status === "disconnected"
? "Reconnect"
- : binding && binding.status !== "disconnected"
+ : binding
? "Disconnect"
: "Connect";
return (
<div
key={connection.id}
- className="flex items-center justify-between gap-3 rounded-xl border px-3 py-2.5"
+ className="flex flex-col gap-3 rounded-xl border px-3 py-2.5"
>
<div className="min-w-0 space-y-1">
<div className="truncate text-sm font-medium">{connection.name}</div>
<div className="text-xs text-muted-foreground">
{providerLabel(connection.provider)}
- {connection.externalIdentity ? ` · ${connection.externalIdentity}` : ""}
+ {(binding?.externalIdentity ?? connection.externalIdentity)
+ ? ` · ${binding?.externalIdentity ?? connection.externalIdentity}`
+ : ""}
</div>
+ {binding?.lastError ? (
+ <p
+ role="status"
+ className="break-words text-xs text-amber-600 dark:text-amber-400"
+ >
+ {binding.lastError}
+ </p>
+ ) : null}
{owner ? (
<Badge
- variant={binding?.status === "needs-reconnect" ? "warning" : "success"}
+ variant={
+ binding?.status === "needs-reconnect" ||
+ binding?.status === "failed" ||
+ binding?.status === "disconnected"
+ ? "warning"
+ : "success"
+ }
size="sm"
>
- {binding?.status === "needs-reconnect"
- ? "Needs reconnect"
- : `Assigned to ${owner.name}`}
+ {binding?.status === "failed"
+ ? "Connection failed"
+ : binding?.status === "needs-reconnect"
+ ? "Needs reconnect"
+ : binding?.status === "disconnected"
+ ? `Disconnected · ${owner.name}`
+ : `Assigned to ${owner.name}`}
</Badge>
) : (
<Badge variant="secondary" size="sm">
Unassigned
</Badge>
)}
- {ownedByCurrentBot && connection.provider === "imessage" ? (
- <p className="text-xs text-muted-foreground">
- Text the number shown in Photon. {bot.name} replies automatically. Groups
- need a dedicated line and an exact @{bot.name} mention.
- </p>
- ) : null}
</div>
- <div className="flex items-center gap-2">
+ <div className="flex flex-wrap items-center gap-2">
{connection.managementUrl ? (
<Button
variant="outline"
@@ -187,7 +219,16 @@ export function BotChannelsSheet({
<a href={connection.managementUrl} target="_blank" rel="noreferrer" />
}
>
- Open Photon
+ Open provider
+ </Button>
+ ) : null}
+ {ownedByCurrentBot ? (
+ <Button
+ variant="outline"
+ disabled={busyId !== null}
+ onClick={() => void unassign(connection)}
+ >
+ Unassign
</Button>
) : null}
<Button
diff --git a/apps/web/src/components/roster/BotDetailsPanel.test.tsx b/apps/web/src/components/roster/BotDetailsPanel.test.tsx
index 38af82912..8773d9c84 100644
--- a/apps/web/src/components/roster/BotDetailsPanel.test.tsx
+++ b/apps/web/src/components/roster/BotDetailsPanel.test.tsx
@@ -1,6 +1,7 @@
// @effect-diagnostics nodeBuiltinImport:off - The route contract reads its source.
import * as NodeFS from "node:fs";
+import { BotId, ProjectId } from "@t3tools/contracts";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vite-plus/test";
@@ -69,6 +70,32 @@ describe("BotDetailsPanel", () => {
expect(markup).toContain("border-t border-border");
});
+ it.each(["disconnected", "failed", "needs-reconnect"] as const)(
+ "shows an assigned %s channel without claiming it is connected",
+ (status) => {
+ const markup = renderToStaticMarkup(
+ <BotDetailsPanel
+ bot={{
+ ...bot,
+ channelBindings: [
+ {
+ botId: BotId.make(bot.id),
+ provider: "slack",
+ projectId: ProjectId.make("project-1"),
+ status,
+ externalIdentity: null,
+ connectedAt: null,
+ sentMessageIds: [],
+ },
+ ],
+ }}
+ />,
+ );
+ expect(markup).toContain("0 of 1 connected");
+ expect(markup).not.toContain("No channels");
+ },
+ );
+
it("sets, clears, and rejects invalid hard stops", () => {
expect(parseBotUsageCapInput("50000")).toEqual({
valid: true,
diff --git a/apps/web/src/components/roster/BotDetailsPanel.tsx b/apps/web/src/components/roster/BotDetailsPanel.tsx
index ace9b6588..000afb2b2 100644
--- a/apps/web/src/components/roster/BotDetailsPanel.tsx
+++ b/apps/web/src/components/roster/BotDetailsPanel.tsx
@@ -235,8 +235,11 @@ function BotProfileEditor({
const enabledToolCount = tools.filter(
(tool) => tool.workspaceEnabled && !disabledMcpServerIds.includes(tool.id),
).length;
- const connectedChannelCount = (bot.channelBindings ?? []).filter(
- (binding) => binding.status !== "disconnected",
+ const assignedChannels = (bot.channelBindings ?? []).filter(
+ (binding) => binding.connectionId || binding.projectId || binding.status !== "disconnected",
+ );
+ const connectedChannelCount = assignedChannels.filter(
+ (binding) => binding.status === "connected",
).length;
const toolOverridesDirty =
[...disabledMcpServerIds].sort().join("\u0000") !==
@@ -475,7 +478,9 @@ function BotProfileEditor({
>
<AppIcon className="size-4 shrink-0 text-muted-foreground" icon={Link02Icon} />
<span className="min-w-0 flex-1 text-sm">
- {connectedChannelCount === 0 ? "No channels" : `${connectedChannelCount} connected`}
+ {assignedChannels.length === 0
+ ? "No channels"
+ : `${connectedChannelCount} of ${assignedChannels.length} connected`}
</span>
<span className="text-xs text-muted-foreground">Manage</span>
</button>
diff --git a/apps/web/src/components/roster/BotRosterSidebar.tsx b/apps/web/src/components/roster/BotRosterSidebar.tsx
index 9ebd819ed..21bea00a5 100644
--- a/apps/web/src/components/roster/BotRosterSidebar.tsx
+++ b/apps/web/src/components/roster/BotRosterSidebar.tsx
@@ -73,7 +73,6 @@ import {
import { useRosterStore, type RosterItemRef, type RosterSection } from "./rosterStore";
import type { Bot, BotAvatar, Group } from "./types";
import { useBotThreadRef } from "./useBotThreadRef";
-import { useServerRosterSync } from "./useServerRoster";
/** Avatar with a yellow needs-you light and a green working light. */
function RosterAvatar({
@@ -529,7 +528,6 @@ function PinnedRosterItem({
}
export default function BotRosterSidebar() {
- useServerRosterSync();
const navigate = useNavigate();
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const environmentId = usePrimaryEnvironmentId();
diff --git a/apps/web/src/components/roster/BotThreadLanding.tsx b/apps/web/src/components/roster/BotThreadLanding.tsx
index a836ad8f8..d7c2574fc 100644
--- a/apps/web/src/components/roster/BotThreadLanding.tsx
+++ b/apps/web/src/components/roster/BotThreadLanding.tsx
@@ -42,6 +42,7 @@ import { BotConversationScrollArea } from "./BotConversationScrollArea";
import { DelegationCard } from "./DelegationCard";
import {
channelOriginForAssistantMessage,
+ channelOriginLabel,
channelProviderLabel,
isBotConversationWorking,
visibleBotChatMessages,
@@ -397,6 +398,11 @@ export function BotThreadLanding({ botId }: { readonly botId: string }) {
</div>
<div className="flex max-w-[78%] flex-col items-end">
<div className="w-full rounded-2xl bg-foreground/10 px-3.5 py-2 text-sm leading-6">
+ {message.channelOrigin ? (
+ <div className="mb-1 text-xs font-medium text-muted-foreground">
+ {channelOriginLabel(message.channelOrigin, message.authorDisplayName)}
+ </div>
+ ) : null}
{message.text ? (
<p className="whitespace-pre-wrap">{message.text}</p>
) : null}
diff --git a/apps/web/src/components/roster/botConversationPresentation.ts b/apps/web/src/components/roster/botConversationPresentation.ts
index 3e4350390..023fa0b84 100644
--- a/apps/web/src/components/roster/botConversationPresentation.ts
+++ b/apps/web/src/components/roster/botConversationPresentation.ts
@@ -1,19 +1,17 @@
+import {
+ channelOriginLabel as sharedChannelOriginLabel,
+ channelProviderLabel as sharedChannelProviderLabel,
+} from "@t3tools/client-runtime/channel-presentation";
import type { ChannelMessageOrigin, OrchestrationMessage } from "@t3tools/contracts";
import type { RosterPresence } from "./roster.logic";
-export function channelProviderLabel(
- provider: ChannelMessageOrigin["provider"] | "whatsapp",
-): string {
- if (provider === "imessage") return "iMessage";
- if (provider === "whatsapp") return "WhatsApp";
- return "Telegram";
-}
+export const channelProviderLabel = sharedChannelProviderLabel;
-export function channelOriginLabel(origin: ChannelMessageOrigin): string {
- const provider = channelProviderLabel(origin.provider);
- return origin.provider === "imessage" && origin.externalSenderId
- ? `${provider} · ${origin.externalSenderId}`
- : provider;
+export function channelOriginLabel(
+ origin: ChannelMessageOrigin,
+ senderDisplayName?: string | null,
+): string {
+ return sharedChannelOriginLabel(origin, senderDisplayName);
}
export function channelOriginForAssistantMessage(
diff --git a/apps/web/src/components/settings/BotChannelRows.tsx b/apps/web/src/components/settings/BotChannelRows.tsx
index b18bd99fe..e434ecf69 100644
--- a/apps/web/src/components/settings/BotChannelRows.tsx
+++ b/apps/web/src/components/settings/BotChannelRows.tsx
@@ -2,17 +2,8 @@ import {
type BotId,
type ChannelBinding,
type ChannelProvider,
- type EnvironmentId,
+ type ProjectId,
} from "@t3tools/contracts";
-import { useState } from "react";
-
-import { botEnvironment } from "../../state/bots";
-import { useAtomCommand } from "../../state/use-atom-command";
-import { Button } from "../ui/button";
-import { Input } from "../ui/input";
-import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
-import { toastManager } from "../ui/toast";
-import { SettingsRow } from "./settingsLayout";
export interface ChannelBot {
readonly id: BotId;
@@ -34,6 +25,7 @@ export function bindingFor(bot: ChannelBot, provider: ChannelProvider): ChannelB
export function selfHostedIMessageConnectInput(
botId: BotId,
+ targetProjectId: ProjectId,
serverUrl: string,
apiKey: string,
phone: string,
@@ -41,6 +33,7 @@ export function selfHostedIMessageConnectInput(
const trimmedPhone = phone.trim();
return {
botId,
+ targetProjectId,
provider: "imessage" as const,
mode: "self-hosted" as const,
serverUrl: serverUrl.trim(),
@@ -51,6 +44,7 @@ export function selfHostedIMessageConnectInput(
export function whatsAppConnectInput(
botId: BotId,
+ targetProjectId: ProjectId,
accessToken: string,
appSecret: string,
phoneNumberId: string,
@@ -58,6 +52,7 @@ export function whatsAppConnectInput(
) {
return {
botId,
+ targetProjectId,
provider: "whatsapp" as const,
accessToken: accessToken.trim(),
appSecret: appSecret.trim(),
@@ -65,338 +60,3 @@ export function whatsAppConnectInput(
verifyToken: verifyToken.trim(),
};
}
-
-function statusLabel(status: ChannelBinding["status"]): string {
- switch (status) {
- case "connected":
- return "Connected";
- case "needs-reconnect":
- return "Needs reconnect";
- case "not-live":
- return "Not live";
- case "disconnected":
- return "Disconnected";
- }
-}
-
-function description(binding: ChannelBinding): string {
- return `${statusLabel(binding.status)}${binding.externalIdentity ? ` · ${binding.externalIdentity}` : ""}`;
-}
-
-function useChannelActions(
- environmentId: EnvironmentId,
- bot: ChannelBot,
- provider: ChannelProvider,
- label: string,
-) {
- const binding = bindingFor(bot, provider);
- const disconnect = useAtomCommand(botEnvironment.channels.disconnect, {
- reportFailure: false,
- });
- const reconnect = useAtomCommand(botEnvironment.channels.reconnect, {
- reportFailure: false,
- });
- const [busy, setBusy] = useState(false);
- const run = async (action: () => Promise<{ readonly _tag: string }>, failure: string) => {
- setBusy(true);
- const result = await action();
- setBusy(false);
- if (result._tag === "Failure") {
- toastManager.add({ type: "error", title: failure });
- return false;
- }
- return true;
- };
- const connected = binding.status === "connected" || binding.status === "needs-reconnect";
- const connectedControl = (
- <div className="flex items-center gap-2">
- <Button
- disabled={busy}
- variant="outline"
- onClick={() =>
- void run(
- () => reconnect({ environmentId, input: { botId: bot.id, provider } }),
- `Could not reconnect ${label}`,
- )
- }
- >
- Reconnect
- </Button>
- <Button
- disabled={busy}
- variant="outline"
- onClick={() =>
- void run(
- () => disconnect({ environmentId, input: { botId: bot.id, provider } }),
- `Could not disconnect ${label}`,
- )
- }
- >
- Disconnect
- </Button>
- </div>
- );
- return { binding, busy, connected, connectedControl, run };
-}
-
-export function TelegramChannelRow({
- environmentId,
- bot,
-}: {
- readonly environmentId: EnvironmentId;
- readonly bot: ChannelBot;
-}) {
- const connect = useAtomCommand(botEnvironment.channels.connect, {
- reportFailure: false,
- });
- const [token, setToken] = useState("");
- const actions = useChannelActions(environmentId, bot, "telegram", "Telegram");
- return (
- <SettingsRow
- title="Telegram"
- description={description(actions.binding)}
- control={
- actions.connected ? (
- actions.connectedControl
- ) : (
- <div className="flex w-72 gap-2">
- <Input
- aria-label="Telegram BotFather token"
- placeholder="BotFather token"
- type="password"
- value={token}
- onChange={(event) => setToken(event.currentTarget.value)}
- />
- <Button
- disabled={actions.busy || token.trim().length === 0}
- onClick={() =>
- void actions
- .run(
- () =>
- connect({
- environmentId,
- input: {
- botId: bot.id,
- provider: "telegram",
- token: token.trim(),
- },
- }),
- "Could not connect Telegram",
- )
- .then((success) => success && setToken(""))
- }
- >
- Connect
- </Button>
- </div>
- )
- }
- />
- );
-}
-
-export function IMessageChannelRow({
- environmentId,
- bot,
-}: {
- readonly environmentId: EnvironmentId;
- readonly bot: ChannelBot;
-}) {
- const connect = useAtomCommand(botEnvironment.channels.connect, {
- reportFailure: false,
- });
- const [mode, setMode] = useState<"hosted" | "self-hosted">("hosted");
- const [projectId, setProjectId] = useState("");
- const [projectSecret, setProjectSecret] = useState("");
- const [serverUrl, setServerUrl] = useState("");
- const [apiKey, setApiKey] = useState("");
- const [phone, setPhone] = useState("");
- const actions = useChannelActions(environmentId, bot, "imessage", "iMessage");
- const missingCredentials =
- mode === "hosted"
- ? !projectId.trim() || !projectSecret.trim()
- : !serverUrl.trim() || !apiKey.trim();
- return (
- <SettingsRow
- title="iMessage"
- description={description(actions.binding)}
- control={
- actions.connected ? (
- actions.connectedControl
- ) : (
- <div className="flex w-72 flex-col gap-2">
- <Select value={mode} onValueChange={(value) => value && setMode(value)}>
- <SelectTrigger aria-label="iMessage connection type" className="w-full">
- <SelectValue />
- </SelectTrigger>
- <SelectPopup>
- <SelectItem value="hosted">Photon hosted or free/shared number</SelectItem>
- <SelectItem value="self-hosted">Photon self-hosted</SelectItem>
- </SelectPopup>
- </Select>
- {mode === "hosted" ? (
- <>
- <Input
- aria-label="Photon project ID"
- placeholder="Photon project ID"
- value={projectId}
- onChange={(event) => setProjectId(event.currentTarget.value)}
- />
- <Input
- aria-label="Photon project secret"
- placeholder="Photon project secret"
- type="password"
- value={projectSecret}
- onChange={(event) => setProjectSecret(event.currentTarget.value)}
- />
- </>
- ) : (
- <>
- <Input
- aria-label="Photon server"
- placeholder="Photon gRPC host:port"
- value={serverUrl}
- onChange={(event) => setServerUrl(event.currentTarget.value)}
- />
- <Input
- aria-label="Photon API key"
- placeholder="Photon API key"
- type="password"
- value={apiKey}
- onChange={(event) => setApiKey(event.currentTarget.value)}
- />
- <Input
- aria-label="Photon phone or line"
- placeholder="Phone or line (optional)"
- value={phone}
- onChange={(event) => setPhone(event.currentTarget.value)}
- />
- </>
- )}
- <div className="flex justify-between gap-2">
- <Button
- variant="outline"
- onClick={() => window.open("https://photon.codes/pricing", "_blank", "noopener")}
- >
- Free/shared number
- </Button>
- <Button
- disabled={actions.busy || missingCredentials}
- onClick={() =>
- void actions.run(
- () =>
- connect({
- environmentId,
- input:
- mode === "hosted"
- ? {
- botId: bot.id,
- provider: "imessage",
- mode,
- projectId: projectId.trim(),
- projectSecret: projectSecret.trim(),
- }
- : selfHostedIMessageConnectInput(bot.id, serverUrl, apiKey, phone),
- }),
- "Could not connect iMessage",
- )
- }
- >
- Connect
- </Button>
- </div>
- </div>
- )
- }
- />
- );
-}
-
-export function WhatsAppChannelRow({
- environmentId,
- bot,
-}: {
- readonly environmentId: EnvironmentId;
- readonly bot: ChannelBot;
-}) {
- const connect = useAtomCommand(botEnvironment.channels.connect, {
- reportFailure: false,
- });
- const [accessToken, setAccessToken] = useState("");
- const [appSecret, setAppSecret] = useState("");
- const [phoneNumberId, setPhoneNumberId] = useState("");
- const [verifyToken, setVerifyToken] = useState("");
- const actions = useChannelActions(environmentId, bot, "whatsapp", "WhatsApp");
- const missingCredentials =
- !accessToken.trim() || !appSecret.trim() || !phoneNumberId.trim() || !verifyToken.trim();
- return (
- <SettingsRow
- title="WhatsApp"
- description={description(actions.binding)}
- control={
- actions.connected ? (
- actions.connectedControl
- ) : (
- <div className="flex w-72 flex-col gap-2">
- <Input
- aria-label="WhatsApp access token"
- placeholder="Access token"
- type="password"
- value={accessToken}
- onChange={(event) => setAccessToken(event.currentTarget.value)}
- />
- <Input
- aria-label="WhatsApp app secret"
- placeholder="App secret"
- type="password"
- value={appSecret}
- onChange={(event) => setAppSecret(event.currentTarget.value)}
- />
- <Input
- aria-label="WhatsApp phone number ID"
- placeholder="Phone number ID"
- value={phoneNumberId}
- onChange={(event) => setPhoneNumberId(event.currentTarget.value)}
- />
- <Input
- aria-label="WhatsApp verify token"
- placeholder="Verify token"
- type="password"
- value={verifyToken}
- onChange={(event) => setVerifyToken(event.currentTarget.value)}
- />
- <Button
- disabled={actions.busy || missingCredentials}
- onClick={() =>
- void actions
- .run(
- () =>
- connect({
- environmentId,
- input: whatsAppConnectInput(
- bot.id,
- accessToken,
- appSecret,
- phoneNumberId,
- verifyToken,
- ),
- }),
- "Could not connect WhatsApp",
- )
- .then((success) => {
- if (!success) return;
- setAccessToken("");
- setAppSecret("");
- setPhoneNumberId("");
- setVerifyToken("");
- })
- }
- >
- Connect
- </Button>
- </div>
- )
- }
- />
- );
-}
diff --git a/apps/web/src/components/settings/BotChannelsSettings.render.test.tsx b/apps/web/src/components/settings/BotChannelsSettings.render.test.tsx
new file mode 100644
index 000000000..6508cc92a
--- /dev/null
+++ b/apps/web/src/components/settings/BotChannelsSettings.render.test.tsx
@@ -0,0 +1,106 @@
+import { AuthAccessWriteScope } from "@t3tools/contracts";
+import type { ReactNode } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
+
+const fixtures = vi.hoisted(() => ({
+ bots: [] as Array<{
+ id: string;
+ name: string;
+ archivedAt: null;
+ channelBindings: Array<{
+ botId: string;
+ connectionId: string;
+ provider: "imessage";
+ projectId: string;
+ status: "disconnected";
+ lastError?: string;
+ externalIdentity: null;
+ connectedAt: null;
+ sentMessageIds: string[];
+ }>;
+ }>,
+ projects: [
+ { id: "project-uuid", title: "Selected workspace", workspaceRoot: "/Users/leo/code/selected" },
+ ],
+ connections: [
+ { id: "profile-1", name: "Fixture line", provider: "imessage", externalIdentity: null },
+ ],
+}));
+
+vi.mock("@effect/atom-react", () => ({
+ useAtomValue: (atom: string) => (atom === "bots" ? fixtures.bots : fixtures.projects),
+}));
+vi.mock("../../state/bots", () => ({
+ environmentBotsAtom: () => "bots",
+ botEnvironment: { channels: {} },
+}));
+vi.mock("../../state/projects", () => ({
+ environmentProjects: { environmentProjectsAtom: () => "projects" },
+}));
+vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));
+vi.mock("../../hooks/useSettings", () => ({ useEnvironmentSettings: () => fixtures.connections }));
+vi.mock("../../settingsDialogStore", () => ({ useSettingsEnvironmentId: () => "environment-1" }));
+vi.mock("../../state/session", () => ({
+ useEnvironmentSessionState: () => ({
+ isPending: false,
+ data: { authenticated: true, scopes: [AuthAccessWriteScope] },
+ }),
+}));
+
+vi.mock("./settingsLayout", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("./settingsLayout")>()),
+ SettingsPageContainer: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+}));
+
+import { BotChannelsSettingsPanel } from "./BotChannelsSettings";
+
+describe("channel project selection", () => {
+ beforeEach(() => {
+ fixtures.bots = [];
+ });
+
+ it("asks only for a bot and never exposes a folder or project picker", () => {
+ const html = renderToStaticMarkup(<BotChannelsSettingsPanel />);
+ expect(html).toContain("Bot that answers");
+ expect(html).toContain("Choose a bot");
+ expect(html).not.toContain("project");
+ expect(html).not.toContain("folder");
+ expect(html).not.toContain(">Selected workspace<");
+ const trigger = html.match(/<button[^>]*aria-label="Assign Fixture line"[^>]*>/)?.[0];
+ expect(trigger).toBeDefined();
+ expect(trigger).not.toMatch(/\sdisabled(=|\s|>)/);
+ });
+
+ it("renders the assigned project and bot names rather than their IDs", () => {
+ fixtures.bots = [
+ {
+ id: "bot-uuid",
+ name: "Akeru",
+ archivedAt: null,
+ channelBindings: [
+ {
+ botId: "bot-uuid",
+ connectionId: "profile-1",
+ provider: "imessage",
+ projectId: "project-uuid",
+ status: "disconnected",
+ lastError:
+ "Delivery could not be confirmed. Check the external conversation before retrying.",
+ externalIdentity: null,
+ connectedAt: null,
+ sentMessageIds: [],
+ },
+ ],
+ },
+ ];
+ const html = renderToStaticMarkup(<BotChannelsSettingsPanel />);
+ expect(html).toContain(">Akeru<");
+ expect(html).not.toContain(">project-uuid<");
+ expect(html).not.toContain(">bot-uuid<");
+ expect(html).toContain('role="status"');
+ expect(html).toContain(
+ "Delivery could not be confirmed. Check the external conversation before retrying.",
+ );
+ });
+});
diff --git a/apps/web/src/components/settings/BotChannelsSettings.test.ts b/apps/web/src/components/settings/BotChannelsSettings.test.ts
index 56289a59a..d51846caa 100644
--- a/apps/web/src/components/settings/BotChannelsSettings.test.ts
+++ b/apps/web/src/components/settings/BotChannelsSettings.test.ts
@@ -1,4 +1,4 @@
-import { AuthAccessWriteScope, BotId, ChannelConnectionId } from "@t3tools/contracts";
+import { AuthAccessWriteScope, BotId, ChannelConnectionId, ProjectId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import {
@@ -16,6 +16,7 @@ import {
describe("bot channel settings", () => {
const botId = BotId.make("bot-1");
+ const projectId = ProjectId.make("project-1");
it("shows disconnected live adapters", () => {
const bot = { id: botId, channelBindings: [] };
@@ -55,24 +56,32 @@ describe("bot channel settings", () => {
it("sends a trimmed Photon phone when self-hosted", () => {
expect(
- selfHostedIMessageConnectInput(botId, " photon.test:443 ", " secret ", " +15551234567 "),
+ selfHostedIMessageConnectInput(
+ botId,
+ projectId,
+ " photon.test:443 ",
+ " secret ",
+ " +15551234567 ",
+ ),
).toEqual({
botId,
+ targetProjectId: projectId,
provider: "imessage",
mode: "self-hosted",
serverUrl: "photon.test:443",
apiKey: "secret",
phone: "+15551234567",
});
- expect(selfHostedIMessageConnectInput(botId, "server", "key", " ")).not.toHaveProperty(
- "phone",
- );
+ expect(
+ selfHostedIMessageConnectInput(botId, projectId, "server", "key", " "),
+ ).not.toHaveProperty("phone");
});
it("sends trimmed WhatsApp credentials", () => {
expect(
whatsAppConnectInput(
botId,
+ projectId,
" access-token ",
" app-secret ",
" phone-number-id ",
@@ -80,6 +89,7 @@ describe("bot channel settings", () => {
),
).toEqual({
botId,
+ targetProjectId: projectId,
provider: "whatsapp",
accessToken: "access-token",
appSecret: "app-secret",
@@ -131,6 +141,15 @@ describe("bot channel settings", () => {
];
expect(assignedBotForConnection(connectionId, bots)?.name).toBe("Scout");
+ expect(
+ assignedBotForConnection(connectionId, [
+ {
+ ...bots[0]!,
+ archivedAt: null,
+ channelBindings: [{ ...bots[0]!.channelBindings[0]!, status: "disconnected" }],
+ },
+ ])?.name,
+ ).toBe("Scout");
expect(assignedBotForConnection(ChannelConnectionId.make("unassigned"), bots)).toBeUndefined();
});
@@ -138,13 +157,16 @@ describe("bot channel settings", () => {
expect(providerLabel("imessage")).toBe("Photon");
expect(providerLabel("whatsapp")).toBe("Meta Cloud API");
expect(providerLabel("telegram")).toBe("Telegram Bot API");
+ expect(providerLabel("slack")).toBe("Slack Socket Mode");
+ expect(providerLabel("discord")).toBe("Discord Gateway");
});
it("explains the real end-to-end channel test", () => {
- expect(channelTestInstructions("imessage", "Akeru")).toContain("replies automatically");
- expect(channelTestInstructions("imessage", "Akeru")).toContain("exact @Akeru mention");
- expect(channelTestInstructions("whatsapp")).toContain("WhatsApp message");
- expect(channelTestInstructions("telegram")).toContain("Telegram message");
+ expect(channelTestInstructions("imessage", "Akeru")).toContain("direct iMessage");
+ expect(channelTestInstructions("whatsapp")).toContain("direct WhatsApp");
+ expect(channelTestInstructions("telegram")).toContain("direct Telegram");
+ expect(channelTestInstructions("slack", "Akeru")).toContain("Slack channel thread");
+ expect(channelTestInstructions("discord", "Akeru")).toContain("Discord server");
});
it("parses copied Photon environment variables", () => {
diff --git a/apps/web/src/components/settings/BotChannelsSettings.tsx b/apps/web/src/components/settings/BotChannelsSettings.tsx
index 96b09999d..82c2a1f10 100644
--- a/apps/web/src/components/settings/BotChannelsSettings.tsx
+++ b/apps/web/src/components/settings/BotChannelsSettings.tsx
@@ -1,12 +1,13 @@
import { useAtomValue } from "@effect/atom-react";
import {
BotId,
- ChannelConnectionId,
+ type ChannelConnectionId,
type ChannelConnectionProfile,
type ChannelProvider,
type EnvironmentId,
type OrchestrationBot,
} from "@t3tools/contracts";
+import { PlusIcon } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { resolveChannelSettingsAccess } from "../../channelAccess";
@@ -18,51 +19,42 @@ import { useSettingsEnvironmentId } from "../../settingsDialogStore";
import { useAtomCommand } from "../../state/use-atom-command";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
-import { Input } from "../ui/input";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
import { Spinner } from "../ui/spinner";
-import { Textarea } from "../ui/textarea";
import { toastManager } from "../ui/toast";
-import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";
+import { ChannelSetupDialog } from "./ChannelSetupDialog";
+import { CHANNEL_PROVIDER_META, channelProviderMeta } from "./channelProviderMeta";
+import { SettingsPageContainer, SettingsSection } from "./settingsLayout";
import { searchableSetting } from "./settingsSearch";
const NO_ENVIRONMENT = "" as EnvironmentId;
const UNASSIGNED = "unassigned";
-const CHANNELS: ReadonlyArray<{
- readonly provider: ChannelProvider;
- readonly label: string;
-}> = [
- { provider: "imessage", label: "iMessage" },
- { provider: "whatsapp", label: "WhatsApp" },
- { provider: "telegram", label: "Telegram" },
-];
-
export function assignedBotForConnection(
connectionId: ChannelConnectionId,
bots: ReadonlyArray<Pick<OrchestrationBot, "id" | "name" | "archivedAt" | "channelBindings">>,
) {
return bots.find((bot) =>
- (bot.channelBindings ?? []).some(
- (binding) => binding.connectionId === connectionId && binding.status !== "disconnected",
- ),
+ (bot.channelBindings ?? []).some((binding) => binding.connectionId === connectionId),
);
}
export function providerLabel(provider: ChannelProvider): string {
- return provider === "imessage"
- ? "Photon"
- : provider === "whatsapp"
- ? "Meta Cloud API"
- : "Telegram Bot API";
+ if (provider === "imessage") return "Photon";
+ if (provider === "whatsapp") return "Meta Cloud API";
+ if (provider === "telegram") return "Telegram Bot API";
+ if (provider === "slack") return "Slack Socket Mode";
+ return "Discord Gateway";
}
export function channelTestInstructions(provider: ChannelProvider, botName?: string): string {
- return provider === "imessage"
- ? `Text the number shown in Photon. ${botName ?? "The bot"} replies automatically. Groups need a dedicated line and an exact @${botName ?? "BotName"} mention.`
- : provider === "whatsapp"
- ? "Send a WhatsApp message to this number to test a reply."
- : "Send a Telegram message to this bot to test a reply.";
+ if (provider === "imessage") return "Send a direct iMessage to this line to test a reply.";
+ if (provider === "whatsapp") return "Send a direct WhatsApp message to this number.";
+ if (provider === "telegram") return "Send a direct Telegram message to this bot.";
+ if (provider === "slack") {
+ return `Send a direct message or mention ${botName ?? "the bot"} in a Slack channel thread.`;
+ }
+ return `Send a direct message or mention ${botName ?? "the bot"} in a Discord server.`;
}
export function parsePhotonHostedCredentials(input: string): {
@@ -100,9 +92,6 @@ export function BotChannelsSettingsPanel() {
targetEnvironmentId,
(settings) => settings.channelConnections,
);
- const saveConnection = useAtomCommand(botEnvironment.channels.saveConnection, {
- reportFailure: false,
- });
const deleteConnection = useAtomCommand(botEnvironment.channels.deleteConnection, {
reportFailure: false,
});
@@ -110,11 +99,12 @@ export function BotChannelsSettingsPanel() {
const disconnect = useAtomCommand(botEnvironment.channels.disconnect, {
reportFailure: false,
});
+ const detach = useAtomCommand(botEnvironment.channels.detach, { reportFailure: false });
+ const reconnect = useAtomCommand(botEnvironment.channels.reconnect, {
+ reportFailure: false,
+ });
const [provider, setProvider] = useState<ChannelProvider>("imessage");
- const [mode, setMode] = useState<"hosted" | "self-hosted">("hosted");
- const [name, setName] = useState("");
- const [photonCredentials, setPhotonCredentials] = useState("");
- const [values, setValues] = useState<Record<string, string>>({});
+ const [setupOpen, setSetupOpen] = useState(false);
const [busy, setBusy] = useState(false);
const [busyConnectionId, setBusyConnectionId] = useState<string | null>(null);
const [pendingProfile, setPendingProfile] = useState<{
@@ -126,24 +116,7 @@ export function BotChannelsSettingsPanel() {
isPending: session.isPending,
session: session.data,
});
- const value = (key: string) => values[key] ?? "";
- const setValue = (key: string, next: string) =>
- setValues((current) => ({ ...current, [key]: next }));
const providerConnections = connections.filter((connection) => connection.provider === provider);
- const required =
- provider === "telegram"
- ? [value("token")]
- : provider === "whatsapp"
- ? [value("accessToken"), value("appSecret"), value("phoneNumberId"), value("verifyToken")]
- : mode === "hosted"
- ? [value("projectId"), value("projectSecret")]
- : [value("serverUrl"), value("apiKey")];
-
- useEffect(() => {
- setName("");
- setPhotonCredentials("");
- setValues({});
- }, [provider]);
useEffect(() => {
if (!pendingProfile) return;
@@ -154,56 +127,6 @@ export function BotChannelsSettingsPanel() {
setPendingProfile(null);
}, [connections, pendingProfile]);
- const addConnection = async () => {
- if (!environmentId || mutationRef.current) return;
- mutationRef.current = true;
- setBusy(true);
- const random = crypto.getRandomValues(new Uint32Array(4));
- const connectionId = ChannelConnectionId.make(`channel-${[...random].join("-")}`);
- const input =
- provider === "telegram"
- ? { connectionId, name: name.trim(), provider, token: value("token").trim() }
- : provider === "whatsapp"
- ? {
- connectionId,
- name: name.trim(),
- provider,
- accessToken: value("accessToken").trim(),
- appSecret: value("appSecret").trim(),
- phoneNumberId: value("phoneNumberId").trim(),
- verifyToken: value("verifyToken").trim(),
- }
- : mode === "hosted"
- ? {
- connectionId,
- name: name.trim(),
- provider,
- mode,
- projectId: value("projectId").trim(),
- projectSecret: value("projectSecret").trim(),
- }
- : {
- connectionId,
- name: name.trim(),
- provider,
- mode,
- serverUrl: value("serverUrl").trim(),
- apiKey: value("apiKey").trim(),
- ...(value("phone").trim() ? { phone: value("phone").trim() } : {}),
- };
- const result = await saveConnection({ environmentId, input });
- if (result._tag === "Failure") {
- mutationRef.current = false;
- setBusy(false);
- toastManager.add({ type: "error", title: "Could not save channel" });
- return;
- }
- setPendingProfile({ id: connectionId, present: true });
- setName("");
- setPhotonCredentials("");
- setValues({});
- };
-
const removeConnection = async (connection: ChannelConnectionProfile) => {
if (!environmentId || mutationRef.current) return;
mutationRef.current = true;
@@ -224,11 +147,14 @@ export function BotChannelsSettingsPanel() {
const updateAssignment = async (connection: ChannelConnectionProfile, nextBotId: string) => {
if (!environmentId || busyConnectionId) return;
const assignedBot = assignedBotForConnection(connection.id, bots);
+ const assignedBinding = assignedBot?.channelBindings.find(
+ (binding) => binding.connectionId === connection.id,
+ );
if (assignedBot?.id === nextBotId) return;
setBusyConnectionId(connection.id);
if (assignedBot) {
- const result = await disconnect({
+ const result = await detach({
environmentId,
input: { botId: assignedBot.id, provider: connection.provider },
});
@@ -255,6 +181,7 @@ export function BotChannelsSettingsPanel() {
input: {
botId: assignedBot.id,
connectionId: connection.id,
+ ...(assignedBinding?.projectId ? { projectId: assignedBinding.projectId } : {}),
provider: connection.provider,
},
})
@@ -291,21 +218,23 @@ export function BotChannelsSettingsPanel() {
return (
<SettingsPageContainer>
<div className="px-4 py-8 text-sm text-muted-foreground">
- Open this environment on its host to manage channels.
+ This client does not have permission to manage channels.
</div>
</SettingsPageContainer>
);
}
+ const meta = channelProviderMeta(provider);
+
return (
<SettingsPageContainer className="gap-8">
<SettingsSection {...searchableSetting("bot-channels")}>
<div
- className="mx-3 grid grid-cols-3 gap-1 rounded-xl bg-muted/60 p-1 sm:mx-4"
+ className="mx-3 flex flex-wrap gap-1 rounded-xl bg-muted/60 p-1 sm:mx-4"
role="tablist"
aria-label="Channel type"
>
- {CHANNELS.map((channel) => (
+ {CHANNEL_PROVIDER_META.map((channel) => (
<button
key={channel.provider}
type="button"
@@ -313,12 +242,13 @@ export function BotChannelsSettingsPanel() {
aria-selected={provider === channel.provider}
onClick={() => setProvider(channel.provider)}
className={cn(
- "h-8 rounded-lg px-3 text-sm font-medium transition-colors",
+ "flex h-8 shrink-0 items-center gap-1.5 rounded-lg px-3 text-sm font-medium transition-colors",
provider === channel.provider
? "bg-background text-foreground shadow-sm"
: "text-muted-foreground hover:text-foreground",
)}
>
+ <channel.icon className="size-4 shrink-0" aria-hidden />
{channel.label}
</button>
))}
@@ -326,51 +256,101 @@ export function BotChannelsSettingsPanel() {
</SettingsSection>
<SettingsSection
- title={CHANNELS.find((channel) => channel.provider === provider)?.label ?? "Channels"}
+ title={meta.label}
+ icon={<meta.icon className="size-5 shrink-0" aria-hidden />}
+ headerAction={
+ <Button onClick={() => setSetupOpen(true)}>
+ <PlusIcon className="size-4" />
+ Add connection
+ </Button>
+ }
>
+ <p className="mx-3 -mt-1 mb-1 text-sm text-muted-foreground sm:mx-4">{meta.tagline}.</p>
{providerConnections.length === 0 ? (
- <div className="mx-3 rounded-xl border border-dashed px-4 py-6 text-sm text-muted-foreground sm:mx-4">
- No connections.
+ <div className="mx-3 flex flex-col items-start gap-3 rounded-xl border border-dashed px-4 py-6 sm:mx-4">
+ <p className="text-sm text-muted-foreground">No {meta.label} connections yet.</p>
+ <Button variant="outline" onClick={() => setSetupOpen(true)}>
+ Set up {meta.label}
+ </Button>
</div>
) : (
providerConnections.map((connection) => {
const assignedBot = assignedBotForConnection(connection.id, bots);
+ const binding = assignedBot?.channelBindings.find(
+ (candidate) => candidate.connectionId === connection.id,
+ );
+ const externalIdentity = binding?.externalIdentity ?? connection.externalIdentity;
const connectionBusy = busyConnectionId === connection.id;
return (
- <SettingsRow
+ <div
key={connection.id}
- title={connection.name}
- description={`${providerLabel(connection.provider)}${connection.externalIdentity ? ` · ${connection.externalIdentity}` : ""}${assignedBot ? ` · ${channelTestInstructions(connection.provider, assignedBot.name)}` : ""}`}
- status={
- <Badge variant={assignedBot ? "success" : "secondary"} size="sm">
- {assignedBot ? `Assigned to ${assignedBot.name}` : "Unassigned"}
+ className="mx-3 flex flex-col gap-3 rounded-xl border border-border/60 bg-muted/30 px-4 py-3.5 sm:mx-4"
+ >
+ <div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1.5">
+ <meta.icon className="size-5 shrink-0" aria-hidden />
+ <div className="min-w-0 flex-1">
+ <h3 className="truncate text-sm font-medium tracking-[-0.005em] text-foreground">
+ {connection.name}
+ </h3>
+ <p className="truncate text-[13px] text-muted-foreground/80">
+ {providerLabel(connection.provider)}
+ {externalIdentity ? ` · ${externalIdentity}` : ""}
+ </p>
+ </div>
+ <Badge
+ variant={
+ binding?.status === "failed" || binding?.status === "needs-reconnect"
+ ? "warning"
+ : binding?.status === "disconnected"
+ ? "secondary"
+ : assignedBot
+ ? "success"
+ : "secondary"
+ }
+ size="sm"
+ >
+ {binding?.status === "failed"
+ ? "Connection failed"
+ : binding?.status === "needs-reconnect"
+ ? "Needs reconnect"
+ : binding?.status === "disconnected"
+ ? `Disconnected · ${assignedBot?.name ?? "Assigned"}`
+ : assignedBot
+ ? `Assigned to ${assignedBot.name}`
+ : "Unassigned"}
</Badge>
- }
- control={
- <div className="flex items-center gap-2">
- {connection.managementUrl ? (
- <Button
- variant="outline"
- render={
- <a href={connection.managementUrl} target="_blank" rel="noreferrer" />
- }
- >
- Open Photon
- </Button>
- ) : null}
+ </div>
+ {binding?.lastError ? (
+ <p
+ role="status"
+ className="break-words text-xs text-amber-600 dark:text-amber-400"
+ >
+ {binding.lastError}
+ </p>
+ ) : null}
+ {assignedBot ? (
+ <p className="text-[13px] text-muted-foreground/80">
+ {channelTestInstructions(connection.provider, assignedBot.name)}
+ </p>
+ ) : null}
+ <div className="flex min-w-0 flex-wrap items-end gap-x-4 gap-y-2">
+ <div className="flex min-w-0 flex-col gap-1">
+ <span className="text-xs font-medium text-muted-foreground">
+ Bot that answers
+ </span>
<Select
value={assignedBot?.id ?? UNASSIGNED}
onValueChange={(next) => next && void updateAssignment(connection, next)}
>
<SelectTrigger
aria-label={`Assign ${connection.name}`}
- className="w-40"
+ className="w-48"
disabled={connectionBusy}
>
- <SelectValue />
+ <SelectValue>{assignedBot?.name ?? "Choose a bot"}</SelectValue>
</SelectTrigger>
<SelectPopup>
- <SelectItem value={UNASSIGNED}>Unassigned</SelectItem>
+ <SelectItem value={UNASSIGNED}>No bot</SelectItem>
{assignedBot?.archivedAt ? (
<SelectItem value={assignedBot.id}>
{assignedBot.name} (archived)
@@ -383,137 +363,88 @@ export function BotChannelsSettingsPanel() {
))}
</SelectPopup>
</Select>
+ </div>
+ {connection.managementUrl ? (
<Button
variant="outline"
- disabled={busy || connectionBusy || assignedBot !== undefined}
- onClick={() => void removeConnection(connection)}
+ render={
+ <a href={connection.managementUrl} target="_blank" rel="noreferrer" />
+ }
>
- Delete
+ Open provider
</Button>
- </div>
- }
- />
+ ) : null}
+ {assignedBot && binding?.status === "connected" ? (
+ <Button
+ variant="outline"
+ disabled={busy || connectionBusy}
+ onClick={() => {
+ setBusyConnectionId(connection.id);
+ void disconnect({
+ environmentId,
+ input: { botId: assignedBot.id, provider: connection.provider },
+ }).then((result) => {
+ setBusyConnectionId(null);
+ if (result._tag === "Failure") {
+ toastManager.add({
+ type: "error",
+ title: "Could not disconnect channel",
+ });
+ }
+ });
+ }}
+ >
+ Disconnect
+ </Button>
+ ) : null}
+ {assignedBot &&
+ (binding?.status === "failed" ||
+ binding?.status === "needs-reconnect" ||
+ binding?.status === "disconnected") ? (
+ <Button
+ variant="outline"
+ disabled={busy || connectionBusy}
+ onClick={() => {
+ setBusyConnectionId(connection.id);
+ void reconnect({
+ environmentId,
+ input: { botId: assignedBot.id, provider: connection.provider },
+ }).then((result) => {
+ setBusyConnectionId(null);
+ if (result._tag === "Failure") {
+ toastManager.add({
+ type: "error",
+ title: "Could not reconnect channel",
+ });
+ }
+ });
+ }}
+ >
+ Reconnect
+ </Button>
+ ) : null}
+ <Button
+ variant="outline"
+ disabled={busy || connectionBusy || assignedBot !== undefined}
+ onClick={() => void removeConnection(connection)}
+ >
+ Delete
+ </Button>
+ </div>
+ </div>
);
})
)}
</SettingsSection>
- <SettingsSection title="Add connection">
- <SettingsRow
- title={provider === "imessage" ? "Photon" : providerLabel(provider)}
- control={
- <div className="flex w-72 flex-col gap-2">
- <Input
- aria-label="Name"
- placeholder={provider === "imessage" ? "Name, e.g. Work iPhone" : "Name"}
- value={name}
- onChange={(event) => setName(event.currentTarget.value)}
- />
- {provider === "telegram" ? (
- <Input
- type="password"
- placeholder="BotFather token"
- aria-label="Telegram BotFather token"
- value={value("token")}
- onChange={(event) => setValue("token", event.currentTarget.value)}
- />
- ) : null}
- {provider === "imessage" ? (
- <>
- <Select value={mode} onValueChange={(next) => next && setMode(next)}>
- <SelectTrigger aria-label="Photon connection type">
- <SelectValue />
- </SelectTrigger>
- <SelectPopup>
- <SelectItem value="hosted">Photon hosted</SelectItem>
- <SelectItem value="self-hosted">Photon self-hosted</SelectItem>
- </SelectPopup>
- </Select>
- {mode === "hosted" ? (
- <Textarea
- aria-label="Photon hosted credentials"
- className="min-h-20 font-mono text-xs"
- placeholder={"SPECTRUM_PROJECT_ID=...\nSPECTRUM_PROJECT_SECRET=..."}
- rows={2}
- spellCheck={false}
- value={photonCredentials}
- onChange={(event) => {
- const next = event.currentTarget.value;
- const parsed = parsePhotonHostedCredentials(next);
- setPhotonCredentials(next);
- setValues((current) => ({
- ...current,
- projectId: parsed?.projectId ?? "",
- projectSecret: parsed?.projectSecret ?? "",
- }));
- }}
- />
- ) : (
- <>
- <Input
- aria-label="Photon server"
- placeholder="Photon server"
- value={value("serverUrl")}
- onChange={(event) => setValue("serverUrl", event.currentTarget.value)}
- />
- <Input
- aria-label="Photon API key"
- type="password"
- placeholder="Photon API key"
- value={value("apiKey")}
- onChange={(event) => setValue("apiKey", event.currentTarget.value)}
- />
- <Input
- aria-label="Photon phone or line"
- placeholder="Phone or line"
- value={value("phone")}
- onChange={(event) => setValue("phone", event.currentTarget.value)}
- />
- </>
- )}
- </>
- ) : null}
- {provider === "whatsapp" ? (
- <>
- <Input
- aria-label="WhatsApp access token"
- type="password"
- placeholder="Access token"
- value={value("accessToken")}
- onChange={(event) => setValue("accessToken", event.currentTarget.value)}
- />
- <Input
- aria-label="WhatsApp app secret"
- type="password"
- placeholder="App secret"
- value={value("appSecret")}
- onChange={(event) => setValue("appSecret", event.currentTarget.value)}
- />
- <Input
- aria-label="WhatsApp phone number ID"
- placeholder="Phone number ID"
- value={value("phoneNumberId")}
- onChange={(event) => setValue("phoneNumberId", event.currentTarget.value)}
- />
- <Input
- aria-label="WhatsApp verify token"
- type="password"
- placeholder="Verify token"
- value={value("verifyToken")}
- onChange={(event) => setValue("verifyToken", event.currentTarget.value)}
- />
- </>
- ) : null}
- <Button
- disabled={busy || !name.trim() || required.some((item) => !item.trim())}
- onClick={() => void addConnection()}
- >
- Add connection
- </Button>
- </div>
- }
- />
- </SettingsSection>
+ <ChannelSetupDialog
+ environmentId={environmentId}
+ provider={provider}
+ open={setupOpen}
+ onOpenChange={setSetupOpen}
+ bots={activeBots}
+ onSaved={(connectionId) => setPendingProfile({ id: connectionId, present: true })}
+ />
</SettingsPageContainer>
);
}
diff --git a/apps/web/src/components/settings/ChannelSetupDialog.test.tsx b/apps/web/src/components/settings/ChannelSetupDialog.test.tsx
new file mode 100644
index 000000000..dbfc46aa0
--- /dev/null
+++ b/apps/web/src/components/settings/ChannelSetupDialog.test.tsx
@@ -0,0 +1,267 @@
+import { BotId, EnvironmentId } from "@t3tools/contracts";
+import { act, type ReactNode } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+
+const mocks = vi.hoisted(() => ({
+ save: vi.fn<
+ (value: {
+ input: { connectionId: string; token?: string; name: string };
+ }) => Promise<{ _tag: "Success" | "Failure" }>
+ >(),
+ attach:
+ vi.fn<
+ (value: {
+ input: { connectionId: string; botId: string };
+ }) => Promise<{ _tag: "Success" | "Failure" }>
+ >(),
+ toast: vi.fn(),
+ buttons: new Map<string, { onClick?: () => void; disabled?: boolean }>(),
+ inputs: new Map<string, { onChange: (event: { currentTarget: { value: string } }) => void }>(),
+ changeOpen: (_open: boolean) => {},
+}));
+
+vi.mock("../../state/bots", () => ({
+ botEnvironment: { channels: { saveConnection: "save", attach: "attach" } },
+}));
+vi.mock("../../state/use-atom-command", () => ({
+ useAtomCommand: (command: string) => (command === "save" ? mocks.save : mocks.attach),
+}));
+vi.mock("./BotChannelsSettings", () => ({ parsePhotonHostedCredentials: vi.fn() }));
+vi.mock("../ui/toast", () => ({ toastManager: { add: mocks.toast } }));
+vi.mock("../ui/button", () => ({
+ Button: (props: { children: ReactNode; onClick?: () => void; disabled?: boolean }) => {
+ if (typeof props.children === "string") mocks.buttons.set(props.children, props);
+ return null;
+ },
+}));
+vi.mock("../ui/input", () => ({
+ Input: (props: {
+ "aria-label": string;
+ onChange: (event: { currentTarget: { value: string } }) => void;
+ }) => {
+ mocks.inputs.set(props["aria-label"], props);
+ return null;
+ },
+}));
+vi.mock("../ui/dialog", () => ({
+ Dialog: (props: {
+ children: ReactNode;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ }) => {
+ mocks.changeOpen = props.onOpenChange;
+ return props.open ? props.children : null;
+ },
+ DialogPopup: ({ children }: { children: ReactNode }) => children,
+ DialogHeader: ({ children }: { children: ReactNode }) => children,
+ DialogTitle: () => null,
+}));
+vi.mock("../ui/select", () => ({
+ Select: () => null,
+ SelectItem: () => null,
+ SelectPopup: () => null,
+ SelectTrigger: () => null,
+ SelectValue: () => null,
+}));
+
+import { ChannelSetupDialog } from "./ChannelSetupDialog";
+
+// This node-only suite gives ReactDOM a host without a browser DOM dependency.
+class TestNode {
+ parentNode: TestNode | null = null;
+ childNodes: TestNode[] = [];
+ readonly namespaceURI = "http://www.w3.org/1999/xhtml";
+ readonly style = {};
+ readonly tagName: string;
+ readonly nodeName: string;
+ private text = "";
+
+ constructor(
+ name: string,
+ readonly ownerDocument: TestNode | null = null,
+ readonly nodeType = 1,
+ ) {
+ this.tagName = name.toUpperCase();
+ this.nodeName = this.tagName;
+ }
+ get textContent(): string {
+ return this.text + this.childNodes.map((node) => node.textContent).join("");
+ }
+ set textContent(value: string) {
+ this.text = value;
+ this.childNodes = [];
+ }
+ appendChild(child: TestNode) {
+ child.parentNode = this;
+ this.childNodes.push(child);
+ return child;
+ }
+ insertBefore(child: TestNode, before: TestNode) {
+ child.parentNode = this;
+ this.childNodes.splice(this.childNodes.indexOf(before), 0, child);
+ return child;
+ }
+ removeChild(child: TestNode) {
+ this.childNodes.splice(this.childNodes.indexOf(child), 1);
+ child.parentNode = null;
+ return child;
+ }
+ createElement(name: string) {
+ return new TestNode(name, this);
+ }
+ createTextNode(text: string) {
+ const node = new TestNode("#text", this, 3);
+ node.textContent = text;
+ return node;
+ }
+ addEventListener() {}
+ removeEventListener() {}
+ setAttribute() {}
+ removeAttribute() {}
+}
+
+let root: import("react-dom/client").Root;
+let container: TestNode;
+const onSaved = vi.fn();
+const onOpenChange = vi.fn();
+const props = {
+ environmentId: EnvironmentId.make("test-environment"),
+ provider: "telegram" as const,
+ bots: [{ id: BotId.make("test-bot"), name: "Test bot" }],
+ open: true,
+ onSaved,
+ onOpenChange,
+};
+
+async function click(label: string) {
+ const button = mocks.buttons.get(label);
+ expect(button).toBeDefined();
+ expect(button?.disabled).not.toBe(true);
+ await act(async () => {
+ button?.onClick?.();
+ });
+}
+
+async function fill(label: string, value: string) {
+ const input = mocks.inputs.get(label);
+ expect(input).toBeDefined();
+ await act(() => input?.onChange({ currentTarget: { value } }));
+}
+
+async function completeSetup() {
+ await click("Continue");
+ await fill("Telegram Bot token", "test-token");
+ await click("Continue");
+ await fill("Connection name", "Test line");
+}
+
+beforeEach(async () => {
+ mocks.save.mockReset().mockResolvedValue({ _tag: "Success" });
+ mocks.attach.mockReset().mockResolvedValue({ _tag: "Success" });
+ mocks.toast.mockReset();
+ mocks.buttons.clear();
+ mocks.inputs.clear();
+ onSaved.mockReset();
+ onOpenChange.mockReset();
+ const document = new TestNode("#document", null, 9);
+ vi.stubGlobal("document", document);
+ vi.stubGlobal("window", {
+ document,
+ HTMLIFrameElement: TestNode,
+ addEventListener() {},
+ removeEventListener() {},
+ });
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ container = document.createElement("div");
+ const { createRoot } = await import("react-dom/client");
+ root = createRoot(container as unknown as Element);
+ await act(() => root.render(<ChannelSetupDialog {...props} />));
+});
+
+afterEach(async () => {
+ await act(() => root.unmount());
+ vi.unstubAllGlobals();
+});
+
+describe("ChannelSetupDialog recovery", () => {
+ it("retries the saved profile without saving another connection or blaming credentials", async () => {
+ mocks.attach.mockResolvedValueOnce({ _tag: "Failure" });
+ await completeSetup();
+ await click("Connect");
+ expect(onOpenChange).not.toHaveBeenCalled();
+ expect(container.textContent).toContain("Connection saved. Could not connect Test bot.");
+ expect(container.textContent).not.toMatch(/rejected|tokens|credentials/i);
+ const connectionId = mocks.save.mock.calls[0]![0].input.connectionId;
+
+ await click("Connect");
+
+ expect(mocks.save).toHaveBeenCalledTimes(1);
+ expect(mocks.attach.mock.calls.map(([value]) => value.input.connectionId)).toEqual([
+ connectionId,
+ connectionId,
+ ]);
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+
+ it("updates the same saved profile when credentials are corrected before retry", async () => {
+ mocks.attach.mockResolvedValueOnce({ _tag: "Failure" });
+ await completeSetup();
+ await click("Connect");
+ const connectionId = mocks.save.mock.calls[0]![0].input.connectionId;
+ await click("Back");
+ await fill("Telegram Bot token", "corrected-token");
+ await click("Continue");
+ await click("Connect");
+
+ expect(mocks.save).toHaveBeenCalledTimes(2);
+ expect(mocks.save.mock.calls[1]![0].input).toMatchObject({
+ connectionId,
+ token: "corrected-token",
+ });
+ expect(mocks.attach.mock.calls[1]![0].input.connectionId).toBe(connectionId);
+ });
+
+ it("does not attach or retain a profile when saving fails", async () => {
+ mocks.save.mockResolvedValueOnce({ _tag: "Failure" });
+ await completeSetup();
+ await click("Connect");
+ expect(mocks.attach).not.toHaveBeenCalled();
+ expect(onSaved).not.toHaveBeenCalled();
+ await click("Connect");
+ expect(mocks.save).toHaveBeenCalledTimes(2);
+ expect(mocks.attach).toHaveBeenCalledTimes(1);
+ });
+
+ it("keeps the pending operation when dismissal is attempted", async () => {
+ let finish!: (value: { _tag: "Success" | "Failure" }) => void;
+ mocks.attach.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ await completeSetup();
+ await click("Connect");
+ await act(() => mocks.changeOpen(false));
+ expect(onOpenChange).not.toHaveBeenCalled();
+ expect(mocks.buttons.get("Connect")?.disabled).toBe(true);
+ await act(async () => {
+ finish({ _tag: "Failure" });
+ });
+ await click("Connect");
+ expect(mocks.save).toHaveBeenCalledTimes(1);
+ });
+
+ it("starts a new profile after a failed setup is dismissed and reopened", async () => {
+ mocks.attach.mockResolvedValueOnce({ _tag: "Failure" });
+ await completeSetup();
+ await click("Connect");
+ const firstId = mocks.save.mock.calls[0]![0].input.connectionId;
+ await act(() => mocks.changeOpen(false));
+ await act(() => root.render(<ChannelSetupDialog {...props} open={false} />));
+ await act(() => root.render(<ChannelSetupDialog {...props} />));
+ await completeSetup();
+ await click("Connect");
+ expect(mocks.save.mock.calls[1]![0].input.connectionId).not.toBe(firstId);
+ });
+});
diff --git a/apps/web/src/components/settings/ChannelSetupDialog.tsx b/apps/web/src/components/settings/ChannelSetupDialog.tsx
new file mode 100644
index 000000000..01a923253
--- /dev/null
+++ b/apps/web/src/components/settings/ChannelSetupDialog.tsx
@@ -0,0 +1,371 @@
+import {
+ BotId,
+ ChannelConnectionId,
+ type ChannelProvider,
+ type EnvironmentId,
+} from "@t3tools/contracts";
+import { ExternalLinkIcon } from "lucide-react";
+import { useRef, useState } from "react";
+
+import { cn } from "../../lib/utils";
+import { botEnvironment } from "../../state/bots";
+import { useAtomCommand } from "../../state/use-atom-command";
+import { Button } from "../ui/button";
+import { Dialog, DialogHeader, DialogPopup, DialogTitle } from "../ui/dialog";
+import { Input } from "../ui/input";
+import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
+import { Textarea } from "../ui/textarea";
+import { toastManager } from "../ui/toast";
+import { parsePhotonHostedCredentials } from "./BotChannelsSettings";
+import { channelProviderMeta, discordInviteUrl, slackPasteTarget } from "./channelProviderMeta";
+
+const STEPS = ["Set up", "Credentials", "Connect"] as const;
+const CONNECT_LATER = "connect-later";
+
+export function buildChannelConnectionSaveInput(input: {
+ readonly connectionId: ChannelConnectionId;
+ readonly name: string;
+ readonly provider: ChannelProvider;
+ readonly mode: "hosted" | "self-hosted";
+ readonly values: Record<string, string>;
+}) {
+ const { connectionId, name, provider, mode, values } = input;
+ const value = (key: string) => (values[key] ?? "").trim();
+ if (provider === "telegram") return { connectionId, name, provider, token: value("token") };
+ if (provider === "whatsapp") {
+ return {
+ connectionId,
+ name,
+ provider,
+ accessToken: value("accessToken"),
+ appSecret: value("appSecret"),
+ phoneNumberId: value("phoneNumberId"),
+ verifyToken: value("verifyToken"),
+ };
+ }
+ if (provider === "slack") {
+ return {
+ connectionId,
+ name,
+ provider,
+ botToken: value("botToken"),
+ appToken: value("appToken"),
+ };
+ }
+ if (provider === "discord") {
+ return {
+ connectionId,
+ name,
+ provider,
+ applicationId: value("applicationId"),
+ publicKey: value("publicKey"),
+ botToken: value("botToken"),
+ };
+ }
+ return mode === "hosted"
+ ? {
+ connectionId,
+ name,
+ provider,
+ mode,
+ projectId: value("projectId"),
+ projectSecret: value("projectSecret"),
+ }
+ : {
+ connectionId,
+ name,
+ provider,
+ mode,
+ serverUrl: value("serverUrl"),
+ apiKey: value("apiKey"),
+ ...(value("phone") ? { phone: value("phone") } : {}),
+ };
+}
+
+export function ChannelSetupDialog({
+ environmentId,
+ provider,
+ bots,
+ open,
+ onOpenChange,
+ onSaved,
+}: {
+ readonly environmentId: EnvironmentId;
+ readonly provider: ChannelProvider;
+ readonly bots: ReadonlyArray<{ readonly id: BotId; readonly name: string }>;
+ readonly open: boolean;
+ readonly onOpenChange: (open: boolean) => void;
+ readonly onSaved: (connectionId: ChannelConnectionId) => void;
+}) {
+ const meta = channelProviderMeta(provider);
+ const saveConnection = useAtomCommand(botEnvironment.channels.saveConnection, {
+ reportFailure: false,
+ });
+ const attach = useAtomCommand(botEnvironment.channels.attach, { reportFailure: false });
+ const [botId, setBotId] = useState<string>(() => bots[0]?.id ?? CONNECT_LATER);
+ const [step, setStep] = useState(0);
+ const [mode, setMode] = useState<"hosted" | "self-hosted">("hosted");
+ const [name, setName] = useState("");
+ const [photonCredentials, setPhotonCredentials] = useState("");
+ const [values, setValues] = useState<Record<string, string>>({});
+ const [busy, setBusy] = useState(false);
+ const [connectError, setConnectError] = useState<string | null>(null);
+ const savedConnection = useRef<{
+ connectionId: ChannelConnectionId;
+ name: string;
+ mode: typeof mode;
+ values: typeof values;
+ } | null>(null);
+ const value = (key: string) => values[key] ?? "";
+ const setValue = (key: string, next: string) =>
+ setValues((current) => ({ ...current, [key]: next }));
+
+ const fields = meta.fields.filter((field) => provider !== "imessage" || field.mode === mode);
+ const credentialsComplete = fields.every((field) => field.optional || value(field.key).trim());
+ const inviteUrl = provider === "discord" ? discordInviteUrl(value("applicationId")) : null;
+
+ const reset = () => {
+ savedConnection.current = null;
+ setStep(0);
+ setMode("hosted");
+ setName("");
+ setPhotonCredentials("");
+ setValues({});
+ setBotId(bots[0]?.id ?? CONNECT_LATER);
+ setConnectError(null);
+ setBusy(false);
+ };
+
+ const save = async () => {
+ if (busy || !name.trim() || !credentialsComplete) return;
+ setBusy(true);
+ setConnectError(null);
+ const saved = savedConnection.current;
+ const connectionId =
+ saved?.connectionId ??
+ ChannelConnectionId.make(
+ `channel-${[...crypto.getRandomValues(new Uint32Array(4))].join("-")}`,
+ );
+ if (!saved || saved.name !== name.trim() || saved.mode !== mode || saved.values !== values) {
+ const result = await saveConnection({
+ environmentId,
+ input: buildChannelConnectionSaveInput({
+ connectionId,
+ name: name.trim(),
+ provider,
+ mode,
+ values,
+ }),
+ });
+ if (result._tag === "Failure") {
+ setBusy(false);
+ toastManager.add({ type: "error", title: "Could not save channel" });
+ return;
+ }
+ savedConnection.current = { connectionId, name: name.trim(), mode, values };
+ }
+ if (botId !== CONNECT_LATER) {
+ const attached = await attach({
+ environmentId,
+ input: { botId: BotId.make(botId), connectionId, provider },
+ });
+ if (attached._tag === "Failure") {
+ setBusy(false);
+ onSaved(connectionId);
+ setConnectError(
+ `Connection saved. Could not connect ${bots.find((bot) => bot.id === botId)?.name ?? "the bot"}. Try again or check the connection settings.`,
+ );
+ return;
+ }
+ }
+ setBusy(false);
+ onSaved(connectionId);
+ onOpenChange(false);
+ reset();
+ };
+
+ return (
+ <Dialog
+ open={open}
+ onOpenChange={(next) => {
+ if (busy) return;
+ onOpenChange(next);
+ if (!next) reset();
+ }}
+ >
+ <DialogPopup className="max-w-md">
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2.5">
+ <meta.icon className="size-5 shrink-0" aria-hidden />
+ Connect {meta.label}
+ </DialogTitle>
+ </DialogHeader>
+ <div className="flex flex-col gap-4 px-6 pb-6">
+ <div
+ className="flex items-center gap-1.5"
+ aria-label={`Step ${step + 1} of ${STEPS.length}`}
+ >
+ {STEPS.map((label, index) => (
+ <span
+ key={label}
+ className={cn(
+ "h-1 flex-1 rounded-full transition-colors",
+ index <= step ? "bg-foreground/70" : "bg-muted",
+ )}
+ />
+ ))}
+ </div>
+
+ {step === 0 ? (
+ <div className="flex flex-col gap-4">
+ <p className="text-sm text-muted-foreground">{meta.tagline}.</p>
+ <ol className="flex list-none flex-col gap-2.5">
+ {meta.steps.map((instruction, index) => (
+ <li key={instruction} className="flex gap-2.5 text-sm">
+ <span className="flex size-5 shrink-0 items-center justify-center rounded-full bg-muted text-[11px] font-medium text-muted-foreground">
+ {index + 1}
+ </span>
+ <span className="min-w-0">{instruction}</span>
+ </li>
+ ))}
+ </ol>
+ <Button
+ variant="outline"
+ render={<a href={meta.consoleUrl} target="_blank" rel="noreferrer" />}
+ >
+ <ExternalLinkIcon className="size-4" />
+ {meta.consoleLabel}
+ </Button>
+ </div>
+ ) : null}
+
+ {step === 1 ? (
+ <div className="flex flex-col gap-2.5">
+ {provider === "imessage" ? (
+ <Select value={mode} onValueChange={(next) => next && setMode(next)}>
+ <SelectTrigger aria-label="Photon connection type">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectPopup>
+ <SelectItem value="hosted">Photon hosted</SelectItem>
+ <SelectItem value="self-hosted">Photon self-hosted</SelectItem>
+ </SelectPopup>
+ </Select>
+ ) : null}
+ {provider === "imessage" && mode === "hosted" ? (
+ <Textarea
+ aria-label="Photon hosted credentials"
+ className="min-h-20 font-mono text-xs"
+ placeholder={"SPECTRUM_PROJECT_ID=...\nSPECTRUM_PROJECT_SECRET=..."}
+ rows={2}
+ spellCheck={false}
+ value={photonCredentials}
+ onChange={(event) => {
+ const next = event.currentTarget.value;
+ const parsed = parsePhotonHostedCredentials(next);
+ setPhotonCredentials(next);
+ setValues((current) => ({
+ ...current,
+ projectId: parsed?.projectId ?? "",
+ projectSecret: parsed?.projectSecret ?? "",
+ }));
+ }}
+ />
+ ) : (
+ fields.map((field) => (
+ <Input
+ key={field.key}
+ aria-label={`${meta.label} ${field.label}`}
+ type={field.sensitive ? "password" : "text"}
+ placeholder={field.placeholder}
+ value={value(field.key)}
+ onChange={(event) => setValue(field.key, event.currentTarget.value)}
+ onPaste={
+ provider === "slack"
+ ? (event) => {
+ const target = slackPasteTarget(event.clipboardData.getData("text"));
+ if (target && target !== field.key) {
+ event.preventDefault();
+ setValue(target, event.clipboardData.getData("text").trim());
+ }
+ }
+ : undefined
+ }
+ />
+ ))
+ )}
+ {inviteUrl ? (
+ <Button
+ variant="outline"
+ render={<a href={inviteUrl} target="_blank" rel="noreferrer" />}
+ >
+ <ExternalLinkIcon className="size-4" />
+ Invite bot to your server
+ </Button>
+ ) : null}
+ </div>
+ ) : null}
+
+ {step === 2 ? (
+ <div className="flex flex-col gap-2.5">
+ <Input
+ aria-label="Connection name"
+ placeholder={`Name, e.g. ${meta.label} line`}
+ value={name}
+ onChange={(event) => setName(event.currentTarget.value)}
+ />
+ {connectError ? (
+ <p role="alert" className="text-sm text-amber-600 dark:text-amber-400">
+ {connectError}
+ </p>
+ ) : null}
+ <div className="flex flex-col gap-1">
+ <span className="text-xs font-medium text-muted-foreground">Bot that answers</span>
+ <Select value={botId} onValueChange={(next) => next && setBotId(next)}>
+ <SelectTrigger aria-label="Bot that answers">
+ <SelectValue>
+ {bots.find((bot) => bot.id === botId)?.name ?? "Connect later"}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectPopup>
+ <SelectItem value={CONNECT_LATER}>Connect later</SelectItem>
+ {bots.map((bot) => (
+ <SelectItem key={bot.id} value={bot.id}>
+ {bot.name}
+ </SelectItem>
+ ))}
+ </SelectPopup>
+ </Select>
+ </div>
+ </div>
+ ) : null}
+
+ <div className="flex items-center justify-between gap-2">
+ <Button
+ variant="ghost"
+ disabled={step === 0 || busy}
+ onClick={() => setStep((current) => Math.max(0, current - 1))}
+ >
+ Back
+ </Button>
+ {step < 2 ? (
+ <Button
+ disabled={step === 1 && !credentialsComplete}
+ onClick={() => setStep((current) => current + 1)}
+ >
+ Continue
+ </Button>
+ ) : (
+ <Button
+ disabled={busy || !name.trim() || !credentialsComplete}
+ onClick={() => void save()}
+ >
+ {botId === CONNECT_LATER ? "Save connection" : "Connect"}
+ </Button>
+ )}
+ </div>
+ </div>
+ </DialogPopup>
+ </Dialog>
+ );
+}
diff --git a/apps/web/src/components/settings/channelProviderMeta.test.tsx b/apps/web/src/components/settings/channelProviderMeta.test.tsx
new file mode 100644
index 000000000..397d1c2cb
--- /dev/null
+++ b/apps/web/src/components/settings/channelProviderMeta.test.tsx
@@ -0,0 +1,137 @@
+import { ChannelConnectionId } from "@t3tools/contracts";
+import { describe, expect, it } from "vite-plus/test";
+
+import { buildChannelConnectionSaveInput } from "./ChannelSetupDialog";
+import {
+ CHANNEL_PROVIDER_META,
+ channelProviderMeta,
+ discordInviteUrl,
+ slackPasteTarget,
+} from "./channelProviderMeta";
+
+describe("channel provider metadata", () => {
+ it("describes all five providers with icons, steps, and console links", () => {
+ expect(CHANNEL_PROVIDER_META.map((meta) => meta.provider)).toEqual([
+ "imessage",
+ "whatsapp",
+ "telegram",
+ "slack",
+ "discord",
+ ]);
+ for (const meta of CHANNEL_PROVIDER_META) {
+ expect(meta.icon).toBeTypeOf("function");
+ expect(meta.steps.length).toBeGreaterThanOrEqual(2);
+ expect(meta.consoleUrl).toMatch(/^https:\/\//u);
+ expect(meta.fields.length).toBeGreaterThan(0);
+ }
+ });
+
+ it("splits Photon fields by connection mode", () => {
+ const fields = channelProviderMeta("imessage").fields;
+ expect(fields.filter((field) => field.mode === "hosted").map((field) => field.key)).toEqual([
+ "projectId",
+ "projectSecret",
+ ]);
+ expect(
+ fields.filter((field) => field.mode === "self-hosted").map((field) => field.key),
+ ).toEqual(["serverUrl", "apiKey", "phone"]);
+ expect(fields.find((field) => field.key === "phone")?.optional).toBe(true);
+ });
+});
+
+describe("discordInviteUrl", () => {
+ it("builds an invite link only from a plausible application ID", () => {
+ expect(discordInviteUrl("123456789012345678")).toBe(
+ "https://discord.com/oauth2/authorize?client_id=123456789012345678&scope=bot&permissions=397552987200",
+ );
+ expect(discordInviteUrl(" 123456789012345678 ")).toContain("123456789012345678");
+ expect(discordInviteUrl("not-an-id")).toBeNull();
+ expect(discordInviteUrl("")).toBeNull();
+ expect(discordInviteUrl("123")).toBeNull();
+ });
+});
+
+describe("slackPasteTarget", () => {
+ it("routes tokens by prefix and ignores everything else", () => {
+ expect(slackPasteTarget("xoxb-1234-abc")).toBe("botToken");
+ expect(slackPasteTarget(" xapp-1-A1-xyz ")).toBe("appToken");
+ expect(slackPasteTarget("hello")).toBeNull();
+ });
+});
+
+describe("buildChannelConnectionSaveInput", () => {
+ const connectionId = ChannelConnectionId.make("channel-test");
+
+ it("builds each provider's command shape and trims values", () => {
+ expect(
+ buildChannelConnectionSaveInput({
+ connectionId,
+ name: "Line",
+ provider: "telegram",
+ mode: "hosted",
+ values: { token: " 123:abc " },
+ }),
+ ).toEqual({ connectionId, name: "Line", provider: "telegram", token: "123:abc" });
+ expect(
+ buildChannelConnectionSaveInput({
+ connectionId,
+ name: "Line",
+ provider: "slack",
+ mode: "hosted",
+ values: { botToken: "xoxb-1", appToken: "xapp-1" },
+ }),
+ ).toMatchObject({ provider: "slack", botToken: "xoxb-1", appToken: "xapp-1" });
+ expect(
+ buildChannelConnectionSaveInput({
+ connectionId,
+ name: "Line",
+ provider: "discord",
+ mode: "hosted",
+ values: { applicationId: "1", publicKey: "2", botToken: "3" },
+ }),
+ ).toMatchObject({ provider: "discord", applicationId: "1", publicKey: "2", botToken: "3" });
+ expect(
+ buildChannelConnectionSaveInput({
+ connectionId,
+ name: "Line",
+ provider: "whatsapp",
+ mode: "hosted",
+ values: { accessToken: "a", appSecret: "b", phoneNumberId: "c", verifyToken: "d" },
+ }),
+ ).toMatchObject({ provider: "whatsapp", accessToken: "a", verifyToken: "d" });
+ });
+
+ it("builds both Photon modes and omits a blank phone", () => {
+ expect(
+ buildChannelConnectionSaveInput({
+ connectionId,
+ name: "Line",
+ provider: "imessage",
+ mode: "hosted",
+ values: { projectId: "p", projectSecret: "s" },
+ }),
+ ).toEqual({
+ connectionId,
+ name: "Line",
+ provider: "imessage",
+ mode: "hosted",
+ projectId: "p",
+ projectSecret: "s",
+ });
+ const selfHosted = buildChannelConnectionSaveInput({
+ connectionId,
+ name: "Line",
+ provider: "imessage",
+ mode: "self-hosted",
+ values: { serverUrl: "https://x", apiKey: "k", phone: " " },
+ });
+ expect(selfHosted).toEqual({
+ connectionId,
+ name: "Line",
+ provider: "imessage",
+ mode: "self-hosted",
+ serverUrl: "https://x",
+ apiKey: "k",
+ });
+ });
+});
diff --git a/apps/web/src/components/settings/channelProviderMeta.tsx b/apps/web/src/components/settings/channelProviderMeta.tsx
new file mode 100644
index 000000000..f0cd81c11
--- /dev/null
+++ b/apps/web/src/components/settings/channelProviderMeta.tsx
@@ -0,0 +1,184 @@
+import type { ChannelProvider } from "@t3tools/contracts";
+
+import {
+ DiscordIcon,
+ IMessageIcon,
+ SlackIcon,
+ TelegramIcon,
+ WhatsAppIcon,
+ type Icon,
+} from "../Icons";
+
+export interface ChannelCredentialField {
+ readonly key: string;
+ readonly label: string;
+ readonly placeholder: string;
+ readonly sensitive: boolean;
+ /** Restrict the field to one Photon connection type. */
+ readonly mode?: "hosted" | "self-hosted";
+ readonly optional?: boolean;
+}
+
+export interface ChannelProviderMeta {
+ readonly provider: ChannelProvider;
+ readonly label: string;
+ readonly icon: Icon;
+ readonly tagline: string;
+ readonly consoleLabel: string;
+ readonly consoleUrl: string;
+ readonly steps: ReadonlyArray<string>;
+ readonly fields: ReadonlyArray<ChannelCredentialField>;
+}
+
+export const CHANNEL_PROVIDER_META: ReadonlyArray<ChannelProviderMeta> = [
+ {
+ provider: "imessage",
+ label: "iMessage",
+ icon: IMessageIcon,
+ tagline: "Direct messages through Photon",
+ consoleLabel: "Open Photon dashboard",
+ consoleUrl: "https://photon.chat",
+ steps: [
+ "Create a Photon project, or run a self-hosted Photon server.",
+ "Copy the hosted project credentials, or your server URL and API key.",
+ "Paste the credentials here.",
+ ],
+ fields: [
+ {
+ key: "projectId",
+ label: "Project ID",
+ placeholder: "SPECTRUM_PROJECT_ID",
+ sensitive: false,
+ mode: "hosted",
+ },
+ {
+ key: "projectSecret",
+ label: "Project secret",
+ placeholder: "SPECTRUM_PROJECT_SECRET",
+ sensitive: true,
+ mode: "hosted",
+ },
+ {
+ key: "serverUrl",
+ label: "Server URL",
+ placeholder: "https://imessage.example.com",
+ sensitive: false,
+ mode: "self-hosted",
+ },
+ {
+ key: "apiKey",
+ label: "API key",
+ placeholder: "API key",
+ sensitive: true,
+ mode: "self-hosted",
+ },
+ {
+ key: "phone",
+ label: "Phone (optional)",
+ placeholder: "+15555550100",
+ sensitive: false,
+ mode: "self-hosted",
+ optional: true,
+ },
+ ],
+ },
+ {
+ provider: "whatsapp",
+ label: "WhatsApp",
+ icon: WhatsAppIcon,
+ tagline: "Direct messages through the WhatsApp Business Cloud API",
+ consoleLabel: "Open Meta app dashboard",
+ consoleUrl: "https://developers.facebook.com/apps",
+ steps: [
+ "Create a Meta app with WhatsApp and copy the access token, app secret, and phone number ID.",
+ "Choose a verify token and configure the webhook URL shown in the docs.",
+ "Paste all four values here.",
+ ],
+ fields: [
+ { key: "accessToken", label: "Access token", placeholder: "Access token", sensitive: true },
+ { key: "appSecret", label: "App secret", placeholder: "App secret", sensitive: true },
+ {
+ key: "phoneNumberId",
+ label: "Phone number ID",
+ placeholder: "Phone number ID",
+ sensitive: false,
+ },
+ { key: "verifyToken", label: "Verify token", placeholder: "Verify token", sensitive: true },
+ ],
+ },
+ {
+ provider: "telegram",
+ label: "Telegram",
+ icon: TelegramIcon,
+ tagline: "Direct messages through a BotFather bot",
+ consoleLabel: "Open BotFather",
+ consoleUrl: "https://t.me/BotFather",
+ steps: [
+ "Message @BotFather and send /newbot.",
+ "Copy the bot token BotFather returns.",
+ "Paste the token here.",
+ ],
+ fields: [{ key: "token", label: "Bot token", placeholder: "123456:ABC…", sensitive: true }],
+ },
+ {
+ provider: "slack",
+ label: "Slack",
+ icon: SlackIcon,
+ tagline: "Direct messages and mentions over Socket Mode",
+ consoleLabel: "Open Slack app console",
+ consoleUrl: "https://api.slack.com/apps",
+ steps: [
+ "Create a Slack app, enable Socket Mode, and create an app-level token with the connections scope.",
+ "Install the app to your workspace and copy the bot token.",
+ "Subscribe the app to direct-message and mention events, then paste both tokens here.",
+ ],
+ fields: [
+ { key: "botToken", label: "Bot token", placeholder: "xoxb-…", sensitive: true },
+ { key: "appToken", label: "App-level token", placeholder: "xapp-…", sensitive: true },
+ ],
+ },
+ {
+ provider: "discord",
+ label: "Discord",
+ icon: DiscordIcon,
+ tagline: "Direct messages and mentions through the Gateway",
+ consoleLabel: "Open Discord developer portal",
+ consoleUrl: "https://discord.com/developers/applications",
+ steps: [
+ "Create a Discord application and bot, then enable Message Content Intent.",
+ "Copy the application ID, public key, and bot token.",
+ "Paste them here, then invite the bot with the generated link.",
+ ],
+ fields: [
+ {
+ key: "applicationId",
+ label: "Application ID",
+ placeholder: "Application ID",
+ sensitive: false,
+ },
+ { key: "publicKey", label: "Public key", placeholder: "Public key", sensitive: false },
+ { key: "botToken", label: "Bot token", placeholder: "Bot token", sensitive: true },
+ ],
+ },
+];
+
+export function channelProviderMeta(provider: ChannelProvider): ChannelProviderMeta {
+ return (
+ CHANNEL_PROVIDER_META.find((meta) => meta.provider === provider) ?? CHANNEL_PROVIDER_META[0]!
+ );
+}
+
+/** Permissions: view channels, send messages, read history, threads, reactions. */
+export function discordInviteUrl(applicationId: string): string | null {
+ const trimmed = applicationId.trim();
+ if (!/^\d{15,21}$/u.test(trimmed)) return null;
+ return `https://discord.com/oauth2/authorize?client_id=${trimmed}&scope=bot&permissions=397552987200`;
+}
+
+/** Route a pasted Slack token to its field by prefix. */
+export function slackPasteTarget(pasted: string): "botToken" | "appToken" | null {
+ const value = pasted.trim();
+ if (value.startsWith("xoxb-")) return "botToken";
+ if (value.startsWith("xapp-")) return "appToken";
+ return null;
+}
diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts
index 25b7d4f4f..73668564f 100644
--- a/apps/web/src/components/settings/settingsSearch.ts
+++ b/apps/web/src/components/settings/settingsSearch.ts
@@ -290,7 +290,7 @@ export const SETTINGS_SEARCH_ITEMS = [
id: "bot-channels",
title: "Bot channels",
to: "/settings/channels",
- keywords: ["Telegram", "iMessage", "Photon", "WhatsApp"],
+ keywords: ["Telegram", "iMessage", "Photon", "WhatsApp", "Slack", "Discord"],
},
{
id: "source-control",
diff --git a/apps/web/src/components/sidebar/SidebarChrome.test.ts b/apps/web/src/components/sidebar/SidebarChrome.test.ts
index d4177676a..01ee2e0b0 100644
--- a/apps/web/src/components/sidebar/SidebarChrome.test.ts
+++ b/apps/web/src/components/sidebar/SidebarChrome.test.ts
@@ -150,6 +150,20 @@ describe("sidebar footer", () => {
expect(source).not.toContain('openSettings("inbox")');
});
+ it("keeps roster synchronization mounted when the mobile sidebar is closed", () => {
+ const layoutSource = NodeFS.readFileSync(
+ new URL("../AppSidebarLayout.tsx", import.meta.url),
+ "utf8",
+ );
+ const rosterSource = NodeFS.readFileSync(
+ new URL("../roster/BotRosterSidebar.tsx", import.meta.url),
+ "utf8",
+ );
+
+ expect(layoutSource).toContain(" useServerRosterSync();");
+ expect(rosterSource).not.toContain("useServerRosterSync");
+ });
+
it("creates manual bots with approval required without adding a first-run bot", () => {
const rosterSource = NodeFS.readFileSync(
new URL("../roster/BotRosterSidebar.tsx", import.meta.url),
diff --git a/docs/README.md b/docs/README.md
index 4126fe119..ef1ed2fcc 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -4,6 +4,7 @@
- [Install and first run](./user/install.md)
- [Configure bots](./user/bots.md)
+- [Bot channels](./user/channels.md)
- Providers: [Codex](./user/providers-codex.md) · [Claude](./user/providers-claude.md)
- [Permission modes](./user/permission-modes.md)
- [Configure sandboxes](./user/sandboxes.md)
@@ -37,6 +38,7 @@ policy in [CONTRIBUTING.md](../CONTRIBUTING.md); agent rules in [AGENTS.md](../A
- [Local verification](./internals/verification.md)
- [Connection runtime](./internals/connection-runtime.md)
- [Providers](./internals/providers.md)
+- [External channels](./internals/channels.md)
- [Plugin lifecycle verification](./internals/plugin-lifecycle-verification.md)
- [Remote environments](./internals/remote.md)
- [Server updates](./internals/server-updates.md)
diff --git a/docs/internals/channels.md b/docs/internals/channels.md
new file mode 100644
index 000000000..db6a13eff
--- /dev/null
+++ b/docs/internals/channels.md
@@ -0,0 +1,66 @@
+# External channels
+
+External channels connect a messaging conversation to normal Akeru orchestration. A channel adapter never calls a provider agent directly.
+
+## Durable model
+
+A reusable connection profile contains safe display data. Credentials live in the environment secret store. A bot binding selects the provider, connection, and project.
+
+An external conversation maps to a deterministic Akeru thread using the bot, project, provider, and provider conversation identity. A provider message identity derives the turn command and message identities. The orchestration command receipt makes repeated delivery idempotent across process restarts.
+
+The Akeru thread is the conversation. A turn is one unit of work. There is no channel session model or separate external inbox.
+
+## Runtime boundary
+
+`ChannelRuntime` owns provider transports and normalizes inbound messages to:
+
+- provider;
+- connection and selected project;
+- external conversation identity;
+- external message identity;
+- sender identity and display name;
+- supported text content.
+
+The runtime dispatches `thread.create` when the deterministic thread does not exist, then dispatches `thread.turn.start`. Provider selection, tools, memory, permission mode, usage limits, delegation, checkpoints, and projections follow the normal Akeru path.
+
+After a channel-originated turn completes, provider runtime ingestion resolves the final owner reply and queues external delivery. `ChannelDeliveryStore` claims delivery before provider I/O. Bot binding recovery metadata stays bounded and does not replace the delivery store.
+
+## Delivery recovery
+
+The delivery store retains an unfinished claim when provider acceptance is unknown. Akeru does not retry that post automatically, including after reconnect. A fixed binding warning exposes the unresolved state without exposing provider error details. Confirmed message IDs in the binding are limited to 128; the delivery store remains authoritative after an ID leaves that list.
+
+The shipped Slack, Discord, and Telegram post wrappers recognize specific structured rejection errors. Only a rejection that proves no text was accepted releases a claim for retry. Slack SDK request retries are disabled so an earlier accepted attempt cannot be hidden by a later rejection.
+
+WhatsApp can fail after accepting an earlier text chunk, and its adapter does not retain enough structured error data to prove rejection. Photon has internal retries that Akeru cannot classify as unaccepted. These adapters keep all post errors ambiguous. This is not an exactly-once delivery guarantee.
+
+## Conversation policy
+
+Telegram, iMessage, and WhatsApp accept direct messages only. Slack and Discord accept direct messages and direct bot mentions in platform threads. After the first Slack or Discord mention, the adapter subscribes to that platform thread. Later replies continue the same Akeru thread.
+
+External senders do not become paired people or in-app group members. The assigned bot remains the only external reply owner. It can use normal Akeru delegation, but child bots and provider subagents do not post to the external channel.
+
+## Quiet status signals
+
+Slack and Discord request messages carry one status reaction: accepted (`eyes`), completed (`white_check_mark`), or failed/cancelled (`x`). `updateChannelStatus` serializes updates per transport, removes previous status reactions before setting the next one, and bounds per-transport tracked statuses. Provider runtime ingestion enqueues terminal updates from `turn.completed`, `turn.aborted`, `session.exited`, and error/stopped session states through a drainable worker. Disconnect, reconnect, and restore clear persisted reactions from channel-origin messages. Providers without reaction support emit no signal.
+
+## Capabilities
+
+The shared provider capability record states whether an adapter supports direct messages, mentions, threads, reactions, typing state, message edits, attachments, and interactive actions. Runtime and client behavior must follow this record instead of assuming every provider has the same features.
+
+## Lifecycle
+
+A channel supports save, assign, connect, reconnect, disconnect, unassign, and delete. Server startup restores connected transports. A failed restore produces a visible repair state and does not stop server startup.
+
+Slack uses Socket Mode. Discord and Photon use supervised Gateway listeners that renew after their finite listener period expires. An early listener exit marks the transport unhealthy. Shutdown waits for listener cleanup. Retired transport callbacks cannot start new work after disconnect or replacement.
+
+Startup restores Slack and Discord subscriptions from channel origins in full thread records. Slack subscriptions exist before Socket Mode starts. First-mention context includes at most ten earlier messages and 8,000 characters. The current mention remains intact.
+
+Replies must match the current binding's project. Reassigning a channel to another project prevents old-project replies from using the new assignment.
+
+## Security boundary
+
+The server requires the environment administrator scope, `access:write`, for every credential and assignment command. UI checks are presentation only. Secrets must not enter settings responses, orchestration events, logs, analytics, diagnostics, URLs, or client state.
+
+`channel.attach` accepts an optional project ID. The bot-only setup omits it, so the server selects an available project from the bot's most recently updated unarchived thread. If none exists, it selects the project with the most recent environment activity. Attachment fails when no live project exists. Direct `channel.connect` requests still require an explicit project ID.
+
+The resolved project is persisted on the binding. Inbound work uses that assignment instead of resolving a new default for each message. If the assigned project becomes unavailable, the channel blocks and reports a repair state.
diff --git a/docs/user/channels.md b/docs/user/channels.md
new file mode 100644
index 000000000..9038bb72a
--- /dev/null
+++ b/docs/user/channels.md
@@ -0,0 +1,98 @@
+# Bot channels
+
+A channel gives one named bot an external messaging line. Messages enter the bot's normal Akeru conversation. The bot uses its workspace, model, tools, memory, permission mode, usage limits, and delegation rules.
+
+Akeru does not create a separate messaging session. The Akeru conversation keeps the work history, and each external request starts a turn.
+
+## Manage connections
+
+Open **Settings > Bot channels** with an environment administrator connection.
+
+1. Select a service and open its setup form.
+2. Enter the credentials and a connection name.
+3. Select the bot that answers and click **Connect**.
+
+Select **Connect later** to save a connection without assigning a bot. You can assign it from the saved connection card.
+
+Akeru chooses the workspace when you connect the bot. It prefers the bot's most recently active conversation in an available workspace. If the bot has none, Akeru uses the workspace with the most recent activity. The environment needs at least one workspace.
+
+You can reconnect, disconnect, unassign, or delete a connection. Disconnect stops messages but keeps the bot and project assignment. Unassign removes that assignment so you can use the connection with another bot or delete it. A connection that fails during server restart shows a repair state instead of appearing connected.
+
+If reassignment changes the workspace, replies from the earlier workspace cannot use the new assignment.
+
+Credentials stay on the environment server. Web, desktop, and mobile receive safe connection and delivery state only. A standard remote client cannot change channel credentials or assignment.
+
+## Delivery state
+
+Akeru records confirmed replies and prevents normal retries from posting them again. If a provider confirms that it rejected a reply, you can retry that reply.
+
+A network failure can leave delivery unknown. Akeru keeps that attempt and does not post it again automatically. Settings and the bot's Channels panel show a warning. Check the external conversation before taking further action. Reconnecting does not prove whether the earlier reply arrived.
+
+Mobile shows channel health, the selected project, recent confirmed deliveries, and a warning when a channel needs attention. Recent delivery counts cover retained confirmations, not the channel's full history.
+
+## Status signals
+
+On Slack and Discord, the bot marks your request message with a reaction: an eyes reaction when it accepts the request, a check mark on success, and an X on failure or cancellation. Akeru removes stale reactions when a connection restores or closes. Telegram, iMessage, and WhatsApp do not support these reactions and receive no status signal. Detailed progress stays inside Akeru; the channel never receives a stream of tool output.
+
+## Conversation behavior
+
+| Provider | Supported conversations |
+| -------- | ------------------------------------------------------------------ |
+| Telegram | Direct messages |
+| iMessage | Direct messages |
+| WhatsApp | Direct messages |
+| Slack | Direct messages and direct mentions in Slack threads |
+| Discord | Direct messages and direct mentions in Discord servers and threads |
+
+A group message on Telegram, iMessage, or WhatsApp does not start Akeru work.
+
+For Slack and Discord, a direct mention starts a linked Akeru thread. Later replies in that platform thread continue the same Akeru thread without another mention. Akeru includes a small amount of recent platform-thread context with the first mention.
+
+## Delegation
+
+The connected bot remains the external conversation owner. It can send work to another Akeru bot or group. Delegated work follows the existing access, memory, usage, depth, concurrency, and approval limits.
+
+Delegated bots do not send separate external replies. The connected bot returns one combined answer through the original channel.
+
+## Telegram
+
+Create a bot with BotFather and copy its token. Enter the token in the Telegram connection form, select a bot, and click **Connect**. Send a direct message to the Telegram bot to test it.
+
+## iMessage
+
+Akeru uses Photon for iMessage. You can use Photon hosted credentials or a self-hosted Photon server. Enter the connection details, select a bot, and click **Connect**. Send a direct iMessage to the connected line.
+
+External iMessage group chats are not supported.
+
+## WhatsApp
+
+Akeru uses the WhatsApp Business Cloud API. The connection needs an access token, app secret, phone number ID, and verify token. Configure Meta to send webhook requests to `https://<server>/api/channels/whatsapp/<bot-id>/webhook`. Replace `<server>` with your environment server's public hostname. Replace `<bot-id>` with the identifier after `/bots/` in the bot's web address.
+
+WhatsApp must be able to reach the environment server over public HTTPS. If the environment has no public address, the WhatsApp connection cannot receive webhooks.
+
+## Slack
+
+Create a Slack app for one workspace.
+
+1. Enable Socket Mode.
+2. Create an app-level token with the Socket Mode connection scope.
+3. Install the app and copy the bot token.
+4. Subscribe the app to direct-message and mention events.
+5. Save the bot token and app-level token in Akeru.
+6. Select a bot and click **Connect**.
+
+Socket Mode uses an outbound connection from the environment server. It works when Akeru runs locally, over SSH, or through Tailscale without a public webhook URL.
+
+The Slack channel connection is separate from the Slack plugin. The connection receives messages for a bot. The plugin gives a bot Slack tools. They do not share credentials or connection state.
+
+## Discord
+
+Create a Discord application and bot. Enable Message Content Intent, then copy the application ID, public key, and bot token. Invite the bot with permission to view channels, send messages, read message history, create or use threads, and add reactions.
+
+Enter the credentials in Akeru, select a bot, and click **Connect**. Direct messages reach the bot. A direct mention in a server starts work in the linked Discord conversation.
+
+## Access warning
+
+Anyone who can reach a connected bot can ask it to use the selected project and its enabled tools. The bot's permission mode still controls sensitive work, but channel membership is part of the access boundary.
+
+Keep Slack bots out of channels that should not reach the workspace. Limit Discord server and channel access. Use a private phone or messaging identity for Telegram, iMessage, and WhatsApp when the selected project contains sensitive data.
diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json
index a950ba4ee..2f9ac76ae 100644
--- a/packages/client-runtime/package.json
+++ b/packages/client-runtime/package.json
@@ -47,6 +47,10 @@
"types": "./src/providerSkills.ts",
"default": "./src/providerSkills.ts"
},
+ "./channel-presentation": {
+ "types": "./src/channelPresentation.ts",
+ "default": "./src/channelPresentation.ts"
+ },
"./settings-deep-link": {
"types": "./src/settingsDeepLink.ts",
"default": "./src/settingsDeepLink.ts"
diff --git a/packages/client-runtime/src/channelPresentation.test.ts b/packages/client-runtime/src/channelPresentation.test.ts
new file mode 100644
index 000000000..ea8fa92e5
--- /dev/null
+++ b/packages/client-runtime/src/channelPresentation.test.ts
@@ -0,0 +1,110 @@
+import { describe, expect, it } from "@effect/vitest";
+
+import { BotId, MessageId, ProjectId, type ChannelBinding } from "@t3tools/contracts";
+import {
+ channelBindingPresentation,
+ channelHealthLabel,
+ channelOriginLabel,
+ channelProviderLabel,
+} from "./channelPresentation.ts";
+
+describe("channel presentation", () => {
+ const binding: ChannelBinding = {
+ botId: BotId.make("bot-1"),
+ provider: "slack",
+ status: "connected",
+ externalIdentity: null,
+ connectedAt: null,
+ sentMessageIds: [],
+ };
+
+ it("labels every health state without exposing raw errors", () => {
+ expect([
+ channelHealthLabel("connected"),
+ channelHealthLabel("disconnected"),
+ channelHealthLabel("needs-reconnect"),
+ channelHealthLabel("failed"),
+ channelHealthLabel("not-live"),
+ ]).toEqual([
+ "Connected",
+ "Disconnected",
+ "Reconnect required",
+ "Connection failed",
+ "Not live",
+ ]);
+ });
+
+ it("reports only confirmed deliveries and does not choose a default project", () => {
+ expect(channelBindingPresentation(binding, [])).toEqual({
+ provider: "Slack",
+ health: "Connected",
+ warning: null,
+ project: "No project selected",
+ delivery: "No confirmed deliveries",
+ });
+ const id = MessageId.make("message-1");
+ expect(channelBindingPresentation({ ...binding, sentMessageIds: [id, id] }, []).delivery).toBe(
+ "1 confirmed delivery",
+ );
+ expect(
+ channelBindingPresentation(
+ { ...binding, sentMessageIds: [id, MessageId.make("message-2")] },
+ [],
+ ).delivery,
+ ).toBe("2 confirmed deliveries");
+ });
+
+ it("shows a repair warning without exposing error details", () => {
+ const presentation = channelBindingPresentation(
+ { ...binding, lastError: "private-error-detail" },
+ [],
+ );
+ expect(presentation.warning).toBe("Channel needs attention");
+ expect(JSON.stringify(presentation)).not.toContain("private-error-detail");
+ });
+
+ it("resolves only the assigned project", () => {
+ const projectId = ProjectId.make("project-1");
+ expect(channelBindingPresentation({ ...binding, projectId }, []).project).toBe(
+ "Project unavailable",
+ );
+ expect(
+ channelBindingPresentation({ ...binding, projectId }, [{ id: projectId, title: "Workspace" }])
+ .project,
+ ).toBe("Workspace");
+ });
+
+ it("falls back to the sender ID and permits an absent sender", () => {
+ expect(
+ channelOriginLabel(
+ { provider: "discord", externalThreadId: "thread", externalSenderId: "sender" },
+ " ",
+ ),
+ ).toBe("Discord · sender");
+ expect(channelOriginLabel({ provider: "imessage", externalThreadId: "thread" })).toBe(
+ "iMessage",
+ );
+ });
+ it("labels every advertised provider", () => {
+ expect([
+ channelProviderLabel("telegram"),
+ channelProviderLabel("imessage"),
+ channelProviderLabel("whatsapp"),
+ channelProviderLabel("slack"),
+ channelProviderLabel("discord"),
+ ]).toEqual(["Telegram", "iMessage", "WhatsApp", "Slack", "Discord"]);
+ });
+
+ it("prefers the persisted sender display name", () => {
+ expect(
+ channelOriginLabel(
+ {
+ provider: "slack",
+ externalThreadId: "slack:C1:1",
+ externalSenderId: "U1",
+ },
+ "Alice",
+ ),
+ ).toBe("Slack · Alice");
+ });
+});
diff --git a/packages/client-runtime/src/channelPresentation.ts b/packages/client-runtime/src/channelPresentation.ts
new file mode 100644
index 000000000..6e56b2a73
--- /dev/null
+++ b/packages/client-runtime/src/channelPresentation.ts
@@ -0,0 +1,59 @@
+import type {
+ ChannelBinding,
+ ChannelBindingStatus,
+ ChannelMessageOrigin,
+ ChannelProvider,
+ ProjectId,
+} from "@t3tools/contracts";
+
+export function channelProviderLabel(provider: ChannelProvider): string {
+ if (provider === "imessage") return "iMessage";
+ if (provider === "whatsapp") return "WhatsApp";
+ if (provider === "telegram") return "Telegram";
+ if (provider === "slack") return "Slack";
+ return "Discord";
+}
+
+export function channelHealthLabel(status: ChannelBindingStatus): string {
+ switch (status) {
+ case "connected":
+ return "Connected";
+ case "disconnected":
+ return "Disconnected";
+ case "needs-reconnect":
+ return "Reconnect required";
+ case "failed":
+ return "Connection failed";
+ case "not-live":
+ return "Not live";
+ }
+}
+
+export function channelBindingPresentation(
+ binding: ChannelBinding,
+ projects: ReadonlyArray<{ readonly id: ProjectId; readonly title: string }>,
+) {
+ const deliveredCount = new Set(binding.sentMessageIds).size;
+ return {
+ provider: channelProviderLabel(binding.provider),
+ health: channelHealthLabel(binding.status),
+ warning: binding.lastError ? "Channel needs attention" : null,
+ project: binding.projectId
+ ? (projects.find((project) => project.id === binding.projectId)?.title ??
+ "Project unavailable")
+ : "No project selected",
+ delivery:
+ deliveredCount === 0
+ ? "No confirmed deliveries"
+ : `${deliveredCount} confirmed ${deliveredCount === 1 ? "delivery" : "deliveries"}`,
+ };
+}
+
+export function channelOriginLabel(
+ origin: ChannelMessageOrigin,
+ senderDisplayName?: string | null,
+): string {
+ const sender = senderDisplayName?.trim() || origin.externalSenderId;
+ const provider = channelProviderLabel(origin.provider);
+ return sender ? `${provider} · ${sender}` : provider;
+}
diff --git a/packages/client-runtime/src/operations/commands.test.ts b/packages/client-runtime/src/operations/commands.test.ts
index bb96621b1..3bfe4d44a 100644
--- a/packages/client-runtime/src/operations/commands.test.ts
+++ b/packages/client-runtime/src/operations/commands.test.ts
@@ -33,6 +33,7 @@ import {
connectChannel,
createMcpServer,
createProject,
+ detachChannel,
disconnectChannel,
reconnectChannel,
sendChannelMessage,
@@ -201,9 +202,12 @@ describe("environment commands", () => {
const supervisor = yield* makeSupervisor(dispatched);
const botId = BotId.make("bot-1");
- yield* connectChannel({ botId, provider: "telegram", token: "token" }).pipe(
- Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
- );
+ yield* connectChannel({
+ botId,
+ targetProjectId: ProjectId.make("project-1"),
+ provider: "telegram",
+ token: "token",
+ }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
yield* reconnectChannel({ botId, provider: "telegram" }).pipe(
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
);
@@ -215,12 +219,16 @@ describe("environment commands", () => {
yield* disconnectChannel({ botId, provider: "telegram" }).pipe(
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
);
+ yield* detachChannel({ botId, provider: "telegram" }).pipe(
+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
+ );
expect(dispatched.map((command) => command.type)).toEqual([
"channel.connect",
"channel.reconnect",
"channel.send",
"channel.disconnect",
+ "channel.detach",
]);
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
);
diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts
index 2c8a34948..9d8650e52 100644
--- a/packages/client-runtime/src/operations/commands.ts
+++ b/packages/client-runtime/src/operations/commands.ts
@@ -40,6 +40,7 @@ export type SaveChannelConnectionInput = CommandInput<"channel.connection.save">
export type DeleteChannelConnectionInput = CommandInput<"channel.connection.delete">;
export type AttachChannelInput = CommandInput<"channel.attach">;
export type DisconnectChannelInput = CommandInput<"channel.disconnect">;
+export type DetachChannelInput = CommandInput<"channel.detach">;
export type ReconnectChannelInput = CommandInput<"channel.reconnect">;
export type SendChannelMessageInput = CommandInput<"channel.send">;
export type CreateGroupInput = CommandInput<"group.create">;
@@ -395,6 +396,16 @@ export const disconnectChannel: (input: DisconnectChannelInput) => CommandEffect
});
});
+export const detachChannel: (input: DetachChannelInput) => CommandEffect = Effect.fn(
+ "EnvironmentCommands.detachChannel",
+)(function* (input) {
+ return yield* dispatch({
+ ...input,
+ type: "channel.detach",
+ commandId: yield* commandId(input),
+ });
+});
+
export const reconnectChannel: (input: ReconnectChannelInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.reconnectChannel",
)(function* (input) {
diff --git a/packages/client-runtime/src/state/bots.ts b/packages/client-runtime/src/state/bots.ts
index bd7d139f3..3dfd03b38 100644
--- a/packages/client-runtime/src/state/bots.ts
+++ b/packages/client-runtime/src/state/bots.ts
@@ -12,6 +12,7 @@ import {
type DeleteChannelConnectionInput,
type AttachChannelInput,
type DisconnectChannelInput,
+ type DetachChannelInput,
type ReconnectChannelInput,
type SendChannelMessageInput,
type CreateGroupInput,
@@ -32,6 +33,7 @@ import {
deleteChannelConnection,
attachChannel,
disconnectChannel,
+ detachChannel,
reconnectChannel,
sendChannelMessage,
createGroup,
@@ -56,6 +58,7 @@ export type {
DeleteChannelConnectionInput,
AttachChannelInput,
DisconnectChannelInput,
+ DetachChannelInput,
ReconnectChannelInput,
SendChannelMessageInput,
CreateGroupInput,
@@ -138,6 +141,12 @@ export function createBotEnvironmentAtoms<R, E>(
scheduler,
concurrency: botConcurrency,
}),
+ detach: createEnvironmentCommand(runtime, {
+ label: "environment-data:commands:channel:detach",
+ execute: (input: DetachChannelInput) => detachChannel(input),
+ scheduler,
+ concurrency: botConcurrency,
+ }),
reconnect: createEnvironmentCommand(runtime, {
label: "environment-data:commands:channel:reconnect",
execute: (input: ReconnectChannelInput) => reconnectChannel(input),
diff --git a/packages/contracts/src/orchestration.test.ts b/packages/contracts/src/orchestration.test.ts
index e760831e0..5df3be9cc 100644
--- a/packages/contracts/src/orchestration.test.ts
+++ b/packages/contracts/src/orchestration.test.ts
@@ -2,10 +2,11 @@ import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
-import { ChannelConnectionId, MessageId } from "./baseSchemas.ts";
+import { ChannelConnectionId, MessageId, ProjectId } from "./baseSchemas.ts";
import {
BotAvatar,
BotEngine,
+ CHANNEL_TRANSPORT_CAPABILITIES,
DEFAULT_LOCAL_EXECUTION_MODE,
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
@@ -119,12 +120,47 @@ it.effect("decodes bot engine options while keeping old engines valid", () =>
}),
);
+it("defines the frozen conversation policy for every channel provider", () => {
+ assert.deepEqual(
+ Object.fromEntries(
+ Object.entries(CHANNEL_TRANSPORT_CAPABILITIES).map(([provider, capabilities]) => [
+ provider,
+ {
+ directMessages: capabilities.directMessages,
+ mentions: capabilities.mentions,
+ threads: capabilities.threads,
+ },
+ ]),
+ ),
+ {
+ telegram: { directMessages: true, mentions: false, threads: false },
+ imessage: { directMessages: true, mentions: false, threads: false },
+ whatsapp: { directMessages: true, mentions: false, threads: false },
+ slack: { directMessages: true, mentions: true, threads: true },
+ discord: { directMessages: true, mentions: true, threads: true },
+ },
+ );
+});
+
+it("advertises only channel actions exposed by the shipped transports", () => {
+ for (const capabilities of Object.values(CHANNEL_TRANSPORT_CAPABILITIES)) {
+ assert.equal(capabilities.typing, false);
+ assert.equal(capabilities.messageEdits, false);
+ assert.equal(capabilities.attachments, false);
+ assert.equal(capabilities.interactiveActions, false);
+ }
+ assert.equal(CHANNEL_TRANSPORT_CAPABILITIES.telegram.reactions, false);
+ assert.equal(CHANNEL_TRANSPORT_CAPABILITIES.slack.reactions, true);
+ assert.equal(CHANNEL_TRANSPORT_CAPABILITIES.discord.reactions, true);
+});
+
it.effect("decodes live channel commands", () =>
Effect.gen(function* () {
const telegram = yield* decodeClientOrchestrationCommand({
type: "channel.connect",
commandId: "connect-telegram",
botId: "bot-1",
+ targetProjectId: "project-1",
provider: "telegram",
token: " token ",
});
@@ -132,6 +168,7 @@ it.effect("decodes live channel commands", () =>
type: "channel.connect",
commandId: "connect-imessage",
botId: "bot-1",
+ targetProjectId: "project-1",
provider: "imessage",
mode: "hosted",
projectId: " photon-project ",
@@ -141,12 +178,32 @@ it.effect("decodes live channel commands", () =>
type: "channel.connect",
commandId: "connect-whatsapp",
botId: "bot-1",
+ targetProjectId: "project-1",
provider: "whatsapp",
accessToken: " access-token ",
appSecret: " app-secret ",
phoneNumberId: " phone-number-id ",
verifyToken: " verify-token ",
});
+ const slack = yield* decodeClientOrchestrationCommand({
+ type: "channel.connect",
+ commandId: "connect-slack",
+ botId: "bot-1",
+ targetProjectId: "project-1",
+ provider: "slack",
+ botToken: " xoxb-token ",
+ appToken: " xapp-token ",
+ });
+ const discord = yield* decodeClientOrchestrationCommand({
+ type: "channel.connect",
+ commandId: "connect-discord",
+ botId: "bot-1",
+ targetProjectId: "project-1",
+ provider: "discord",
+ botToken: " discord-token ",
+ applicationId: " app-1 ",
+ publicKey: " public-key ",
+ });
const saveConnection = yield* decodeClientOrchestrationCommand({
type: "channel.connection.save",
commandId: "save-photon",
@@ -172,6 +229,19 @@ it.effect("decodes live channel commands", () =>
phoneNumberId: "phone-number-id",
verifyToken: "verify-token",
});
+ assert.deepInclude(slack, {
+ targetProjectId: ProjectId.make("project-1"),
+ provider: "slack",
+ botToken: "xoxb-token",
+ appToken: "xapp-token",
+ });
+ assert.deepInclude(discord, {
+ targetProjectId: ProjectId.make("project-1"),
+ provider: "discord",
+ botToken: "discord-token",
+ applicationId: "app-1",
+ publicKey: "public-key",
+ });
assert.deepInclude(saveConnection, {
connectionId: ChannelConnectionId.make("photon-work"),
name: "Work iPhone",
@@ -197,6 +267,7 @@ it.effect("decodes WhatsApp message origins", () =>
channelOrigin: {
provider: "whatsapp",
externalThreadId: "whatsapp:phone:user",
+ externalMessageId: "wamid.1",
externalSenderId: "user",
},
},
@@ -210,6 +281,7 @@ it.effect("decodes WhatsApp message origins", () =>
assert.deepEqual(command.message.channelOrigin, {
provider: "whatsapp",
externalThreadId: "whatsapp:phone:user",
+ externalMessageId: "wamid.1",
externalSenderId: "user",
});
}),
@@ -222,6 +294,7 @@ it.effect("requires credentials for the selected iMessage mode", () =>
type: "channel.connect",
commandId: "connect-imessage-hosted",
botId: "bot-1",
+ targetProjectId: "project-1",
provider: "imessage",
mode: "hosted",
}),
@@ -231,6 +304,7 @@ it.effect("requires credentials for the selected iMessage mode", () =>
type: "channel.connect",
commandId: "connect-imessage-self-hosted",
botId: "bot-1",
+ targetProjectId: "project-1",
provider: "imessage",
mode: "self-hosted",
}),
diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts
index ce9f5b1e6..b9d575038 100644
--- a/packages/contracts/src/orchestration.ts
+++ b/packages/contracts/src/orchestration.ts
@@ -395,22 +395,93 @@ export const BotUsageCap = Schema.Struct({
});
export type BotUsageCap = typeof BotUsageCap.Type;
-export const ChannelProvider = Schema.Literals(["telegram", "imessage", "whatsapp"]);
+export const CHANNEL_PROVIDERS = ["telegram", "imessage", "whatsapp", "slack", "discord"] as const;
+export const ChannelProvider = Schema.Literals(CHANNEL_PROVIDERS);
export type ChannelProvider = typeof ChannelProvider.Type;
+
+export const ChannelTransportCapabilities = Schema.Struct({
+ directMessages: Schema.Boolean,
+ mentions: Schema.Boolean,
+ threads: Schema.Boolean,
+ reactions: Schema.Boolean,
+ typing: Schema.Boolean,
+ messageEdits: Schema.Boolean,
+ attachments: Schema.Boolean,
+ interactiveActions: Schema.Boolean,
+});
+export type ChannelTransportCapabilities = typeof ChannelTransportCapabilities.Type;
+
+export const CHANNEL_TRANSPORT_CAPABILITIES = {
+ telegram: {
+ directMessages: true,
+ mentions: false,
+ threads: false,
+ reactions: false,
+ typing: false,
+ messageEdits: false,
+ attachments: false,
+ interactiveActions: false,
+ },
+ imessage: {
+ directMessages: true,
+ mentions: false,
+ threads: false,
+ reactions: false,
+ typing: false,
+ messageEdits: false,
+ attachments: false,
+ interactiveActions: false,
+ },
+ whatsapp: {
+ directMessages: true,
+ mentions: false,
+ threads: false,
+ reactions: false,
+ typing: false,
+ messageEdits: false,
+ attachments: false,
+ interactiveActions: false,
+ },
+ slack: {
+ directMessages: true,
+ mentions: true,
+ threads: true,
+ reactions: true,
+ typing: false,
+ messageEdits: false,
+ attachments: false,
+ interactiveActions: false,
+ },
+ discord: {
+ directMessages: true,
+ mentions: true,
+ threads: true,
+ reactions: true,
+ typing: false,
+ messageEdits: false,
+ attachments: false,
+ interactiveActions: false,
+ },
+} as const satisfies Record<ChannelProvider, ChannelTransportCapabilities>;
+
export const ChannelBindingStatus = Schema.Literals([
"disconnected",
"connected",
"needs-reconnect",
+ "failed",
"not-live",
]);
export type ChannelBindingStatus = typeof ChannelBindingStatus.Type;
export const ChannelBinding = Schema.Struct({
botId: BotId,
connectionId: Schema.optional(ChannelConnectionId),
+ projectId: Schema.optional(ProjectId),
provider: ChannelProvider,
status: ChannelBindingStatus,
externalIdentity: Schema.NullOr(TrimmedNonEmptyString),
connectedAt: Schema.NullOr(IsoDateTime),
+ lastAttemptAt: Schema.optional(IsoDateTime),
+ lastError: Schema.optional(TrimmedNonEmptyString),
sentMessageIds: Schema.Array(MessageId).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
});
export type ChannelBinding = typeof ChannelBinding.Type;
@@ -486,6 +557,7 @@ export type OrchestrationGroup = typeof OrchestrationGroup.Type;
export const ChannelMessageOrigin = Schema.Struct({
provider: ChannelProvider,
externalThreadId: TrimmedNonEmptyString,
+ externalMessageId: Schema.optional(TrimmedNonEmptyString),
externalSenderId: Schema.optional(TrimmedNonEmptyString),
});
export type ChannelMessageOrigin = typeof ChannelMessageOrigin.Type;
@@ -1089,6 +1161,7 @@ const ChannelConnectCommand = Schema.Union([
type: Schema.Literal("channel.connect"),
commandId: CommandId,
botId: BotId,
+ targetProjectId: ProjectId,
provider: Schema.Literal("telegram"),
token: TrimmedNonEmptyString,
}),
@@ -1096,6 +1169,7 @@ const ChannelConnectCommand = Schema.Union([
type: Schema.Literal("channel.connect"),
commandId: CommandId,
botId: BotId,
+ targetProjectId: ProjectId,
provider: Schema.Literal("imessage"),
mode: Schema.Literal("hosted"),
projectId: TrimmedNonEmptyString,
@@ -1105,6 +1179,7 @@ const ChannelConnectCommand = Schema.Union([
type: Schema.Literal("channel.connect"),
commandId: CommandId,
botId: BotId,
+ targetProjectId: ProjectId,
provider: Schema.Literal("imessage"),
mode: Schema.Literal("self-hosted"),
serverUrl: TrimmedNonEmptyString,
@@ -1115,12 +1190,32 @@ const ChannelConnectCommand = Schema.Union([
type: Schema.Literal("channel.connect"),
commandId: CommandId,
botId: BotId,
+ targetProjectId: ProjectId,
provider: Schema.Literal("whatsapp"),
accessToken: TrimmedNonEmptyString,
appSecret: TrimmedNonEmptyString,
phoneNumberId: TrimmedNonEmptyString,
verifyToken: TrimmedNonEmptyString,
}),
+ Schema.Struct({
+ type: Schema.Literal("channel.connect"),
+ commandId: CommandId,
+ botId: BotId,
+ targetProjectId: ProjectId,
+ provider: Schema.Literal("slack"),
+ botToken: TrimmedNonEmptyString,
+ appToken: TrimmedNonEmptyString,
+ }),
+ Schema.Struct({
+ type: Schema.Literal("channel.connect"),
+ commandId: CommandId,
+ botId: BotId,
+ targetProjectId: ProjectId,
+ provider: Schema.Literal("discord"),
+ botToken: TrimmedNonEmptyString,
+ applicationId: TrimmedNonEmptyString,
+ publicKey: TrimmedNonEmptyString,
+ }),
]);
const ChannelConnectionSaveCommand = Schema.Union([
@@ -1164,6 +1259,25 @@ const ChannelConnectionSaveCommand = Schema.Union([
phoneNumberId: TrimmedNonEmptyString,
verifyToken: TrimmedNonEmptyString,
}),
+ Schema.Struct({
+ type: Schema.Literal("channel.connection.save"),
+ commandId: CommandId,
+ connectionId: ChannelConnectionId,
+ name: TrimmedNonEmptyString,
+ provider: Schema.Literal("slack"),
+ botToken: TrimmedNonEmptyString,
+ appToken: TrimmedNonEmptyString,
+ }),
+ Schema.Struct({
+ type: Schema.Literal("channel.connection.save"),
+ commandId: CommandId,
+ connectionId: ChannelConnectionId,
+ name: TrimmedNonEmptyString,
+ provider: Schema.Literal("discord"),
+ botToken: TrimmedNonEmptyString,
+ applicationId: TrimmedNonEmptyString,
+ publicKey: TrimmedNonEmptyString,
+ }),
]);
const ChannelConnectionDeleteCommand = Schema.Struct({
@@ -1177,6 +1291,8 @@ const ChannelAttachCommand = Schema.Struct({
commandId: CommandId,
botId: BotId,
connectionId: ChannelConnectionId,
+ // Absent means the server uses the bot's default project, matching in-app chat.
+ projectId: Schema.optional(ProjectId),
provider: ChannelProvider,
});
@@ -1187,6 +1303,13 @@ const ChannelDisconnectCommand = Schema.Struct({
provider: ChannelProvider,
});
+const ChannelDetachCommand = Schema.Struct({
+ type: Schema.Literal("channel.detach"),
+ commandId: CommandId,
+ botId: BotId,
+ provider: ChannelProvider,
+});
+
const ChannelReconnectCommand = Schema.Struct({
type: Schema.Literal("channel.reconnect"),
commandId: CommandId,
@@ -1697,6 +1820,7 @@ export const ClientOrchestrationCommand = Schema.Union([
ChannelConnectionDeleteCommand,
ChannelAttachCommand,
ChannelDisconnectCommand,
+ ChannelDetachCommand,
ChannelReconnectCommand,
ChannelSendCommand,
GroupCreateCommand,
diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts
index 41db855ce..9f77353ec 100644
--- a/packages/contracts/src/settings.ts
+++ b/packages/contracts/src/settings.ts
@@ -671,7 +671,7 @@ export type BackgroundActivitySettings = typeof BackgroundActivitySettings.Type;
export const ChannelConnectionProfile = Schema.Struct({
id: ChannelConnectionId,
provider: ChannelProvider,
- adapter: Schema.Literals(["telegram", "photon", "whatsapp"]),
+ adapter: Schema.Literals(["telegram", "photon", "whatsapp", "slack", "discord"]),
name: TrimmedNonEmptyString,
externalIdentity: Schema.optional(TrimmedNonEmptyString),
managementUrl: Schema.optional(TrimmedNonEmptyString),
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index b57938820..4994de832 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -466,6 +466,12 @@ importers:
'@anthropic-ai/claude-agent-sdk':
specifier: ^0.3.170
version: 0.3.170(@anthropic-ai/[email protected]([email protected]))(@modelcontextprotocol/[email protected]([email protected]))([email protected])
+ '@chat-adapter/discord':
+ specifier: 4.39.0
+ '@chat-adapter/slack':
+ specifier: 4.39.0
'@chat-adapter/state-memory':
specifier: 4.39.0
@@ -2162,10 +2168,18 @@ packages:
resolution: {integrity: sha512-CuNiSqg7+e1cO/GjffyMOm5Tt2jUF9CWHHnvQ/UkqvtkGfHdgwEC0wpmq7fkN3gxwpRnrAN0WzO3vREKmNolMQ==}
engines: {node: '>=18'}
+ '@chat-adapter/[email protected]':
+ resolution: {integrity: sha512-9IS4HF0Jw+Ucsm3f7XaXGCGb22Swb/r6FGaHoSDYxOEraQ88pFH5S7xc8//C+pCnqhX7p8QwLB/dYaNxDnl9pw==}
+ engines: {node: '>=20'}
+
'@chat-adapter/[email protected]':
resolution: {integrity: sha512-zc5mB5rYqbp4ts+Z3tG/YwkCypPYphriYpG95ZMRNGiEYx3cYZJZFmAFFM4YLfdz3VIQ99Fd0HFDYVNyAMV7cg==}
engines: {node: '>=20'}
+ '@chat-adapter/[email protected]':
+ resolution: {integrity: sha512-nDBYFEmD9MUobUH+HJbOYwKYcaeoCFJDXVvd41flh5sslpixSUG2SFcz7F3py62jJ9c0YYNEdwprIExO20IyZQ==}
+ engines: {node: '>=20'}
+
'@chat-adapter/[email protected]':
resolution: {integrity: sha512-sTslMdRA9MG2MYUF9anD+eatZ1o3Nu64TkQCJ9GrGWfRCefM8DnIG/Op+Ej9XS6XjqOORb3eDJvy6IpvWrfT4A==}
engines: {node: '>=20'}
@@ -2286,6 +2300,34 @@ packages:
'@daytona/[email protected]':
resolution: {integrity: sha512-3YlwbVN81KpF6CFTjno2jO45EzNQ97FF2hh+DeYzu9O9vSWRFrO16ae1XiJ5eMzFlkMvF+R4zwqnqtBenIg3HA==}
+ '@discordjs/[email protected]':
+ resolution: {integrity: sha512-gSKkhXLqs96TCzk66VZuHHl8z2bQMJFGwrXC0f33ngK+FLNau4hU1PYny3DNJfNdSH+gVMzE85/d5FQ2BpcNwQ==}
+ engines: {node: '>=16.11.0'}
+
+ '@discordjs/[email protected]':
+ resolution: {integrity: sha512-SVb428OMd3WO1paV3rm6tSjM4wC+Kecaa1EUGX7vc6/fddvw/6lg90z4QtCqm21zvVe92vMMDt9+DkIvjXImQQ==}
+ engines: {node: '>=16.11.0'}
+
+ '@discordjs/[email protected]':
+ resolution: {integrity: sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg==}
+ engines: {node: '>=18'}
+
+ '@discordjs/[email protected]':
+ resolution: {integrity: sha512-y4UPwWhH6vChKRkGdMB4odasUbHOUwy7KL+OVwF86PvT6QVOwElx+TiI1/6kcmcEe+g5YRXJFiXSXUdabqZOvQ==}
+ engines: {node: '>=16.11.0'}
+
+ '@discordjs/[email protected]':
+ resolution: {integrity: sha512-wvOylxNYJkwKjctS/Mn5GP1w9r3/rzyH+ThD1JlAca6zEdlHs8QWBBUQJpU5Q+W6DoIj/Ljh1IPlZs7hTU+UAg==}
+ engines: {node: '>=18'}
+
+ '@discordjs/[email protected]':
+ resolution: {integrity: sha512-3LKP7F2+atl9vJFhaBjn4nOaSWahZ/yWjOvA4e5pnXkt2qyXRCHLxoBQy81GFtLGCq7K9lPm9R517M1U+/90Qg==}
+ engines: {node: '>=18'}
+
+ '@discordjs/[email protected]':
+ resolution: {integrity: sha512-wPlQDxEmlDg5IxhJPuxXr3Vy9AjYq5xCvFWGJyD7w7Np8ZGu+Mc+97LCoEc/+AYCo2IDpKioiH0/c/mj5ZR9Uw==}
+ engines: {node: '>=16.11.0'}
+
'@distilled.cloud/[email protected]':
resolution: {integrity: sha512-Uw2yZf7PJ2ienrKG49HN1ajnke65mTtHBUrSb/3ykeZ/8cLaSgwVhPscHxSzGByY0TEtYcYKNNmfUVISgGQl9g==}
peerDependencies:
@@ -5502,6 +5544,18 @@ packages:
cpu: [x64]
os: [win32]
+ '@sapphire/[email protected]':
+ resolution: {integrity: sha512-cvGzxbba6sav2zZkH8GPf2oGk9yYoD5qrNWdu9fRehifgnFZJMV+nuy2nON2roRO4yQQ+v7MK/Pktl/HgfsUXg==}
+ engines: {node: '>=v14.0.0', npm: '>=7.0.0'}
+
+ '@sapphire/[email protected]':
+ resolution: {integrity: sha512-d9dUmWVA7MMiKobL3VpLF8P2aeanRTu6ypG2OIaEv/ZHH/SUQ2iHOVyi5wAPjQ+HmnMuL0whK9ez8I/raWbtIg==}
+ engines: {node: '>=v16'}
+
+ '@sapphire/[email protected]':
+ resolution: {integrity: sha512-xzvBr1Q1c4lCe7i6sRnrofxeO1QTP/LKQ6A6qy0iB4x5yfiSfARMEQEghojzTNALDTcv8En04qYNIco9/K9eZQ==}
+ engines: {node: '>=v14.0.0', npm: '>=7.0.0'}
+
'@sec-ant/[email protected]':
resolution: {integrity: sha512-831qok9r2t8AlxLko40y2ebgSDhenenCatLVeW/uBtnHPyhHOvG0C7TvfgecV+wHzIm5KUICgzmVpWS+IMEAeg==}
@@ -5570,6 +5624,22 @@ packages:
resolution: {integrity: sha512-doH1gimEu3A46VX6aVxpHTeHrytJAG6HgdxntYnCFiIFHEM/ZGpG8KiZGBChchjQmG0XFIBL552kBTjVcMZXwQ==}
engines: {node: '>=12'}
+ '@slack/[email protected]':
+ resolution: {integrity: sha512-6cmdPrV/RYfd2U0mDGiMK8S7OJqpCTm7enMLRR3edccsPX8j7zXTLnaEF4fhxxJJTAIOil6+qZrnUPTuaLvwrQ==}
+ engines: {node: '>= 18', npm: '>= 8.6.0'}
+
+ '@slack/[email protected]':
+ resolution: {integrity: sha512-qYy07je71WnEHgRwmw12DlAnZLi5HXmdlI2WUzUK2LH/rYXQpP6uEg462S5CwfE8FoCKUdIigHtYnOOfzZH1lQ==}
+ engines: {node: '>= 18', npm: '>= 8.6.0'}
+
+ '@slack/[email protected]':
+ resolution: {integrity: sha512-sZ9lIgJhPX2qft/tKWiklFlc0o1FWeI7QtciZJfW1+ErH1eGGHvOZ8e73sleTCFEFJp1q/R0WeS8Oa7AsiDprg==}
+ engines: {node: '>= 12.13.0', npm: '>= 6.12.0'}
+
+ '@slack/[email protected]':
+ resolution: {integrity: sha512-ItjyjEZml+LDH8CjcCLRLJHh7VZtevPKExrRN3l5KWyBliyDnGAeoO4Y+K+fFBmRpKLYVPgqWMX4THldv2HVtA==}
+ engines: {node: '>= 18', npm: '>= 8.6.0'}
+
'@smithy/[email protected]':
resolution: {integrity: sha512-wBXDRup6UU97VKyaiRo8AssnfStPtG0oAAfpq/bC0a1YYau8pM86YB4kM6ccoVi1mS8l/UHbn9oDM+7uozr/ug==}
engines: {node: '>=18.0.0'}
@@ -6402,6 +6472,10 @@ packages:
'@vitest/[email protected]':
resolution: {integrity: sha512-A51o8ymO5PpqlWNnBP9ZHPXDIpuMtTLlGSjN7la4US+LJzoUMyhwjA5QXlm39JexgwHKW4Xjs8Z2d3dLCXOeuA==}
+ '@vladfrangu/[email protected]':
+ resolution: {integrity: sha512-Xfe6rpCTxSxfbswi/W/Pz7zp1WWSNn4A0eW4mLkQUewCrXXtMj31lCg+iQyTkh/CkusZSq9eDflu7tjEDXUY6g==}
+ engines: {node: '>=v14.0.0', npm: '>=7.0.0'}
+
'@voidzero-dev/[email protected]':
resolution: {integrity: sha512-yAbKexF3npOGjg1N5EtXxun+7vdM/0x6QE5jucO/dv0LFhCAIzSN3UvLVCeamJt/Bz3jt7DLqQHEgXXrjy8drA==}
engines: {node: ^20.19.0 || ^22.18.0 || >=24.11.0}
@@ -7960,6 +8034,20 @@ packages:
resolution: {integrity: sha512-2xMCmOoMrdQIPHdsTawECdNPwlVFB9zGcz3kuhmBO6U3oU+UQjsue0i8ayLKpgBcm+hcXPMVSGUN9d+pvJ6+VQ==}
+ resolution: {integrity: sha512-7xpNK0EiWjjDFp2nAhHXezE4OUWm7s1zhc/UXXN6hnFFU8dfoPHgV0Hx0RPiCa3ILRpdeh152icc68DGCyXYIw==}
+
+ resolution: {integrity: sha512-ytuaRTzdnHUCXJ6KjL9MrItQX0xKncBKEeYI1Bst4+ud47eejH3cG6gaesYakjpPcUhh68XYS2YwGq3mmujFsA==}
+
+ resolution: {integrity: sha512-jjJx8iwAeJcj8oEauV43fue9lNqkf38fy60aSs2+G8D1nJmDxUIrk08o3h0F3wgwuBWWJUZO+X/VgfXsxpCiJA==}
+ engines: {node: '>=18.4.0'}
+
+ resolution: {integrity: sha512-qHbFlFG2N7y3LjPySYsL6A1+BnX6bkTVgo842EX0CqVPk/KTMwZkojPHEXKsQUpWZNyz5BISNHK1cPpQw0+m4A==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-nr5vQxEhM0REomp1qiHbc6V99yrfBZy+wUU56VXADfSOlLj8PdLqsHiRe7b+FbqKesiyv4ax+k1GVwGonYKuCg==}
@@ -8389,6 +8477,9 @@ packages:
resolution: {integrity: sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==}
engines: {node: '>=6'}
+ resolution: {integrity: sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==}
+
resolution: {integrity: sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==}
@@ -9434,6 +9525,9 @@ packages:
engines: {node: '>=20'}
hasBin: true
+ resolution: {integrity: sha512-FO/Rhvz5tuw4MCWkpMzHFKWD2LsfHzIb7i6MdPYZ/KW7AlxawyLkqdy+jPZP1WubqEADE3O4FUENlJHDfQASRg==}
+
resolution: {integrity: sha512-5BMULNob1vgFX6EjQw5izWDxrecWK9AM72rugNr0TFldMOi0fj6Jk+zeKIt0xGj4cEfQIJth4w3OKWOJ4f+AFw==}
engines: {node: '>=0.10.0'}
@@ -10086,6 +10180,9 @@ packages:
resolution: {integrity: sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==}
+ resolution: {integrity: sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==}
+
resolution: {integrity: sha512-wIkUCfVKpVsWo3JSZlc+8MB5it+2AN5W8J7YVMST30UrvcQNZ1Okbj+rbVniijTWE6FGYy4XJq/rHkas8qJMLQ==}
@@ -10161,6 +10258,9 @@ packages:
resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==}
hasBin: true
+ resolution: {integrity: sha512-x5sn4UX2k5gCWlcfmoFwG4TPie8+dctESyqOBdhB5p6MsgWXdBKGmt9nXPObj/JI50TTL928lc5Yt1WntMn1bw==}
+
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
@@ -10982,6 +11082,10 @@ packages:
resolution: {integrity: sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-LICb2p9CB7FS+0eR1oqWnHhp0FljGLZCWBE9aix0Uye9W8LTQPwMTYVGWQWIw9RdQiDg4+epXQODwIYJtSJaow==}
+ engines: {node: '>=4'}
+
resolution: {integrity: sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==}
engines: {node: '>=6'}
@@ -11002,6 +11106,10 @@ packages:
resolution: {integrity: sha512-I4Prw6ivkd6p8PiYR1tXASOAOBzIJwu0TB7fqaX0c/8c3QAehNYmX57EijyGGGBt3c/BIowGwV03RVBtXvHEVg==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-RwFpb72c/BhQLEXIZ5K2e+AhgNVmIejGlTgiB9MzZ0e93GRvqZ7uSi0dvRF7/XIXDeNkra2fNHBxTyPDGySpjQ==}
+ engines: {node: '>=8'}
+
resolution: {integrity: sha512-7NED7xhQ74Ngp4JP/2e0VZHp7vSWfJfqeiR92jPgxsz6m0Se4P03YoTKa9dDXyZ3r6P616gUXttrB6nnHYKang==}
engines: {node: '>=20'}
@@ -11014,6 +11122,10 @@ packages:
resolution: {integrity: sha512-J5ApzjyRkkf601HpEeykoiCvzHQjWxPAHhyjFcEUP2SWq0+35NKh8TLhpLw+Dkq5TZBFvUM6UigdE9hIVYTl5w==}
engines: {node: '>=20'}
+ resolution: {integrity: sha512-rhIwUycgwwKcP9yTOOFK/AKsAopjjCakVqLHePO3CC6Mir1Z99xT+R63jZxAT5lFZLa2inS5h+ZS2GvR99/FBg==}
+ engines: {node: '>=8'}
+
resolution: {integrity: sha512-AxTM2wDGORHGEkPCt8yqxOTMgpfbEHqF51f/5fJCmwFC3C/zNcGT63SymH2ttOAaiIws2zVg4+izQCjrakcwHg==}
engines: {node: '>=20'}
@@ -12644,6 +12756,9 @@ packages:
resolution: {integrity: sha512-tLJxacIQUM82IR7JO1UUkKlYuUTmoY9HBJAmNWFzheSlDS5SPMcNIepejHJa4BpPQLAcbRhRf3GDJzyj6rbKvA==}
+ resolution: {integrity: sha512-ufKpbmrugz5Aou4wcr5Wc1UUFWOLhq+Fm6qa6P0w0K5Qw2yhaUoiWszhCVuNQyNwrlGiscHOmqYoAox1PtvgjA==}
+
resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}
@@ -15022,6 +15137,21 @@ snapshots:
dependencies:
fontkitten: 1.0.3
+ dependencies:
+ '@chat-adapter/shared': 4.39.0([email protected]([email protected]))([email protected])
+ discord-api-types: 0.37.120
+ discord-interactions: 4.4.0
+ discord.js: 14.27.0([email protected])([email protected])
+ transitivePeerDependencies:
+ - ai
+ - bufferutil
+ - supports-color
+ - utf-8-validate
+ - workflow
+ - zod
+
dependencies:
@@ -15031,6 +15161,21 @@ snapshots:
- workflow
- zod
+ dependencies:
+ '@chat-adapter/shared': 4.39.0([email protected]([email protected]))([email protected])
+ '@slack/socket-mode': 2.0.7([email protected])([email protected])
+ '@slack/web-api': 7.19.0
+ transitivePeerDependencies:
+ - ai
+ - bufferutil
+ - debug
+ - supports-color
+ - utf-8-validate
+ - workflow
+ - zod
+
dependencies:
@@ -15212,6 +15357,55 @@ snapshots:
- debug
- supports-color
+ '@discordjs/[email protected]':
+ dependencies:
+ '@discordjs/formatters': 0.6.2
+ '@discordjs/util': 1.2.0
+ '@sapphire/shapeshift': 4.0.0
+ discord-api-types: 0.38.55
+ fast-deep-equal: 3.1.3
+ ts-mixer: 6.0.4
+ tslib: 2.8.1
+
+ '@discordjs/[email protected]': {}
+
+ '@discordjs/[email protected]': {}
+
+ '@discordjs/[email protected]':
+ dependencies:
+ discord-api-types: 0.38.55
+
+ '@discordjs/[email protected]':
+ dependencies:
+ '@discordjs/collection': 2.1.1
+ '@discordjs/util': 1.2.0
+ '@sapphire/async-queue': 1.5.5
+ '@sapphire/snowflake': 3.5.5
+ '@vladfrangu/async_event_emitter': 2.4.7
+ discord-api-types: 0.38.55
+ magic-bytes.js: 1.13.1
+ tslib: 2.8.1
+ undici: 6.28.0
+
+ '@discordjs/[email protected]':
+ dependencies:
+ discord-api-types: 0.38.55
+
+ dependencies:
+ '@discordjs/collection': 2.1.1
+ '@discordjs/rest': 2.6.3
+ '@discordjs/util': 1.2.0
+ '@sapphire/async-queue': 1.5.5
+ '@types/ws': 8.18.1
+ '@vladfrangu/async_event_emitter': 2.4.7
+ discord-api-types: 0.38.55
+ tslib: 2.8.1
+ transitivePeerDependencies:
+ - bufferutil
+ - utf-8-validate
+
'@distilled.cloud/[email protected]([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))':
dependencies:
'@aws-crypto/crc32': 5.2.0
@@ -18989,6 +19183,15 @@ snapshots:
'@rollup/[email protected]':
optional: true
+ '@sapphire/[email protected]': {}
+
+ '@sapphire/[email protected]':
+ dependencies:
+ fast-deep-equal: 3.1.3
+ lodash: 4.18.1
+
+ '@sapphire/[email protected]': {}
+
'@sec-ant/[email protected]': {}
'@shikijs/[email protected]':
@@ -19064,6 +19267,44 @@ snapshots:
dependencies:
escape-string-regexp: 5.0.0
+ '@slack/[email protected]':
+ dependencies:
+ '@types/node': 24.12.4
+
+ dependencies:
+ '@slack/logger': 4.0.1
+ '@slack/web-api': 7.19.0
+ '@types/node': 24.12.4
+ '@types/ws': 8.18.1
+ eventemitter3: 5.0.4
+ transitivePeerDependencies:
+ - bufferutil
+ - debug
+ - supports-color
+ - utf-8-validate
+
+ '@slack/[email protected]': {}
+
+ '@slack/[email protected]':
+ dependencies:
+ '@slack/logger': 4.0.1
+ '@slack/types': 2.22.0
+ '@types/node': 24.12.4
+ '@types/retry': 0.12.0
+ axios: 1.20.0
+ eventemitter3: 5.0.4
+ form-data: 4.0.6
+ is-electron: 2.2.2
+ is-stream: 2.0.1
+ p-queue: 6.6.2
+ p-retry: 4.6.2
+ retry: 0.13.1
+ transitivePeerDependencies:
+ - debug
+ - supports-color
+
'@smithy/[email protected]':
dependencies:
'@aws-crypto/crc32': 5.2.0
@@ -19981,6 +20222,8 @@ snapshots:
convert-source-map: 2.0.0
tinyrainbow: 3.1.0
+ '@vladfrangu/[email protected]': {}
+
dependencies:
'@oxc-project/runtime': 0.138.0
@@ -21740,6 +21983,31 @@ snapshots:
minimatch: 3.1.5
p-limit: 3.1.0
+
+
+
+ dependencies:
+ '@discordjs/builders': 1.14.1
+ '@discordjs/collection': 1.5.3
+ '@discordjs/formatters': 0.6.2
+ '@discordjs/rest': 2.6.3
+ '@discordjs/util': 1.2.0
+ '@discordjs/ws': 1.2.3([email protected])([email protected])
+ '@sapphire/snowflake': 3.5.5
+ discord-api-types: 0.38.55
+ fast-deep-equal: 3.1.3
+ lodash.snakecase: 4.1.1
+ magic-bytes.js: 1.13.1
+ tslib: 2.8.1
+ undici: 6.28.0
+ transitivePeerDependencies:
+ - bufferutil
+ - utf-8-validate
+
dependencies:
app-builder-lib: 26.15.6([email protected])([email protected])
@@ -22155,6 +22423,8 @@ snapshots:
+
@@ -23691,6 +23961,8 @@ snapshots:
+
@@ -24204,6 +24476,8 @@ snapshots:
+
@@ -24259,6 +24533,8 @@ snapshots:
+
dependencies:
'@jridgewell/sourcemap-codec': 1.5.5
@@ -25439,6 +25715,8 @@ snapshots:
+
dependencies:
p-try: 2.2.0
@@ -25457,6 +25735,11 @@ snapshots:
+ dependencies:
+ eventemitter3: 4.0.7
+ p-timeout: 3.2.0
+
dependencies:
eventemitter3: 5.0.4
@@ -25471,6 +25754,10 @@ snapshots:
dependencies:
is-network-error: 1.3.2
+ dependencies:
+ p-finally: 1.0.0
+
@@ -27596,6 +27883,8 @@ snapshots:
+