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): ship groups and external channels (#107)

Leo65da264432de
diff --git a/apps/server/package.json b/apps/server/package.json
index 8e2ddab96..ff06ccc9e 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -24,6 +24,8 @@
"dependencies": {
"@ai-sdk/anthropic": "3.0.113",
"@anthropic-ai/claude-agent-sdk": "^0.3.170",
+ "@chat-adapter/state-memory": "4.39.0",
+ "@chat-adapter/whatsapp": "4.39.0",
"@daytona/sdk": "^0.207.0",
"@effect/platform-bun": "catalog:",
"@effect/platform-node": "catalog:",
@@ -34,10 +36,13 @@
"@mastra/core": "1.63.0",
"@mastra/libsql": "1.22.0",
"@mastra/memory": "1.28.0",
+ "@mastra/telegram": "0.1.0",
"@opencode-ai/sdk": "^1.3.15",
+ "@photon-ai/chat-adapter-imessage": "3.2.0",
"@pierre/diffs": "catalog:",
"@upstash/box": "0.5.3",
"@vercel/sandbox": "^2.5.0",
+ "chat": "4.39.0",
"e2b": "^2.32.0",
"effect": "catalog:",
"msgpackr-extract": "3.0.4",
diff --git a/apps/server/src/auth/EnvironmentAuth.ts b/apps/server/src/auth/EnvironmentAuth.ts
index e27d7aaac..86efea2a7 100644
--- a/apps/server/src/auth/EnvironmentAuth.ts
+++ b/apps/server/src/auth/EnvironmentAuth.ts
@@ -36,6 +36,10 @@ import { layerConfig as SqlitePersistenceLayer } from "../persistence/Layers/Sql
export const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
export const INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT = "administrative-bootstrap";
+export function isEnvironmentHostSessionSubject(subject: string): boolean {
+ return subject === INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT;
+}
+
export interface IssuedPairingLink {
readonly id: string;
readonly credential: string;
diff --git a/apps/server/src/channels/ChannelCommand.ts b/apps/server/src/channels/ChannelCommand.ts
new file mode 100644
index 000000000..dd944e60a
--- /dev/null
+++ b/apps/server/src/channels/ChannelCommand.ts
@@ -0,0 +1,47 @@
+import type { ClientOrchestrationCommand } from "@t3tools/contracts";
+
+import {
+ connectChannel,
+ attachChannelConnection,
+ deleteChannelConnection,
+ disconnectChannel,
+ reconnectChannel,
+ saveChannelConnection,
+ sendChannelMessage,
+ type ChannelRuntimeDependencies,
+} from "./ChannelRuntime.ts";
+
+export type ChannelCommand = Extract<
+ ClientOrchestrationCommand,
+ { readonly type: `channel.${string}` }
+>;
+
+export function isChannelCommand(command: ClientOrchestrationCommand): command is ChannelCommand {
+ return command.type.startsWith("channel.");
+}
+
+export async function executeChannelCommand(
+ dependencies: ChannelRuntimeDependencies,
+ command: ChannelCommand,
+): Promise<{ readonly sequence: number }> {
+ const sequence =
+ command.type === "channel.connect"
+ ? await connectChannel(dependencies, command)
+ : command.type === "channel.connection.save"
+ ? await saveChannelConnection(dependencies, command)
+ : command.type === "channel.connection.delete"
+ ? await deleteChannelConnection(dependencies, command.connectionId)
+ : command.type === "channel.attach"
+ ? await attachChannelConnection(
+ dependencies,
+ command.botId,
+ command.connectionId,
+ 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);
+ return { sequence };
+}
diff --git a/apps/server/src/channels/ChannelDeliveryStore.test.ts b/apps/server/src/channels/ChannelDeliveryStore.test.ts
new file mode 100644
index 000000000..e1722505a
--- /dev/null
+++ b/apps/server/src/channels/ChannelDeliveryStore.test.ts
@@ -0,0 +1,68 @@
+import { assert, it } from "@effect/vitest";
+import { BotId, MessageId, ThreadId } from "@t3tools/contracts";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+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";
+
+const TestLayer = Layer.mergeAll(NodeSqliteClient.layerMemory());
+
+it.layer(TestLayer)("channel delivery store", (it) => {
+ it.effect("claims each assistant message once before transport", () =>
+ Effect.gen(function* () {
+ yield* runMigrations();
+ const store = yield* makeChannelDeliveryStore;
+ const sql = yield* SqlClient.SqlClient;
+ const claim = {
+ messageId: MessageId.make("message-1"),
+ botId: BotId.make("bot-1"),
+ threadId: ThreadId.make("thread-1"),
+ provider: "whatsapp" as const,
+ externalThreadId: "chat-1",
+ requestedAt: "2026-08-27T20:00:00.000Z",
+ };
+
+ const concurrentClaims = yield* Effect.all([store.claim(claim), store.claim(claim)], {
+ concurrency: "unbounded",
+ });
+ assert.deepEqual(concurrentClaims.toSorted(), ["claimed", "requested"]);
+ yield* store.markSent({
+ messageId: claim.messageId,
+ sentAt: "2026-08-27T20:00:01.000Z",
+ });
+ assert.equal(yield* store.claim(claim), "sent");
+
+ const rows = yield* sql<{ readonly status: string; readonly sentAt: string | null }>`
+ SELECT status, sent_at AS "sentAt"
+ FROM channel_deliveries
+ WHERE message_id = ${claim.messageId}
+ `;
+ assert.deepEqual(rows, [{ status: "sent", sentAt: "2026-08-27T20:00:01.000Z" }]);
+ }),
+ );
+
+ it.effect("releases only requested deliveries", () =>
+ Effect.gen(function* () {
+ yield* runMigrations();
+ const store = yield* makeChannelDeliveryStore;
+ const claim = {
+ messageId: MessageId.make("message-retry"),
+ 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");
+ 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");
+ }),
+ );
+});
diff --git a/apps/server/src/channels/ChannelDeliveryStore.ts b/apps/server/src/channels/ChannelDeliveryStore.ts
new file mode 100644
index 000000000..32c3ecec5
--- /dev/null
+++ b/apps/server/src/channels/ChannelDeliveryStore.ts
@@ -0,0 +1,97 @@
+import { BotId, ChannelProvider, IsoDateTime, MessageId, ThreadId } from "@t3tools/contracts";
+import * as Context from "effect/Context";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Schema from "effect/Schema";
+import * as SqlClient from "effect/unstable/sql/SqlClient";
+
+import { toPersistenceSqlError, type ProjectionRepositoryError } from "../persistence/Errors.ts";
+
+export const ChannelDeliveryClaim = Schema.Struct({
+ messageId: MessageId,
+ botId: BotId,
+ threadId: ThreadId,
+ provider: ChannelProvider,
+ externalThreadId: Schema.String,
+ requestedAt: IsoDateTime,
+});
+export type ChannelDeliveryClaim = typeof ChannelDeliveryClaim.Type;
+export type ChannelDeliveryClaimResult = "claimed" | "requested" | "sent";
+
+export interface ChannelDeliveryStoreShape {
+ readonly claim: (
+ input: ChannelDeliveryClaim,
+ ) => Effect.Effect<ChannelDeliveryClaimResult, ProjectionRepositoryError>;
+ readonly releaseRequested: (
+ messageId: MessageId,
+ ) => Effect.Effect<void, ProjectionRepositoryError>;
+ readonly markSent: (input: {
+ readonly messageId: MessageId;
+ readonly sentAt: string;
+ }) => Effect.Effect<void, ProjectionRepositoryError>;
+}
+
+export class ChannelDeliveryStore extends Context.Service<
+ ChannelDeliveryStore,
+ ChannelDeliveryStoreShape
+>()("akeru-bot/channels/ChannelDeliveryStore") {}
+
+export const makeChannelDeliveryStore = Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+
+ const claim: ChannelDeliveryStoreShape["claim"] = (input) =>
+ Effect.gen(function* () {
+ const inserted = yield* sql<{ readonly messageId: string }>`
+ INSERT OR IGNORE INTO channel_deliveries (
+ message_id, bot_id, thread_id, provider, external_thread_id, status, requested_at, sent_at
+ ) VALUES (
+ ${input.messageId}, ${input.botId}, ${input.threadId}, ${input.provider},
+ ${input.externalThreadId}, 'requested', ${input.requestedAt}, NULL
+ )
+ RETURNING message_id AS "messageId"
+ `;
+ if (inserted.length === 1) return "claimed" as const;
+ const rows = yield* sql<{ readonly status: "requested" | "sent" }>`
+ SELECT status FROM channel_deliveries WHERE message_id = ${input.messageId}
+ `;
+ return rows[0]?.status ?? "requested";
+ }).pipe(Effect.mapError(toPersistenceSqlError("ChannelDeliveryStore.claim")));
+
+ const releaseRequested: ChannelDeliveryStoreShape["releaseRequested"] = (messageId) =>
+ sql`
+ DELETE FROM channel_deliveries
+ WHERE message_id = ${messageId} AND status = 'requested'
+ `.pipe(
+ Effect.asVoid,
+ Effect.mapError(toPersistenceSqlError("ChannelDeliveryStore.releaseRequested")),
+ );
+
+ const markSent: ChannelDeliveryStoreShape["markSent"] = ({ messageId, sentAt }) =>
+ sql`
+ UPDATE channel_deliveries
+ SET status = 'sent', sent_at = COALESCE(sent_at, ${sentAt})
+ WHERE message_id = ${messageId}
+ `.pipe(Effect.asVoid, Effect.mapError(toPersistenceSqlError("ChannelDeliveryStore.markSent")));
+
+ return { claim, releaseRequested, markSent } satisfies ChannelDeliveryStoreShape;
+});
+
+export const ChannelDeliveryStoreLive = Layer.effect(
+ ChannelDeliveryStore,
+ makeChannelDeliveryStore,
+);
+
+export function makeMemoryChannelDeliveryStore(): ChannelDeliveryStoreShape {
+ const status = new Map<MessageId, "requested" | "sent">();
+ return {
+ claim: (input) =>
+ Effect.sync(() => {
+ const existing = status.get(input.messageId);
+ if (existing) return existing;
+ status.set(input.messageId, "requested");
+ return "claimed";
+ }),
+ releaseRequested: (messageId) => Effect.sync(() => void status.delete(messageId)),
+ markSent: ({ messageId }) => Effect.sync(() => void status.set(messageId, "sent")),
+ };
+}
diff --git a/apps/server/src/channels/ChannelRuntime.test.ts b/apps/server/src/channels/ChannelRuntime.test.ts
new file mode 100644
index 000000000..d95d2bac8
--- /dev/null
+++ b/apps/server/src/channels/ChannelRuntime.test.ts
@@ -0,0 +1,1388 @@
+import { createHmac } from "node:crypto";
+
+import {
+ BotId,
+ ChannelConnectionId,
+ CommandId,
+ DEFAULT_SERVER_SETTINGS,
+ EventId,
+ MessageId,
+ ProjectId,
+ ProviderInstanceId,
+ ThreadId,
+ TurnId,
+ type ChannelBinding,
+ type OrchestrationBot,
+ type OrchestrationCommand,
+ type OrchestrationMessage,
+ type OrchestrationReadModel,
+ 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 * as Effect from "effect/Effect";
+import * as Option from "effect/Option";
+import * as Stream from "effect/Stream";
+import { afterEach, describe, expect, it, vi } from "vite-plus/test";
+
+const photon = vi.hoisted(() => ({
+ adapter: null as iMessageAdapter | null,
+ chat: null as ChatInstance | null,
+ failedSubscription: null as string | null,
+ subscriptionAttempts: [] as string[],
+}));
+
+vi.mock("@photon-ai/chat-adapter-imessage", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@photon-ai/chat-adapter-imessage")>();
+ return {
+ ...actual,
+ createiMessageAdapter: (
+ options: Parameters<typeof actual.createiMessageAdapter>[0],
+ ): iMessageAdapter => {
+ const adapter = actual.createiMessageAdapter(options) as iMessageAdapter & Adapter;
+ adapter.initialize = async (chat) => {
+ photon.adapter = adapter;
+ photon.chat = chat;
+ };
+ adapter.startGatewayListener = async () => new Response(null, { status: 200 });
+ adapter.onThreadSubscribe = async (threadId) => {
+ photon.subscriptionAttempts.push(threadId);
+ if (threadId === photon.failedSubscription) throw new Error("invalid group GUID");
+ };
+ adapter.disconnect = async () => undefined;
+ 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,
+ channelBindingsForRuntime,
+ channelThreadId,
+ connectChannel,
+ deleteChannelConnection,
+ disconnectChannel,
+ dispatchInboundChannelMessage,
+ handleWhatsAppWebhook,
+ reconnectChannel,
+ saveChannelConnection,
+ restoreConnectedChannels,
+ sendCompletedChannelReply,
+ sendChannelMessage,
+ shutdownAllChannels,
+ stopArchivedBotChannels,
+ stopChannelsForBot,
+ type ChannelRuntimeDependencies,
+} from "./ChannelRuntime.ts";
+
+const NOW = "2026-08-27T20:00:00.000Z";
+const BOT_ID = BotId.make("bot-1");
+const PROJECT_ID = ProjectId.make("project-1");
+
+function makeBot(
+ id: BotId,
+ input: {
+ readonly name?: string;
+ readonly archivedAt?: string | null;
+ readonly channelBindings?: ReadonlyArray<ChannelBinding>;
+ } = {},
+): OrchestrationBot {
+ return {
+ id,
+ name: input.name ?? id,
+ title: "Agent",
+ label: null,
+ description: null,
+ disabledMcpServerIds: [],
+ avatar: { kind: "dither", seed: id },
+ engine: null,
+ sandbox: "local",
+ runtimeMode: "full-access",
+ usageCap: null,
+ voiceEnabled: false,
+ channelBindings: input.channelBindings ?? [],
+ groupId: null,
+ archivedAt: input.archivedAt ?? null,
+ createdAt: NOW,
+ updatedAt: NOW,
+ };
+}
+
+function makeModel(bots: ReadonlyArray<OrchestrationBot>): OrchestrationReadModel {
+ return {
+ ...createEmptyReadModel(NOW),
+ snapshotSequence: 12,
+ bots,
+ projects: [
+ {
+ id: PROJECT_ID,
+ title: "Project",
+ workspaceRoot: "/tmp/project",
+ defaultModelSelection: {
+ instanceId: ProviderInstanceId.make("codex"),
+ model: "gpt-5.6",
+ },
+ scripts: [],
+ createdAt: NOW,
+ updatedAt: NOW,
+ deletedAt: null,
+ },
+ ],
+ };
+}
+
+function makeMessage(
+ id: MessageId,
+ role: OrchestrationMessage["role"],
+ text: string,
+ channelOrigin?: OrchestrationMessage["channelOrigin"],
+): OrchestrationMessage {
+ return {
+ id,
+ role,
+ text,
+ turnId: null,
+ ...(channelOrigin !== undefined ? { channelOrigin } : {}),
+ streaming: false,
+ createdAt: NOW,
+ updatedAt: NOW,
+ };
+}
+
+function makeChatSdkMessage(threadId: string, id: string, text: string, senderId: string) {
+ return new ChatMessage({
+ id,
+ threadId,
+ text,
+ formatted: parseMarkdown(text),
+ raw: {},
+ author: {
+ userId: senderId,
+ userName: senderId,
+ fullName: senderId,
+ isBot: false,
+ isMe: false,
+ },
+ // @effect-diagnostics-next-line globalDate:off - Chat SDK Message requires a Date fixture.
+ metadata: { dateSent: new Date(NOW), edited: false },
+ attachments: [],
+ isMention: false,
+ });
+}
+
+function makeThread(
+ id: ThreadId,
+ botId: BotId,
+ messages: ReadonlyArray<OrchestrationMessage>,
+): OrchestrationThread {
+ return {
+ id,
+ projectId: PROJECT_ID,
+ botId,
+ groupId: null,
+ title: "Channel thread",
+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.6" },
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ latestTurn: null,
+ createdAt: NOW,
+ updatedAt: NOW,
+ archivedAt: null,
+ settledOverride: null,
+ settledAt: null,
+ deletedAt: null,
+ messages,
+ proposedPlans: [],
+ activities: [],
+ checkpoints: [],
+ session: null,
+ };
+}
+
+function makeMemorySecretStore() {
+ const values = new Map<string, Uint8Array>();
+ const store: ServerSecretStore["Service"] = {
+ get: (name) => Effect.succeed(Option.fromUndefinedOr(values.get(name))),
+ set: (name, value) => Effect.sync(() => void values.set(name, value)),
+ create: (name, value) => Effect.sync(() => void values.set(name, value)),
+ getOrCreateRandom: (name, bytes) =>
+ Effect.sync(() => {
+ const value = values.get(name) ?? new Uint8Array(bytes);
+ values.set(name, value);
+ return value;
+ }),
+ remove: (name) => Effect.sync(() => void values.delete(name)),
+ };
+ return { store, values };
+}
+
+function makeHarness(input: {
+ readonly bots?: ReadonlyArray<OrchestrationBot>;
+ readonly threads?: ReadonlyArray<OrchestrationThread>;
+ readonly post?: (externalThreadId: string, text: string) => Promise<void>;
+ readonly shutdown?: () => Promise<void>;
+ readonly deliveryStore?: ChannelRuntimeDependencies["deliveryStore"];
+ readonly secretStore?: ChannelRuntimeDependencies["secretStore"];
+ readonly settings?: ChannelRuntimeDependencies["settings"];
+ readonly startTransport?: ChannelRuntimeDependencies["startTransport"] | null;
+ readonly failBotUpdate?: (updateIndex: number) => Error | undefined;
+}) {
+ let model = makeModel(input.bots ?? [makeBot(BOT_ID)]);
+ let settings = DEFAULT_SERVER_SETTINGS;
+ const threads = [...(input.threads ?? [])];
+ const commands: OrchestrationCommand[] = [];
+ const { store: memorySecretStore, values: secrets } = makeMemorySecretStore();
+ const secretStore = input.secretStore ?? memorySecretStore;
+ let sequence = model.snapshotSequence;
+ let botUpdateIndex = 0;
+ const dispatch = (command: OrchestrationCommand) =>
+ Effect.sync(() => {
+ if (command.type === "bot.update") {
+ botUpdateIndex += 1;
+ const failure = input.failBotUpdate?.(botUpdateIndex);
+ if (failure) throw failure;
+ }
+ commands.push(command);
+ sequence += 1;
+ const channelBindings = command.type === "bot.update" ? command.channelBindings : undefined;
+ if (channelBindings !== undefined) {
+ const botId = command.type === "bot.update" ? command.botId : undefined;
+ model = {
+ ...model,
+ snapshotSequence: sequence,
+ bots: model.bots.map((bot) => (bot.id === botId ? { ...bot, channelBindings } : bot)),
+ };
+ }
+ if (command.type === "thread.create") {
+ threads.push(makeThread(command.threadId, command.botId!, []));
+ model = { ...model, threads };
+ }
+ return { sequence };
+ });
+ const engine = {
+ readEvents: () => Stream.empty,
+ dispatch,
+ streamDomainEvents: Stream.empty,
+ latestSequence: Effect.sync(() => sequence),
+ } satisfies OrchestrationEngineShape;
+ const dependencies: ChannelRuntimeDependencies = {
+ engine,
+ secretStore,
+ settings: input.settings ?? {
+ getSettings: Effect.sync(() => settings),
+ updateSettings: (patch) =>
+ Effect.sync(() => {
+ settings = { ...settings, ...patch } as typeof settings;
+ return settings;
+ }),
+ },
+ deliveryStore: input.deliveryStore ?? makeMemoryChannelDeliveryStore(),
+ readModel: async () => ({ ...model, threads }),
+ readThread: async (threadId) => threads.find((thread) => thread.id === threadId) ?? null,
+ nowIso: async () => NOW,
+ randomUuid: async () => `uuid-${commands.length}`,
+ ...(input.startTransport === null
+ ? {}
+ : {
+ startTransport:
+ input.startTransport ??
+ (async () => ({
+ externalIdentity: "@akeru",
+ runtime: {
+ post: input.post ?? (async () => undefined),
+ shutdown: input.shutdown ?? (async () => undefined),
+ },
+ })),
+ }),
+ };
+ return { commands, dependencies, secrets, readModel: () => model, readSettings: () => settings };
+}
+
+const telegramConnect = (botId: BotId, token = "telegram-token") => ({
+ type: "channel.connect" as const,
+ commandId: CommandId.make(`connect-${botId}`),
+ botId,
+ provider: "telegram" as const,
+ token,
+});
+
+const imessageConnect = (botId: BotId) => ({
+ type: "channel.connect" as const,
+ commandId: CommandId.make(`connect-imessage-${botId}`),
+ botId,
+ provider: "imessage" as const,
+ mode: "hosted" as const,
+ projectId: "photon-project",
+ projectSecret: "photon-secret",
+});
+
+const whatsappConnect = (botId: BotId) => ({
+ type: "channel.connect" as const,
+ commandId: CommandId.make(`connect-whatsapp-${botId}`),
+ botId,
+ provider: "whatsapp" as const,
+ accessToken: "access-token",
+ appSecret: "app-secret",
+ phoneNumberId: "phone-number-id",
+ verifyToken: "verify-token",
+});
+
+const signedWhatsAppRequest = (body: string) =>
+ new Request(`https://akeru.example/api/channels/whatsapp/${BOT_ID}/webhook`, {
+ method: "POST",
+ headers: {
+ "content-type": "application/json",
+ "x-hub-signature-256": `sha256=${createHmac("sha256", "app-secret").update(body).digest("hex")}`,
+ },
+ body,
+ });
+
+afterEach(async () => {
+ await shutdownAllChannels();
+ photon.adapter = null;
+ photon.chat = null;
+ photon.failedSubscription = null;
+ photon.subscriptionAttempts.length = 0;
+});
+
+describe("channel runtime", () => {
+ it("gives each external conversation a stable isolated thread", () => {
+ const first = channelThreadId(BOT_ID, "telegram", "telegram:123");
+
+ 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);
+ });
+
+ it("preserves the inbound provider, thread, and sender on the turn command", async () => {
+ const harness = makeHarness({});
+
+ await dispatchInboundChannelMessage(harness.dependencies, {
+ botId: BOT_ID,
+ provider: "telegram",
+ externalThreadId: "chat-a",
+ externalSenderId: "sender-7",
+ text: "Hello",
+ });
+
+ 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.channelOrigin).toEqual({
+ provider: "telegram",
+ externalThreadId: "chat-a",
+ externalSenderId: "sender-7",
+ });
+ });
+
+ it("verifies WhatsApp webhook challenges", async () => {
+ const harness = makeHarness({ startTransport: null });
+ await connectChannel(harness.dependencies, whatsappConnect(BOT_ID));
+
+ const accepted = await handleWhatsAppWebhook(
+ BOT_ID,
+ new Request(
+ `https://akeru.example/api/channels/whatsapp/${BOT_ID}/webhook?hub.mode=subscribe&hub.verify_token=verify-token&hub.challenge=challenge-123`,
+ ),
+ );
+ const rejected = await handleWhatsAppWebhook(
+ BOT_ID,
+ new Request(
+ `https://akeru.example/api/channels/whatsapp/${BOT_ID}/webhook?hub.mode=subscribe&hub.verify_token=wrong&hub.challenge=challenge-123`,
+ ),
+ );
+
+ expect(accepted.status).toBe(200);
+ expect(await accepted.text()).toBe("challenge-123");
+ expect(rejected.status).toBe(403);
+ });
+
+ it("validates and dispatches inbound WhatsApp DMs", async () => {
+ const harness = makeHarness({ startTransport: null });
+ await connectChannel(harness.dependencies, whatsappConnect(BOT_ID));
+ const payload = JSON.stringify({
+ object: "whatsapp_business_account",
+ entry: [
+ {
+ id: "business-id",
+ changes: [
+ {
+ field: "messages",
+ value: {
+ messaging_product: "whatsapp",
+ metadata: {
+ display_phone_number: "+15550001111",
+ phone_number_id: "phone-number-id",
+ },
+ contacts: [{ profile: { name: "Alice" }, wa_id: "15551234567" }],
+ messages: [
+ {
+ from: "15551234567",
+ id: "wamid.1",
+ timestamp: "1788220000",
+ text: { body: "Hello from WhatsApp" },
+ type: "text",
+ },
+ ],
+ },
+ },
+ ],
+ },
+ ],
+ });
+
+ const invalidSignature = await handleWhatsAppWebhook(
+ BOT_ID,
+ new Request(`https://akeru.example/api/channels/whatsapp/${BOT_ID}/webhook`, {
+ method: "POST",
+ body: payload,
+ }),
+ );
+ const invalidPayload = await handleWhatsAppWebhook(BOT_ID, signedWhatsAppRequest("{}"));
+ const accepted = await handleWhatsAppWebhook(BOT_ID, signedWhatsAppRequest(payload));
+
+ expect(invalidSignature.status).toBe(401);
+ expect(invalidPayload.status).toBe(400);
+ expect(accepted.status).toBe(200);
+ 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.channelOrigin).toEqual({
+ provider: "whatsapp",
+ externalThreadId: "whatsapp:phone-number-id:15551234567",
+ externalSenderId: "15551234567",
+ });
+ });
+
+ it("keeps DMs automatic and requires the exact bot mention in iMessage groups", 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) => {
+ directMessage = onDirectMessage;
+ transportContext = context;
+ return {
+ externalIdentity: "Photon hosted",
+ runtime: { post: async () => undefined, shutdown: async () => undefined },
+ };
+ },
+ });
+ await connectChannel(harness.dependencies, imessageConnect(BOT_ID));
+
+ await directMessage?.({
+ externalThreadId: "imessage:iMessage;-;+15551234567",
+ externalSenderId: "+15551234567",
+ 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",
+ });
+
+ expect(harness.commands.filter((command) => command.type === "thread.turn.start")).toHaveLength(
+ 1,
+ );
+
+ await transportContext?.onIMessageGroupMessage({
+ externalThreadId: "imessage:opaque-family-chat",
+ externalSenderId: "+15557654321",
+ text: "@build bot check the build",
+ });
+
+ 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"),
+ );
+
+ await transportContext?.onIMessageGroupMessage({
+ externalThreadId: "imessage:opaque-family-chat",
+ externalSenderId: "+15557654321",
+ text: "@build bot check again",
+ });
+
+ const turnsAfterSecondMention = harness.commands.filter(
+ (command) => command.type === "thread.turn.start",
+ );
+ expect(turnsAfterSecondMention.map((turn) => turn.message.text)).toEqual([
+ "DM without a mention",
+ turns[1]?.message.text,
+ "@build bot check again",
+ ]);
+ });
+
+ it("keeps recent iMessage context separate by group", async () => {
+ let transportContext:
+ | Parameters<NonNullable<ChannelRuntimeDependencies["startTransport"]>>[2]
+ | undefined;
+ 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 },
+ };
+ },
+ });
+ 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 transportContext?.onIMessageGroupMessage({
+ externalThreadId: "imessage:group-b",
+ externalSenderId: "dave",
+ text: "@build bot answer B",
+ });
+
+ 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("bounds buffered iMessage group chatter", async () => {
+ let transportContext:
+ | Parameters<NonNullable<ChannelRuntimeDependencies["startTransport"]>>[2]
+ | undefined;
+ 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 },
+ };
+ },
+ });
+ await connectChannel(harness.dependencies, imessageConnect(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",
+ });
+
+ 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);
+ });
+
+ 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.");
+
+ 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"),
+ );
+
+ 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",
+ ]);
+ });
+
+ 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;
+
+ await connectChannel(harness.dependencies, imessageConnect(BOT_ID));
+ await stopChannelsForBot(BOT_ID);
+ await expect(restoreConnectedChannels(harness.dependencies)).resolves.toEqual([]);
+
+ expect(photon.subscriptionAttempts.filter((id) => id === groupId)).toHaveLength(2);
+ expect(photon.subscriptionAttempts.filter((id) => id === badGroupId)).toHaveLength(2);
+ });
+
+ 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 }> = [];
+ 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 }),
+ });
+ await connectChannel(harness.dependencies, imessageConnect(BOT_ID));
+
+ await sendChannelMessage(harness.dependencies, { botId: BOT_ID, threadId, messageId });
+
+ expect(posts).toEqual([{ externalThreadId: groupId, text: "Build is green" }]);
+ });
+
+ it("rejects inbound messages for archived bots", async () => {
+ const harness = makeHarness({ bots: [makeBot(BOT_ID, { archivedAt: NOW })] });
+
+ await expect(
+ dispatchInboundChannelMessage(harness.dependencies, {
+ botId: BOT_ID,
+ provider: "telegram",
+ externalThreadId: "chat-a",
+ text: "Hello",
+ }),
+ ).rejects.toThrow("unavailable");
+ expect(harness.commands).toEqual([]);
+ });
+
+ it("shows connected persisted bindings as needing reconnect until transport starts", () => {
+ const binding: ChannelBinding = {
+ botId: BOT_ID,
+ provider: "telegram",
+ status: "connected",
+ externalIdentity: "@akeru",
+ connectedAt: NOW,
+ sentMessageIds: [],
+ };
+
+ expect(channelBindingsForRuntime([binding], () => false)).toEqual([
+ { ...binding, status: "needs-reconnect" },
+ ]);
+ expect(channelBindingsForRuntime([binding], () => true)).toEqual([binding]);
+ });
+
+ it("rejects archived bot connections and skips them during restore", async () => {
+ let starts = 0;
+ const binding: ChannelBinding = {
+ botId: BOT_ID,
+ provider: "telegram",
+ status: "connected",
+ externalIdentity: "@akeru",
+ connectedAt: NOW,
+ sentMessageIds: [],
+ };
+ const harness = makeHarness({
+ bots: [makeBot(BOT_ID, { archivedAt: NOW, channelBindings: [binding] })],
+ startTransport: async () => {
+ starts += 1;
+ throw new Error("Transport must not start.");
+ },
+ });
+
+ await expect(connectChannel(harness.dependencies, telegramConnect(BOT_ID))).rejects.toThrow(
+ "unavailable",
+ );
+ await expect(restoreConnectedChannels(harness.dependencies)).resolves.toEqual([]);
+ expect(starts).toBe(0);
+ });
+
+ it("stops every live transport on bot archive events without stopping restored bots", async () => {
+ let stops = 0;
+ const harness = makeHarness({ shutdown: async () => void (stops += 1) });
+ await connectChannel(harness.dependencies, telegramConnect(BOT_ID));
+ await connectChannel(harness.dependencies, imessageConnect(BOT_ID));
+ const eventBase = {
+ sequence: 13,
+ eventId: EventId.make("event-bot-lifecycle"),
+ aggregateKind: "bot" as const,
+ aggregateId: BOT_ID,
+ occurredAt: NOW,
+ commandId: CommandId.make("command-bot-lifecycle"),
+ causationEventId: null,
+ correlationId: CommandId.make("command-bot-lifecycle"),
+ metadata: {},
+ };
+
+ await Effect.runPromise(
+ stopArchivedBotChannels(
+ Stream.make({
+ ...eventBase,
+ type: "bot.restored",
+ payload: { botId: BOT_ID, updatedAt: NOW },
+ }),
+ ),
+ );
+ expect(stops).toBe(0);
+
+ await Effect.runPromise(
+ stopArchivedBotChannels(
+ Stream.make({
+ ...eventBase,
+ type: "bot.archived",
+ payload: { botId: BOT_ID, archivedAt: NOW, updatedAt: NOW },
+ }),
+ ),
+ );
+ expect(stops).toBe(2);
+ });
+
+ it("connects, disconnects, reconnects, restores, and stops a bot runtime", async () => {
+ let starts = 0;
+ let stops = 0;
+ const harness = makeHarness({
+ startTransport: async () => {
+ starts += 1;
+ return {
+ externalIdentity: "@akeru",
+ runtime: {
+ post: async () => undefined,
+ shutdown: async () => void (stops += 1),
+ },
+ };
+ },
+ });
+
+ await connectChannel(harness.dependencies, telegramConnect(BOT_ID));
+ expect(harness.readModel().bots[0]?.channelBindings?.[0]?.status).toBe("connected");
+ await stopChannelsForBot(BOT_ID);
+ expect(stops).toBe(1);
+ await reconnectChannel(harness.dependencies, BOT_ID, "telegram");
+ await stopChannelsForBot(BOT_ID);
+ await restoreConnectedChannels(harness.dependencies);
+ await disconnectChannel(harness.dependencies, BOT_ID, "telegram");
+
+ expect(starts).toBe(3);
+ expect(stops).toBe(3);
+ expect(harness.readModel().bots[0]?.channelBindings?.[0]?.status).toBe("disconnected");
+ expect(harness.secrets.size).toBe(0);
+ });
+
+ it("saves, attaches, reconnects, detaches, and deletes a reusable connection", async () => {
+ const connectionId = ChannelConnectionId.make("telegram-main");
+ const harness = makeHarness({});
+
+ await saveChannelConnection(harness.dependencies, {
+ type: "channel.connection.save",
+ commandId: CommandId.make("save-connection"),
+ connectionId,
+ name: "Main Telegram",
+ provider: "telegram",
+ token: "telegram-token",
+ });
+ await attachChannelConnection(harness.dependencies, BOT_ID, connectionId, "telegram");
+ expect(harness.readSettings().channelConnections).toEqual([
+ {
+ id: connectionId,
+ name: "Main Telegram",
+ provider: "telegram",
+ adapter: "telegram",
+ },
+ ]);
+ expect(harness.readModel().bots[0]?.channelBindings?.[0]).toMatchObject({
+ connectionId,
+ provider: "telegram",
+ status: "connected",
+ });
+
+ await expect(
+ saveChannelConnection(harness.dependencies, {
+ type: "channel.connection.save",
+ commandId: CommandId.make("edit-attached-connection"),
+ connectionId,
+ name: "Changed Telegram",
+ provider: "telegram",
+ token: "changed-token",
+ }),
+ ).rejects.toThrow("Disconnect this channel before editing it");
+
+ await expect(deleteChannelConnection(harness.dependencies, connectionId)).rejects.toThrow(
+ "Disconnect 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",
+ );
+ expect(harness.secrets.size).toBe(1);
+ await deleteChannelConnection(harness.dependencies, connectionId);
+ expect(harness.secrets.size).toBe(0);
+ expect(harness.readSettings().channelConnections).toEqual([]);
+ });
+
+ it("serializes multiple reusable connection profiles", async () => {
+ const telegramId = ChannelConnectionId.make("telegram-work");
+ const photonId = ChannelConnectionId.make("photon-personal");
+ const harness = makeHarness({});
+
+ await Promise.all([
+ saveChannelConnection(harness.dependencies, {
+ type: "channel.connection.save",
+ commandId: CommandId.make("save-telegram"),
+ connectionId: telegramId,
+ name: "Work Telegram",
+ provider: "telegram",
+ token: "telegram-token",
+ }),
+ saveChannelConnection(harness.dependencies, {
+ type: "channel.connection.save",
+ commandId: CommandId.make("save-photon"),
+ connectionId: photonId,
+ name: "Personal iPhone",
+ provider: "imessage",
+ mode: "self-hosted",
+ serverUrl: "photon.example:443",
+ apiKey: "photon-key",
+ phone: "+15551234567",
+ }),
+ ]);
+
+ expect(harness.readSettings().channelConnections).toEqual([
+ {
+ id: telegramId,
+ name: "Work Telegram",
+ provider: "telegram",
+ adapter: "telegram",
+ },
+ {
+ id: photonId,
+ name: "Personal iPhone",
+ provider: "imessage",
+ adapter: "photon",
+ externalIdentity: "+15551234567",
+ },
+ ]);
+ });
+
+ it("stores a safe dashboard link for hosted Photon", async () => {
+ const connectionId = ChannelConnectionId.make("photon-hosted");
+ const harness = makeHarness({});
+
+ await saveChannelConnection(harness.dependencies, {
+ type: "channel.connection.save",
+ commandId: CommandId.make("save-photon-hosted"),
+ connectionId,
+ name: "Launch iPhone",
+ provider: "imessage",
+ mode: "hosted",
+ projectId: "project/launch",
+ projectSecret: "never-in-settings",
+ });
+
+ expect(harness.readSettings().channelConnections).toEqual([
+ {
+ id: connectionId,
+ name: "Launch iPhone",
+ provider: "imessage",
+ adapter: "photon",
+ externalIdentity: "project/launch",
+ managementUrl: "https://app.photon.codes/dashboard/project%2Flaunch",
+ },
+ ]);
+ expect(JSON.stringify(harness.readSettings().channelConnections)).not.toContain(
+ "never-in-settings",
+ );
+ });
+
+ it("rolls back a saved secret when profile persistence fails", async () => {
+ const connectionId = ChannelConnectionId.make("failed-profile");
+ const harness = makeHarness({
+ settings: {
+ getSettings: Effect.succeed(DEFAULT_SERVER_SETTINGS),
+ updateSettings: () => Effect.die(new Error("settings write failed")),
+ },
+ });
+
+ await expect(
+ saveChannelConnection(harness.dependencies, {
+ type: "channel.connection.save",
+ commandId: CommandId.make("save-failed-profile"),
+ connectionId,
+ name: "Failed profile",
+ provider: "telegram",
+ token: "telegram-token",
+ }),
+ ).rejects.toThrow("settings write failed");
+ expect(harness.secrets.size).toBe(0);
+ });
+
+ it("restores saved WhatsApp credentials", async () => {
+ let starts = 0;
+ const harness = makeHarness({
+ startTransport: async (input) => {
+ starts += 1;
+ expect(input).toMatchObject({
+ provider: "whatsapp",
+ accessToken: "access-token",
+ appSecret: "app-secret",
+ phoneNumberId: "phone-number-id",
+ verifyToken: "verify-token",
+ });
+ return {
+ externalIdentity: "phone-number-id",
+ runtime: { post: async () => undefined, shutdown: async () => undefined },
+ };
+ },
+ });
+
+ await connectChannel(harness.dependencies, whatsappConnect(BOT_ID));
+ await stopChannelsForBot(BOT_ID);
+ await restoreConnectedChannels(harness.dependencies);
+
+ expect(starts).toBe(2);
+ });
+
+ 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 posts: Array<{ readonly externalThreadId: string; readonly text: string }> = [];
+ const harness = makeHarness({
+ threads: [
+ makeThread(threadId, BOT_ID, [
+ makeMessage(MessageId.make("whatsapp-inbound"), "user", "Question", {
+ provider: "whatsapp",
+ externalThreadId,
+ externalSenderId: "15551234567",
+ }),
+ makeMessage(messageId, "assistant", "Approved answer"),
+ ]),
+ ],
+ post: async (target, text) => void posts.push({ externalThreadId: target, text }),
+ });
+ await connectChannel(harness.dependencies, whatsappConnect(BOT_ID));
+
+ await sendChannelMessage(harness.dependencies, { botId: BOT_ID, threadId, messageId });
+
+ expect(posts).toEqual([{ externalThreadId, text: "Approved answer" }]);
+ });
+
+ it("automatically sends one completed reply for an inbound channel turn", async () => {
+ const turnId = TurnId.make("turn-auto-reply");
+ const requestMessageId = MessageId.make("inbound-auto-reply");
+ const messageId = MessageId.make("assistant-auto-reply");
+ const threadId = ThreadId.make("thread-auto-reply");
+ let posts = 0;
+ const thread: OrchestrationThread = {
+ ...makeThread(threadId, BOT_ID, [
+ makeMessage(requestMessageId, "user", "Hello", {
+ provider: "imessage",
+ externalThreadId: "iMessage;-;sender",
+ }),
+ { ...makeMessage(messageId, "assistant", "Hello back"), turnId },
+ ]),
+ latestTurn: {
+ turnId,
+ state: "completed",
+ requestedAt: NOW,
+ startedAt: NOW,
+ completedAt: NOW,
+ assistantMessageId: messageId,
+ requestMessageId,
+ respondingBotId: BOT_ID,
+ },
+ };
+ const harness = makeHarness({
+ threads: [thread],
+ post: async () => void (posts += 1),
+ });
+ await connectChannel(harness.dependencies, imessageConnect(BOT_ID));
+
+ await expect(
+ sendCompletedChannelReply(harness.dependencies, threadId, turnId),
+ ).resolves.toBeGreaterThan(0);
+ await expect(
+ sendCompletedChannelReply(harness.dependencies, threadId, turnId),
+ ).resolves.toBeGreaterThan(0);
+
+ expect(posts).toBe(1);
+ expect(harness.readModel().bots[0]?.channelBindings[0]?.sentMessageIds).toContain(messageId);
+
+ await expect(
+ sendCompletedChannelReply(
+ harness.dependencies,
+ threadId,
+ TurnId.make("stale-auto-reply-turn"),
+ ),
+ ).resolves.toBeNull();
+ expect(posts).toBe(1);
+ });
+
+ 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");
+ const localMessageId = MessageId.make("local-request");
+ const assistantMessageId = MessageId.make("local-assistant");
+ const threadId = ThreadId.make("thread-local-after-channel");
+ let posts = 0;
+ const thread: OrchestrationThread = {
+ ...makeThread(threadId, BOT_ID, [
+ makeMessage(inboundMessageId, "user", "Channel question", {
+ provider: "imessage",
+ externalThreadId: "iMessage;-;sender",
+ }),
+ makeMessage(localMessageId, "user", "Local question"),
+ { ...makeMessage(assistantMessageId, "assistant", "Local answer"), turnId },
+ ]),
+ latestTurn: {
+ turnId,
+ state: "completed",
+ requestedAt: NOW,
+ startedAt: NOW,
+ completedAt: NOW,
+ assistantMessageId,
+ requestMessageId: localMessageId,
+ respondingBotId: BOT_ID,
+ },
+ };
+ const harness = makeHarness({
+ threads: [thread],
+ post: async () => void (posts += 1),
+ });
+ await connectChannel(harness.dependencies, imessageConnect(BOT_ID));
+
+ await expect(
+ sendCompletedChannelReply(harness.dependencies, threadId, turnId),
+ ).resolves.toBeNull();
+
+ expect(posts).toBe(0);
+ });
+
+ it("uses collision-free secret names for distinct bot IDs", async () => {
+ const firstId = BotId.make("sales/east");
+ const secondId = BotId.make("sales?east");
+ const harness = makeHarness({ bots: [makeBot(firstId), makeBot(secondId)] });
+
+ await connectChannel(harness.dependencies, telegramConnect(firstId, "token-1"));
+ await connectChannel(harness.dependencies, telegramConnect(secondId, "token-2"));
+
+ expect(harness.secrets.size).toBe(2);
+ expect([...harness.secrets.keys()].every((name) => !name.includes("sales"))).toBe(true);
+ });
+
+ it("stops a new transport when reading the previous secret fails", async () => {
+ const { store } = makeMemorySecretStore();
+ let stops = 0;
+ const harness = makeHarness({
+ secretStore: { ...store, get: () => Effect.die(new Error("secret read failed")) },
+ shutdown: async () => void (stops += 1),
+ });
+
+ await expect(connectChannel(harness.dependencies, telegramConnect(BOT_ID))).rejects.toThrow(
+ "secret read failed",
+ );
+
+ expect(stops).toBe(1);
+ expect(harness.readModel().bots[0]?.channelBindings).toEqual([]);
+ });
+
+ it("keeps a connected runtime when removing its secret fails", async () => {
+ const { store, values } = makeMemorySecretStore();
+ let failRemove = false;
+ let stops = 0;
+ const harness = makeHarness({
+ secretStore: {
+ ...store,
+ remove: (name) =>
+ failRemove ? Effect.die(new Error("secret remove failed")) : store.remove(name),
+ },
+ shutdown: async () => void (stops += 1),
+ });
+ await connectChannel(harness.dependencies, telegramConnect(BOT_ID));
+ failRemove = true;
+
+ await expect(disconnectChannel(harness.dependencies, BOT_ID, "telegram")).rejects.toThrow(
+ "secret remove failed",
+ );
+
+ const binding = harness.readModel().bots[0]?.channelBindings?.[0];
+ expect(binding?.status).toBe("connected");
+ expect(binding && channelBindingsForRuntime([binding])).toEqual([binding]);
+ expect(values.size).toBe(1);
+ 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)] });
+
+ await connectChannel(harness.dependencies, telegramConnect(BOT_ID));
+ await expect(connectChannel(harness.dependencies, telegramConnect(secondId))).rejects.toThrow(
+ "already connected",
+ );
+ });
+
+ it("rejects one WhatsApp number bound to two active bots", async () => {
+ const secondId = BotId.make("bot-2");
+ const harness = makeHarness({ bots: [makeBot(BOT_ID), makeBot(secondId)] });
+
+ await connectChannel(harness.dependencies, whatsappConnect(BOT_ID));
+ await expect(connectChannel(harness.dependencies, whatsappConnect(secondId))).rejects.toThrow(
+ "already connected",
+ );
+ });
+
+ it("serializes concurrent WhatsApp identity claims", async () => {
+ const secondId = BotId.make("bot-2");
+ const harness = makeHarness({ bots: [makeBot(BOT_ID), makeBot(secondId)] });
+
+ const results = await Promise.allSettled([
+ connectChannel(harness.dependencies, whatsappConnect(BOT_ID)),
+ connectChannel(harness.dependencies, whatsappConnect(secondId)),
+ ]);
+
+ expect(results.filter((result) => result.status === "fulfilled")).toHaveLength(1);
+ expect(results.filter((result) => result.status === "rejected")).toHaveLength(1);
+ expect(
+ harness
+ .readModel()
+ .bots.flatMap((bot) => bot.channelBindings ?? [])
+ .filter((binding) => binding.provider === "whatsapp" && binding.status === "connected"),
+ ).toHaveLength(1);
+ });
+
+ it("releases a failed post so explicit approval can retry", async () => {
+ const messageId = MessageId.make("message-retry");
+ const threadId = ThreadId.make("thread-retry");
+ let posts = 0;
+ const harness = makeHarness({
+ threads: [
+ makeThread(threadId, BOT_ID, [
+ makeMessage(MessageId.make("inbound"), "user", "Question", {
+ provider: "telegram",
+ externalThreadId: "chat-retry",
+ }),
+ makeMessage(messageId, "assistant", "Retry me"),
+ ]),
+ ],
+ post: async () => {
+ posts += 1;
+ if (posts === 1) throw new Error("transport unavailable");
+ },
+ });
+ await connectChannel(harness.dependencies, telegramConnect(BOT_ID));
+
+ await expect(
+ sendChannelMessage(harness.dependencies, { botId: BOT_ID, threadId, messageId }),
+ ).rejects.toThrow("transport unavailable");
+ await expect(
+ sendChannelMessage(harness.dependencies, { botId: BOT_ID, threadId, messageId }),
+ ).resolves.toBeGreaterThan(0);
+ expect(posts).toBe(2);
+ });
+
+ it("does not mark 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;
+ let posts = 0;
+ let marks = 0;
+ const deliveryStore: ChannelRuntimeDependencies["deliveryStore"] = {
+ claim: () =>
+ Effect.sync(() => {
+ if (status) return status;
+ status = "requested";
+ return "claimed";
+ }),
+ releaseRequested: () => Effect.die(new Error("release failed")),
+ markSent: () => Effect.sync(() => void (marks += 1)),
+ };
+ const harness = makeHarness({
+ deliveryStore,
+ threads: [
+ makeThread(threadId, BOT_ID, [
+ makeMessage(MessageId.make("inbound-release"), "user", "Question", {
+ provider: "telegram",
+ externalThreadId: "chat-release",
+ }),
+ makeMessage(messageId, "assistant", "Do not mark me sent"),
+ ]),
+ ],
+ post: async () => {
+ posts += 1;
+ throw new Error("post failed");
+ },
+ });
+ await connectChannel(harness.dependencies, telegramConnect(BOT_ID));
+
+ await expect(
+ sendChannelMessage(harness.dependencies, { botId: BOT_ID, threadId, messageId }),
+ ).rejects.toThrow("release failed");
+ await expect(
+ sendChannelMessage(harness.dependencies, { botId: BOT_ID, threadId, messageId }),
+ ).rejects.toThrow("unfinished delivery attempt");
+
+ expect(posts).toBe(1);
+ expect(marks).toBe(0);
+ });
+
+ it("does not repost after transport succeeds and mark-sent fails", async () => {
+ const messageId = MessageId.make("message-mark-sent-retry");
+ const threadId = ThreadId.make("thread-mark-sent-retry");
+ let deliveryStatus: "requested" | "sent" | undefined;
+ let markAttempts = 0;
+ let posts = 0;
+ const deliveryStore: ChannelRuntimeDependencies["deliveryStore"] = {
+ claim: () =>
+ Effect.sync(() => {
+ if (deliveryStatus) return deliveryStatus;
+ deliveryStatus = "requested";
+ return "claimed";
+ }),
+ releaseRequested: () => Effect.sync(() => void (deliveryStatus = undefined)),
+ markSent: () =>
+ Effect.sync(() => {
+ markAttempts += 1;
+ if (markAttempts === 1) throw new Error("database unavailable");
+ deliveryStatus = "sent";
+ }),
+ };
+ const harness = makeHarness({
+ deliveryStore,
+ threads: [
+ makeThread(threadId, BOT_ID, [
+ makeMessage(MessageId.make("inbound-mark"), "user", "Question", {
+ provider: "telegram",
+ externalThreadId: "chat-mark",
+ }),
+ makeMessage(messageId, "assistant", "Send once"),
+ ]),
+ ],
+ post: async () => void (posts += 1),
+ });
+ await connectChannel(harness.dependencies, telegramConnect(BOT_ID));
+
+ await expect(
+ sendChannelMessage(harness.dependencies, { botId: BOT_ID, threadId, messageId }),
+ ).rejects.toThrow("database unavailable");
+ await expect(
+ sendChannelMessage(harness.dependencies, { botId: BOT_ID, threadId, messageId }),
+ ).resolves.toBeGreaterThan(0);
+ expect(posts).toBe(1);
+ expect(markAttempts).toBe(2);
+ });
+
+ 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");
+ let posts = 0;
+ const harness = makeHarness({
+ failBotUpdate: (updateIndex) =>
+ updateIndex === 2 ? new Error("binding persistence failed") : undefined,
+ threads: [
+ makeThread(threadId, BOT_ID, [
+ makeMessage(MessageId.make("inbound-binding"), "user", "Question", {
+ provider: "telegram",
+ externalThreadId: "chat-binding",
+ }),
+ makeMessage(messageId, "assistant", "Send once and recover"),
+ ]),
+ ],
+ post: async () => void (posts += 1),
+ });
+ await connectChannel(harness.dependencies, telegramConnect(BOT_ID));
+
+ await expect(
+ sendChannelMessage(harness.dependencies, { botId: BOT_ID, threadId, messageId }),
+ ).rejects.toThrow("binding persistence failed");
+ await expect(
+ sendChannelMessage(harness.dependencies, { botId: BOT_ID, threadId, messageId }),
+ ).resolves.toBeGreaterThan(0);
+
+ expect(posts).toBe(1);
+ expect(harness.readModel().bots[0]?.channelBindings[0]?.sentMessageIds).toContain(messageId);
+ });
+});
diff --git a/apps/server/src/channels/ChannelRuntime.ts b/apps/server/src/channels/ChannelRuntime.ts
new file mode 100644
index 000000000..b02153990
--- /dev/null
+++ b/apps/server/src/channels/ChannelRuntime.ts
@@ -0,0 +1,1208 @@
+import { createHash } from "node:crypto";
+
+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,
+ ChannelConnectionId,
+ CommandId,
+ MessageId,
+ ProviderInstanceId,
+ ThreadId,
+ TurnId,
+ type ChannelBinding,
+ type ChannelConnectionProfile,
+ type ChannelProvider,
+ type ClientOrchestrationCommand,
+ type OrchestrationEvent,
+ type OrchestrationReadModel,
+ type OrchestrationThread,
+} from "@t3tools/contracts";
+import { type Adapter, Chat } from "chat";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import type * as Option from "effect/Option";
+import * as Schema from "effect/Schema";
+import * as Stream from "effect/Stream";
+import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
+
+import type { ServerSecretStore } from "../auth/ServerSecretStore.ts";
+import type { ServerSettingsService } from "../serverSettings.ts";
+import type * as OrchestrationEngine from "../orchestration/Services/OrchestrationEngine.ts";
+import type { ChannelDeliveryStoreShape } from "./ChannelDeliveryStore.ts";
+
+interface ChannelRuntimeEntry {
+ readonly post: (externalThreadId: string, text: string) => Promise<void>;
+ readonly shutdown: () => Promise<void>;
+ readonly webhook?: (request: Request) => Promise<Response>;
+}
+
+interface StartedChannel {
+ readonly binding: ChannelBinding;
+ readonly runtime: ChannelRuntimeEntry;
+}
+
+interface InboundChannelMessage {
+ readonly externalThreadId: string;
+ readonly externalSenderId?: string;
+ readonly text: string;
+}
+
+interface ChannelTransportContext {
+ readonly botName: string;
+ readonly subscribedIMessageGroupIds: ReadonlyArray<string>;
+ readonly onIMessageGroupMessage: (input: InboundChannelMessage) => Promise<void>;
+}
+
+type LiveProvider = ChannelProvider;
+type ChannelConnectInput = Extract<
+ ClientOrchestrationCommand,
+ { readonly type: "channel.connect" }
+>;
+type ChannelConnectionSaveInput = Extract<
+ ClientOrchestrationCommand,
+ { readonly type: "channel.connection.save" }
+>;
+
+export interface ChannelRuntimeDependencies {
+ readonly engine: OrchestrationEngine.OrchestrationEngineShape;
+ readonly secretStore: ServerSecretStore["Service"];
+ readonly settings: Pick<ServerSettingsService["Service"], "getSettings" | "updateSettings">;
+ readonly deliveryStore: ChannelDeliveryStoreShape;
+ readonly readModel: () => Promise<OrchestrationReadModel>;
+ readonly readThread: (threadId: ThreadId) => Promise<OrchestrationThread | null>;
+ readonly nowIso: () => Promise<string>;
+ readonly randomUuid: () => Promise<string>;
+ readonly startTransport?: (
+ input: ChannelConnectInput,
+ onDirectMessage: (input: InboundChannelMessage) => Promise<void>,
+ context: ChannelTransportContext,
+ ) => Promise<{ readonly externalIdentity: string; readonly runtime: ChannelRuntimeEntry }>;
+}
+
+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;
+const encoder = new TextEncoder();
+const decoder = new TextDecoder();
+
+const StoredChannelSecret = Schema.Union([
+ Schema.Struct({ provider: Schema.Literal("telegram"), token: Schema.String }),
+ Schema.Struct({
+ provider: Schema.Literal("imessage"),
+ mode: Schema.Literals(["hosted", "self-hosted"]),
+ projectId: Schema.optional(Schema.String),
+ projectSecret: Schema.optional(Schema.String),
+ serverUrl: Schema.optional(Schema.String),
+ apiKey: Schema.optional(Schema.String),
+ phone: Schema.optional(Schema.String),
+ }),
+ Schema.Struct({
+ provider: Schema.Literal("whatsapp"),
+ accessToken: Schema.String,
+ appSecret: Schema.String,
+ phoneNumberId: Schema.String,
+ verifyToken: Schema.String,
+ }),
+]);
+type StoredChannelSecret = typeof StoredChannelSecret.Type;
+const decodeStoredChannelSecret = Schema.decodeUnknownEffect(StoredChannelSecret);
+
+const runtimeKey = (botId: string, provider: ChannelProvider) => `${botId}:${provider}`;
+const operationKey = (provider: ChannelProvider) => provider;
+const secretName = (botId: BotId, provider: ChannelProvider) =>
+ `channel-${provider}-${createHash("sha256").update(botId).digest("hex")}`;
+const connectionSecretName = (connectionId: ChannelConnectionId) =>
+ `channel-connection-${createHash("sha256").update(connectionId).digest("hex")}`;
+
+export const channelThreadId = (
+ botId: BotId,
+ provider: LiveProvider,
+ externalThreadId: string,
+): ThreadId =>
+ ThreadId.make(
+ `channel-${createHash("sha256").update(`${botId}\0${provider}\0${externalThreadId}`).digest("hex")}`,
+ );
+
+export const WHATSAPP_WEBHOOK_PATH = "/api/channels/whatsapp/:botId/webhook";
+
+export async function handleWhatsAppWebhook(botId: BotId, request: Request): Promise<Response> {
+ const webhook = runtimes.get(runtimeKey(botId, "whatsapp"))?.webhook;
+ return webhook ? webhook(request) : new Response("Not Found", { status: 404 });
+}
+
+const whatsAppWebhookHttpHandler = Effect.gen(function* () {
+ const params = yield* HttpRouter.schemaPathParams(Schema.Struct({ botId: BotId })).pipe(
+ Effect.option,
+ );
+ if (params._tag === "None") return HttpServerResponse.text("Not Found", { status: 404 });
+ const request = yield* HttpServerRequest.HttpServerRequest;
+ const webRequest = yield* HttpServerRequest.toWeb(request).pipe(Effect.option);
+ if (webRequest._tag === "None") return HttpServerResponse.text("Bad Request", { status: 400 });
+ const response = yield* Effect.promise(() =>
+ handleWhatsAppWebhook(params.value.botId, webRequest.value),
+ );
+ return HttpServerResponse.fromWeb(response);
+});
+
+export const whatsAppWebhookRouteLayer = Layer.merge(
+ HttpRouter.add("GET", WHATSAPP_WEBHOOK_PATH, whatsAppWebhookHttpHandler),
+ HttpRouter.add("POST", WHATSAPP_WEBHOOK_PATH, whatsAppWebhookHttpHandler),
+);
+
+const isIMessageDirectThread = (externalThreadId: string) => externalThreadId.includes(";-;");
+
+const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+
+const iMessageGroupTrigger = (botName: string) =>
+ new RegExp(`(?:^|[^\\p{L}\\p{N}_])@${escapeRegExp(botName)}(?=$|[^\\p{L}\\p{N}_-])`, "iu");
+
+function subscribedIMessageGroupIds(
+ model: OrchestrationReadModel,
+ botId: BotId,
+): ReadonlyArray<string> {
+ const ids = new Set<string>();
+ for (const thread of model.threads) {
+ if (thread.botId !== botId || thread.groupId !== null || thread.deletedAt !== null) 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);
+ }
+ }
+ }
+ return [...ids];
+}
+
+export function channelBindingsForRuntime(
+ bindings: ReadonlyArray<ChannelBinding>,
+ isRunning: (botId: BotId, provider: ChannelProvider) => boolean = (botId, provider) =>
+ runtimes.has(runtimeKey(botId, provider)),
+): ReadonlyArray<ChannelBinding> {
+ return bindings.map((binding) =>
+ binding.status === "connected" && !isRunning(binding.botId, binding.provider)
+ ? { ...binding, status: "needs-reconnect" }
+ : binding,
+ );
+}
+
+const randomId = async (dependencies: ChannelRuntimeDependencies, prefix: string) =>
+ `${prefix}-${await dependencies.randomUuid()}`;
+
+async function loadSecret(
+ dependencies: ChannelRuntimeDependencies,
+ botId: BotId,
+ provider: LiveProvider,
+): Promise<StoredChannelSecret | null> {
+ const stored = await Effect.runPromise(dependencies.secretStore.get(secretName(botId, provider)));
+ if (stored._tag === "None") return null;
+ const raw: unknown = JSON.parse(decoder.decode(stored.value));
+ return Effect.runPromise(decodeStoredChannelSecret(raw));
+}
+
+async function loadConnectionSecret(
+ dependencies: ChannelRuntimeDependencies,
+ connectionId: ChannelConnectionId,
+): Promise<StoredChannelSecret | null> {
+ const stored = await Effect.runPromise(
+ dependencies.secretStore.get(connectionSecretName(connectionId)),
+ );
+ if (stored._tag === "None") return null;
+ const raw: unknown = JSON.parse(decoder.decode(stored.value));
+ return Effect.runPromise(decodeStoredChannelSecret(raw));
+}
+
+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 } : {}),
+ };
+
+const connectInputFromSecret = (
+ botId: BotId,
+ 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 ?? ""}`;
+
+async function assertChannelIdentityAvailable(
+ dependencies: ChannelRuntimeDependencies,
+ botId: BotId,
+ candidateSecret: StoredChannelSecret,
+): Promise<void> {
+ const model = await dependencies.readModel();
+ 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") {
+ continue;
+ }
+ const secret = binding.connectionId
+ ? await loadConnectionSecret(dependencies, binding.connectionId).catch(() => null)
+ : await loadSecret(dependencies, bot.id, binding.provider).catch(() => null);
+ if (secret && channelSecretIdentity(secret) === channelSecretIdentity(candidateSecret)) {
+ throw new Error("This channel connection is already connected to another bot.");
+ }
+ }
+ }
+}
+
+export async function dispatchInboundChannelMessage(
+ dependencies: ChannelRuntimeDependencies,
+ input: {
+ readonly botId: BotId;
+ readonly provider: LiveProvider;
+ readonly externalThreadId: string;
+ readonly externalSenderId?: string;
+ readonly text: string;
+ },
+): Promise<void> {
+ const threadId = channelThreadId(input.botId, input.provider, input.externalThreadId);
+ const previous = inboundQueues.get(threadId) ?? Promise.resolve();
+ const next = previous
+ .catch(() => undefined)
+ .then(async () => {
+ const model = await dependencies.readModel();
+ const bot = model.bots.find(
+ (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 modelSelection = bot.engine
+ ? { instanceId: ProviderInstanceId.make(bot.engine.provider), model: bot.engine.model }
+ : project.defaultModelSelection;
+ if (!modelSelection)
+ throw new Error(`Bot '${bot.name}' needs a model before channel messages.`);
+
+ const existing = model.threads.find(
+ (thread) => thread.id === threadId && thread.deletedAt === null,
+ );
+ const createdAt = await dependencies.nowIso();
+ if (!existing) {
+ await Effect.runPromise(
+ dependencies.engine.dispatch({
+ type: "thread.create",
+ commandId: CommandId.make(await randomId(dependencies, "channel-create")),
+ threadId,
+ projectId: project.id,
+ botId: bot.id,
+ groupId: null,
+ title: bot.name,
+ modelSelection,
+ runtimeMode: bot.runtimeMode,
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ createdAt,
+ }),
+ );
+ } else if (existing.botId !== bot.id || existing.groupId != null) {
+ throw new Error(`Channel thread '${threadId}' belongs to another owner.`);
+ }
+
+ await Effect.runPromise(
+ dependencies.engine.dispatch({
+ type: "thread.turn.start",
+ commandId: CommandId.make(await randomId(dependencies, "channel-turn")),
+ threadId,
+ message: {
+ messageId: MessageId.make(await randomId(dependencies, "channel-message")),
+ role: "user",
+ text: input.text,
+ attachments: [],
+ channelOrigin: {
+ provider: input.provider,
+ externalThreadId: input.externalThreadId,
+ ...(input.externalSenderId ? { externalSenderId: input.externalSenderId } : {}),
+ },
+ },
+ modelSelection,
+ runtimeMode: bot.runtimeMode,
+ interactionMode: "default",
+ createdAt,
+ }),
+ );
+ });
+ inboundQueues.set(threadId, next);
+ try {
+ await next;
+ } finally {
+ if (inboundQueues.get(threadId) === next) inboundQueues.delete(threadId);
+ }
+}
+
+async function replaceBinding(
+ dependencies: ChannelRuntimeDependencies,
+ binding: ChannelBinding,
+): Promise<number> {
+ const previous = bindingQueues.get(binding.botId) ?? Promise.resolve();
+ const operation = previous
+ .catch(() => undefined)
+ .then(async () => {
+ const model = await dependencies.readModel();
+ const bot = model.bots.find((candidate) => candidate.id === binding.botId);
+ if (!bot) throw new Error(`Bot '${binding.botId}' does not exist.`);
+ const previousBinding = (bot.channelBindings ?? []).find(
+ (candidate) => candidate.provider === binding.provider,
+ );
+ const nextBinding = {
+ ...binding,
+ sentMessageIds:
+ binding.sentMessageIds.length > 0
+ ? binding.sentMessageIds
+ : (previousBinding?.sentMessageIds ?? []),
+ };
+ const receipt = await Effect.runPromise(
+ dependencies.engine.dispatch({
+ type: "bot.update",
+ commandId: CommandId.make(await randomId(dependencies, "channel-binding")),
+ botId: bot.id,
+ channelBindings: [
+ ...(bot.channelBindings ?? []).filter(
+ (candidate) => candidate.provider !== binding.provider,
+ ),
+ nextBinding,
+ ],
+ }),
+ );
+ return receipt.sequence;
+ });
+ const queued = operation.then(
+ () => undefined,
+ () => undefined,
+ );
+ bindingQueues.set(binding.botId, queued);
+ try {
+ return await operation;
+ } finally {
+ if (bindingQueues.get(binding.botId) === queued) bindingQueues.delete(binding.botId);
+ }
+}
+
+async function withChannelOperation<A>(
+ botId: BotId,
+ provider: ChannelProvider,
+ operation: () => Promise<A>,
+): Promise<A> {
+ const key = operationKey(provider);
+ const previous = operationQueues.get(key) ?? Promise.resolve();
+ const result = previous.catch(() => undefined).then(operation);
+ const queued = result.then(
+ () => undefined,
+ () => undefined,
+ );
+ operationQueues.set(key, queued);
+ try {
+ return await result;
+ } finally {
+ if (operationQueues.get(key) === queued) operationQueues.delete(key);
+ }
+}
+
+async function withConnectionOperation<A>(
+ connectionId: ChannelConnectionId,
+ operation: () => Promise<A>,
+): Promise<A> {
+ const key = `connection:${connectionId}`;
+ const previous = operationQueues.get(key) ?? Promise.resolve();
+ const result = previous.catch(() => undefined).then(operation);
+ const queued = result.then(
+ () => undefined,
+ () => undefined,
+ );
+ operationQueues.set(key, queued);
+ try {
+ return await result;
+ } finally {
+ if (operationQueues.get(key) === queued) operationQueues.delete(key);
+ }
+}
+
+async function withConnectionSettingsOperation<A>(operation: () => Promise<A>): Promise<A> {
+ const key = "connection-settings";
+ const previous = operationQueues.get(key) ?? Promise.resolve();
+ const result = previous.catch(() => undefined).then(operation);
+ const queued = result.then(
+ () => undefined,
+ () => undefined,
+ );
+ operationQueues.set(key, queued);
+ try {
+ return await result;
+ } finally {
+ if (operationQueues.get(key) === queued) operationQueues.delete(key);
+ }
+}
+
+async function stopRuntime(botId: BotId, provider: ChannelProvider): Promise<void> {
+ const key = runtimeKey(botId, provider);
+ const runtime = runtimes.get(key);
+ if (!runtime) return;
+ runtimes.delete(key);
+ await runtime.shutdown();
+}
+
+export async function stopChannelsForBot(botId: BotId): Promise<void> {
+ await Promise.allSettled(
+ (["telegram", "imessage", "whatsapp"] as const).map((provider) =>
+ withChannelOperation(botId, provider, () => stopRuntime(botId, provider)),
+ ),
+ );
+}
+
+export const stopArchivedBotChannels = (events: Stream.Stream<OrchestrationEvent>) =>
+ Stream.runForEach(events, (event) =>
+ event.type === "bot.archived"
+ ? Effect.promise(() => stopChannelsForBot(event.payload.botId))
+ : 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()));
+}
+
+async function startTelegram(
+ botId: BotId,
+ token: string,
+ onDirectMessage: Parameters<NonNullable<ChannelRuntimeDependencies["startTransport"]>>[1],
+): Promise<{ readonly externalIdentity: string; readonly runtime: ChannelRuntimeEntry }> {
+ const provider = new TelegramProvider({ mode: "polling", commands: [] });
+ const connected = await provider.connect(botId, { botToken: token, commands: [] });
+ if (connected.type !== "immediate") throw new Error("Telegram did not connect immediately.");
+ 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 },
+ state: createMemoryState(),
+ });
+ chat.onDirectMessage(async (thread, message) => {
+ if (!message.text.trim()) return;
+ await onDirectMessage({
+ externalThreadId: thread.id,
+ externalSenderId: message.author.userId,
+ text: message.text,
+ });
+ });
+ try {
+ await chat.initialize();
+ } catch (cause) {
+ await provider.disconnect(botId).catch(() => undefined);
+ throw cause;
+ }
+ return {
+ externalIdentity: installation.username ? `@${installation.username}` : botId,
+ runtime: {
+ post: async (externalThreadId, text) => void (await chat.thread(externalThreadId).post(text)),
+ shutdown: async () => {
+ await chat.shutdown();
+ await provider.disconnect(botId).catch(() => undefined);
+ },
+ },
+ };
+}
+
+async function startIMessage(
+ input: Extract<ChannelConnectInput, { readonly provider: "imessage" }>,
+ context: ChannelTransportContext,
+ onDirectMessage: Parameters<NonNullable<ChannelRuntimeDependencies["startTransport"]>>[1],
+): Promise<{ readonly externalIdentity: string; readonly runtime: ChannelRuntimeEntry }> {
+ const adapter = createiMessageAdapter(
+ input.mode === "hosted"
+ ? { projectId: input.projectId, projectSecret: input.projectSecret }
+ : {
+ serverUrl: input.serverUrl,
+ apiKey: input.apiKey,
+ ...(input.phone ? { phone: input.phone } : {}),
+ },
+ );
+ const chat = new Chat({
+ userName: context.botName,
+ adapters: { imessage: 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,
+ });
+ });
+ 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);
+ });
+ 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 chat.shutdown();
+ throw new Error(`Photon gateway failed with status ${response.status}.`);
+ }
+ return {
+ externalIdentity:
+ input.mode === "self-hosted" && input.phone
+ ? input.phone
+ : input.mode === "hosted"
+ ? "Photon hosted"
+ : "Photon self-hosted",
+ runtime: {
+ post: async (externalThreadId, text) => void (await chat.thread(externalThreadId).post(text)),
+ shutdown: async () => {
+ abort.abort();
+ await chat.shutdown();
+ },
+ },
+ };
+}
+
+async function startWhatsApp(
+ input: Extract<ChannelConnectInput, { readonly provider: "whatsapp" }>,
+ context: ChannelTransportContext,
+ onDirectMessage: Parameters<NonNullable<ChannelRuntimeDependencies["startTransport"]>>[1],
+): Promise<{ readonly externalIdentity: string; readonly runtime: ChannelRuntimeEntry }> {
+ const adapter = createWhatsAppAdapter({
+ accessToken: input.accessToken,
+ appSecret: input.appSecret,
+ phoneNumberId: input.phoneNumberId,
+ verifyToken: input.verifyToken,
+ userName: context.botName,
+ });
+ const chat = new Chat({
+ userName: context.botName,
+ adapters: { whatsapp: 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 chat.initialize();
+ return {
+ externalIdentity: input.phoneNumberId,
+ runtime: {
+ post: async (externalThreadId, text) => void (await chat.thread(externalThreadId).post(text)),
+ shutdown: () => chat.shutdown(),
+ webhook: async (request) => {
+ const tasks: Promise<unknown>[] = [];
+ let response: Response;
+ try {
+ response = await adapter.handleWebhook(request, {
+ waitUntil: (task) => void tasks.push(task),
+ });
+ } catch {
+ return new Response("Invalid webhook payload", { status: 400 });
+ }
+ const results = await Promise.allSettled(tasks);
+ return results.some((result) => result.status === "rejected")
+ ? new Response("Webhook processing failed", { status: 500 })
+ : response;
+ },
+ },
+ };
+}
+
+async function startChannel(
+ dependencies: ChannelRuntimeDependencies,
+ input: ChannelConnectInput,
+ connectionId?: ChannelConnectionId,
+): Promise<StartedChannel> {
+ 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 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"),
+ });
+ const consumedMessages = new Set(recentMessages);
+ iMessageGroupContext = iMessageGroupContext.filter(
+ (candidate) => !consumedMessages.has(candidate),
+ );
+ },
+ };
+ const started = dependencies.startTransport
+ ? await dependencies.startTransport(input, onDirectMessage, context)
+ : input.provider === "telegram"
+ ? await startTelegram(bot.id, input.token, onDirectMessage)
+ : input.provider === "imessage"
+ ? await startIMessage(input, context, onDirectMessage)
+ : await startWhatsApp(input, context, onDirectMessage);
+ return {
+ runtime: started.runtime,
+ binding: {
+ botId: bot.id,
+ ...(connectionId ? { connectionId } : {}),
+ provider: input.provider,
+ status: "connected",
+ externalIdentity: started.externalIdentity,
+ connectedAt: await dependencies.nowIso(),
+ sentMessageIds: [],
+ },
+ };
+}
+
+async function commitStartedChannel(
+ dependencies: ChannelRuntimeDependencies,
+ started: StartedChannel,
+ secret?: StoredChannelSecret,
+): Promise<number> {
+ const key = runtimeKey(started.binding.botId, started.binding.provider);
+ const previousRuntime = runtimes.get(key);
+ const name = secretName(started.binding.botId, started.binding.provider);
+ let previousSecret: Option.Option<Uint8Array> | undefined;
+ try {
+ previousSecret = await Effect.runPromise(dependencies.secretStore.get(name));
+ runtimes.set(key, started.runtime);
+ if (secret) {
+ await Effect.runPromise(
+ dependencies.secretStore.set(name, encoder.encode(JSON.stringify(secret))),
+ );
+ }
+ const sequence = await replaceBinding(dependencies, started.binding);
+ if (previousRuntime && previousRuntime !== started.runtime) {
+ await previousRuntime.shutdown().catch(() => undefined);
+ }
+ return sequence;
+ } catch (cause) {
+ if (previousRuntime) runtimes.set(key, previousRuntime);
+ else runtimes.delete(key);
+ await started.runtime.shutdown().catch(() => undefined);
+ if (previousSecret?._tag === "Some") {
+ await Effect.runPromise(dependencies.secretStore.set(name, previousSecret.value)).catch(
+ () => undefined,
+ );
+ } else if (previousSecret?._tag === "None") {
+ await Effect.runPromise(dependencies.secretStore.remove(name)).catch(() => undefined);
+ }
+ throw cause;
+ }
+}
+
+export async function connectChannel(
+ dependencies: ChannelRuntimeDependencies,
+ input: ChannelConnectInput,
+): Promise<number> {
+ return withChannelOperation(input.botId, input.provider, async () => {
+ await assertChannelIdentityAvailable(dependencies, input.botId, storedSecretFromInput(input));
+ const started = await startChannel(dependencies, input);
+ return commitStartedChannel(dependencies, started, storedSecretFromInput(input));
+ });
+}
+
+export async function saveChannelConnection(
+ dependencies: ChannelRuntimeDependencies,
+ input: ChannelConnectionSaveInput,
+): Promise<number> {
+ return withConnectionSettingsOperation(() =>
+ 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",
+ ),
+ );
+ if (attached) throw new Error("Disconnect 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);
+ const profile: ChannelConnectionProfile = {
+ id: input.connectionId,
+ name: input.name,
+ provider: input.provider,
+ adapter: input.provider === "imessage" ? "photon" : input.provider,
+ ...(input.provider === "whatsapp"
+ ? { externalIdentity: input.phoneNumberId }
+ : input.provider === "imessage"
+ ? {
+ externalIdentity:
+ input.mode === "hosted" ? input.projectId : (input.phone ?? input.serverUrl),
+ ...(input.mode === "hosted"
+ ? {
+ managementUrl: `https://app.photon.codes/dashboard/${encodeURIComponent(input.projectId)}`,
+ }
+ : {}),
+ }
+ : {}),
+ };
+ await Effect.runPromise(
+ dependencies.secretStore.set(
+ secretKey,
+ encoder.encode(JSON.stringify(storedSecretFromInput(input))),
+ ),
+ );
+ try {
+ await Effect.runPromise(
+ dependencies.settings.updateSettings({
+ channelConnections: [
+ ...settings.channelConnections.filter(
+ (connection) => connection.id !== input.connectionId,
+ ),
+ profile,
+ ],
+ }),
+ );
+ } catch (cause) {
+ if (previousSecret._tag === "Some") {
+ await Effect.runPromise(
+ dependencies.secretStore.set(secretKey, previousSecret.value),
+ ).catch(() => undefined);
+ } else {
+ await Effect.runPromise(dependencies.secretStore.remove(secretKey)).catch(
+ () => undefined,
+ );
+ }
+ throw cause;
+ }
+ return 0;
+ }),
+ );
+}
+
+export async function deleteChannelConnection(
+ dependencies: ChannelRuntimeDependencies,
+ connectionId: ChannelConnectionId,
+): Promise<number> {
+ return withConnectionSettingsOperation(() =>
+ withConnectionOperation(connectionId, async () => {
+ const model = await dependencies.readModel();
+ if (
+ model.bots.some((bot) =>
+ (bot.channelBindings ?? []).some(
+ (binding) => binding.connectionId === connectionId && binding.status !== "disconnected",
+ ),
+ )
+ ) {
+ throw new Error("Disconnect this channel before deleting it.");
+ }
+ const secretKey = connectionSecretName(connectionId);
+ const previousSecret = await Effect.runPromise(dependencies.secretStore.get(secretKey));
+ const settings = await Effect.runPromise(dependencies.settings.getSettings);
+ await Effect.runPromise(dependencies.secretStore.remove(secretKey));
+ try {
+ await Effect.runPromise(
+ dependencies.settings.updateSettings({
+ channelConnections: settings.channelConnections.filter(
+ (connection) => connection.id !== connectionId,
+ ),
+ }),
+ );
+ } catch (cause) {
+ if (previousSecret._tag === "Some") {
+ await Effect.runPromise(
+ dependencies.secretStore.set(secretKey, previousSecret.value),
+ ).catch(() => undefined);
+ }
+ throw cause;
+ }
+ return 0;
+ }),
+ );
+}
+
+export async function attachChannelConnection(
+ dependencies: ChannelRuntimeDependencies,
+ botId: BotId,
+ connectionId: ChannelConnectionId,
+ provider: ChannelProvider,
+): Promise<number> {
+ return withConnectionOperation(connectionId, () =>
+ withChannelOperation(botId, provider, async () => {
+ const model = await dependencies.readModel();
+ const inUse = model.bots.some(
+ (bot) =>
+ bot.id !== botId &&
+ bot.archivedAt === null &&
+ (bot.channelBindings ?? []).some(
+ (binding) => binding.connectionId === connectionId && binding.status !== "disconnected",
+ ),
+ );
+ if (inUse) throw new Error("This channel connection is attached to another bot.");
+ const secret = await loadConnectionSecret(dependencies, connectionId);
+ if (!secret || secret.provider !== provider)
+ throw new Error("Saved channel connection is unavailable.");
+ await assertChannelIdentityAvailable(dependencies, botId, secret);
+ const commandId = CommandId.make(await randomId(dependencies, "channel-attach"));
+ const started = await startChannel(
+ dependencies,
+ connectInputFromSecret(botId, commandId, secret),
+ connectionId,
+ );
+ return commitStartedChannel(dependencies, started);
+ }),
+ );
+}
+
+export async function disconnectChannel(
+ 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);
+ const name = secretName(botId, provider);
+ const previousSecret = await Effect.runPromise(dependencies.secretStore.get(name));
+ if (!currentBinding?.connectionId) {
+ await Effect.runPromise(dependencies.secretStore.remove(name));
+ }
+ let sequence: number;
+ try {
+ sequence = await replaceBinding(dependencies, {
+ botId,
+ provider,
+ status: "disconnected",
+ externalIdentity: null,
+ connectedAt: null,
+ sentMessageIds: [],
+ });
+ } catch (cause) {
+ if (previousSecret._tag === "Some") {
+ await Effect.runPromise(dependencies.secretStore.set(name, previousSecret.value)).catch(
+ () => undefined,
+ );
+ }
+ throw cause;
+ }
+ await stopRuntime(botId, provider);
+ return sequence;
+ });
+}
+
+export async function reconnectChannel(
+ dependencies: ChannelRuntimeDependencies,
+ botId: BotId,
+ provider: LiveProvider,
+): Promise<number> {
+ return withChannelOperation(botId, provider, async () => {
+ const model = await dependencies.readModel();
+ 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.`);
+ }
+ 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.`);
+ await assertChannelIdentityAvailable(dependencies, botId, secret);
+ const commandId = CommandId.make(await randomId(dependencies, "channel-reconnect"));
+ const input = connectInputFromSecret(botId, commandId, secret);
+ const started = await startChannel(dependencies, input, binding?.connectionId);
+ return commitStartedChannel(dependencies, started);
+ });
+}
+
+export async function restoreConnectedChannels(
+ dependencies: ChannelRuntimeDependencies,
+): Promise<
+ ReadonlyArray<{ readonly botId: BotId; readonly provider: LiveProvider; readonly cause: unknown }>
+> {
+ const model = await dependencies.readModel();
+ const candidates = model.bots.flatMap((bot) =>
+ bot.archivedAt === null
+ ? (bot.channelBindings ?? []).flatMap((binding) =>
+ binding.status === "connected" || binding.status === "needs-reconnect"
+ ? [{ botId: bot.id, provider: binding.provider }]
+ : [],
+ )
+ : [],
+ );
+ const results = await Promise.allSettled(
+ candidates.map(async (candidate) => {
+ await reconnectChannel(dependencies, candidate.botId, candidate.provider);
+ }),
+ );
+ return results.flatMap((result, index) =>
+ result.status === "rejected" ? [{ ...candidates[index]!, cause: result.reason }] : [],
+ );
+}
+
+export async function sendChannelMessage(
+ dependencies: ChannelRuntimeDependencies,
+ input: { readonly botId: BotId; readonly threadId: ThreadId; readonly messageId: MessageId },
+): Promise<number> {
+ const thread = await dependencies.readThread(input.threadId);
+ const messageIndex = thread?.messages.findIndex(
+ (message) => message.id === input.messageId && message.role === "assistant",
+ );
+ if (!thread || thread.botId !== input.botId || messageIndex === undefined || messageIndex < 0) {
+ throw new Error("Channel reply approval does not match this bot thread.");
+ }
+ const origin = thread.messages
+ .slice(0, messageIndex)
+ .toReversed()
+ .find((message) => message.role === "user")?.channelOrigin;
+ if (!origin) throw new Error("Channel reply approval does not match an inbound channel message.");
+ const approvedMessage = thread.messages[messageIndex];
+ if (!approvedMessage?.text.trim()) throw new Error("Channel reply is empty.");
+
+ return withChannelOperation(input.botId, origin.provider, async () => {
+ const model = await dependencies.readModel();
+ const bot = model.bots.find((candidate) => candidate.id === input.botId);
+ const binding = bot?.channelBindings?.find(
+ (candidate) => candidate.provider === origin.provider,
+ );
+ if (!bot || bot.archivedAt !== null || !binding)
+ throw new Error("Channel binding is unavailable.");
+ const claim = await Effect.runPromise(
+ dependencies.deliveryStore.claim({
+ messageId: input.messageId,
+ botId: input.botId,
+ threadId: input.threadId,
+ provider: origin.provider,
+ externalThreadId: origin.externalThreadId,
+ requestedAt: await dependencies.nowIso(),
+ }),
+ );
+ if (claim === "requested" && !binding.sentMessageIds.includes(input.messageId)) {
+ throw new Error("This channel reply has an unfinished delivery attempt.");
+ }
+ if (claim === "claimed") {
+ 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.`,
+ );
+ }
+ try {
+ await runtime.post(origin.externalThreadId, approvedMessage.text);
+ } catch (cause) {
+ await Effect.runPromise(dependencies.deliveryStore.releaseRequested(input.messageId));
+ throw cause;
+ }
+ try {
+ await Effect.runPromise(
+ dependencies.deliveryStore.markSent({
+ messageId: input.messageId,
+ sentAt: await dependencies.nowIso(),
+ }),
+ );
+ } catch (cause) {
+ if (!binding.sentMessageIds.includes(input.messageId)) {
+ await replaceBinding(dependencies, {
+ ...binding,
+ sentMessageIds: [...binding.sentMessageIds, input.messageId],
+ });
+ }
+ throw cause;
+ }
+ } else if (claim === "requested") {
+ await Effect.runPromise(
+ dependencies.deliveryStore.markSent({
+ messageId: input.messageId,
+ sentAt: await dependencies.nowIso(),
+ }),
+ );
+ }
+ const sequence = binding.sentMessageIds.includes(input.messageId)
+ ? model.snapshotSequence
+ : await replaceBinding(dependencies, {
+ ...binding,
+ sentMessageIds: [...binding.sentMessageIds, input.messageId],
+ });
+ return sequence;
+ });
+}
+
+export async function resolveCompletedChannelReply(
+ dependencies: ChannelRuntimeDependencies,
+ threadId: ThreadId,
+ turnId: TurnId,
+): Promise<{
+ readonly botId: BotId;
+ readonly threadId: ThreadId;
+ readonly messageId: MessageId;
+} | null> {
+ const thread = await dependencies.readThread(threadId);
+ const latestTurn = thread?.latestTurn;
+ if (
+ !thread?.botId ||
+ latestTurn?.state !== "completed" ||
+ latestTurn.turnId !== turnId ||
+ !latestTurn.requestMessageId ||
+ !latestTurn.assistantMessageId
+ ) {
+ return null;
+ }
+
+ const inboundIndex = thread.messages.findIndex(
+ (message) =>
+ message.id === latestTurn.requestMessageId &&
+ message.role === "user" &&
+ message.channelOrigin !== undefined,
+ );
+ const assistantIndex = thread.messages.findIndex(
+ (message) =>
+ message.id === latestTurn.assistantMessageId &&
+ message.role === "assistant" &&
+ message.turnId === turnId &&
+ !message.streaming &&
+ Boolean(message.text.trim()),
+ );
+ if (inboundIndex < 0 || assistantIndex <= inboundIndex) return null;
+
+ return {
+ botId: thread.botId,
+ threadId,
+ messageId: latestTurn.assistantMessageId,
+ };
+}
+
+export async function sendCompletedChannelReply(
+ dependencies: ChannelRuntimeDependencies,
+ threadId: ThreadId,
+ turnId: TurnId,
+): Promise<number | null> {
+ const target = await resolveCompletedChannelReply(dependencies, threadId, turnId);
+ return target ? sendChannelMessage(dependencies, target) : null;
+}
diff --git a/apps/server/src/orchestration/AuthenticatedCommand.test.ts b/apps/server/src/orchestration/AuthenticatedCommand.test.ts
new file mode 100644
index 000000000..a9c39ce93
--- /dev/null
+++ b/apps/server/src/orchestration/AuthenticatedCommand.test.ts
@@ -0,0 +1,171 @@
+import {
+ AuthSessionId,
+ BotId,
+ CommandId,
+ GroupId,
+ MessageId,
+ ThreadId,
+ type AuthClientSession,
+} from "@t3tools/contracts";
+import { describe, expect, it } from "vite-plus/test";
+
+import {
+ applyAuthenticatedCommandActor,
+ applyKnownGroupPerson,
+ canManageGroupPeople,
+} from "./AuthenticatedCommand.ts";
+
+const currentPersonId = AuthSessionId.make("person-current");
+const targetPersonId = AuthSessionId.make("person-target");
+
+const targetSession = {
+ sessionId: targetPersonId,
+ client: { label: "Target person" },
+} as AuthClientSession;
+
+describe("authenticated orchestration commands", () => {
+ it("replaces spoofed leave identity with the authenticated person", () => {
+ const command = applyAuthenticatedCommandActor(
+ {
+ type: "group.leave",
+ commandId: CommandId.make("command-leave"),
+ groupId: GroupId.make("group-1"),
+ personId: AuthSessionId.make("person-spoofed"),
+ },
+ { personId: currentPersonId, displayName: "Current person", canManageGroups: false },
+ );
+
+ expect(command).toMatchObject({ type: "group.leave", personId: currentPersonId });
+ });
+
+ it("stamps group creators and turn senders from the authenticated person", () => {
+ const actor = {
+ personId: currentPersonId,
+ displayName: "Current person",
+ canManageGroups: false,
+ };
+ const group = applyAuthenticatedCommandActor(
+ {
+ type: "group.create",
+ commandId: CommandId.make("command-create"),
+ groupId: GroupId.make("group-1"),
+ name: "Product",
+ bossBotId: BotId.make("bot-1"),
+ createdAt: "2026-08-31T00:00:00.000Z",
+ },
+ actor,
+ );
+ const turn = applyAuthenticatedCommandActor(
+ {
+ type: "thread.turn.start",
+ commandId: CommandId.make("command-turn"),
+ threadId: ThreadId.make("thread-1"),
+ message: {
+ messageId: MessageId.make("message-1"),
+ role: "user",
+ text: "Hello",
+ attachments: [],
+ },
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ createdAt: "2026-08-31T00:00:00.000Z",
+ },
+ actor,
+ );
+
+ expect(group).toMatchObject({ creator: { personId: currentPersonId } });
+ expect(turn).toMatchObject({
+ senderPersonId: currentPersonId,
+ senderDisplayName: "Current person",
+ senderCanManageGroups: false,
+ });
+ });
+
+ it("uses the paired session label for group assignment", () => {
+ const command = applyKnownGroupPerson(
+ {
+ type: "group.person.assign",
+ commandId: CommandId.make("command-assign"),
+ groupId: GroupId.make("group-1"),
+ person: {
+ kind: "person",
+ personId: targetPersonId,
+ displayName: "Forged name",
+ },
+ },
+ [targetSession],
+ );
+
+ expect(command).toMatchObject({
+ person: { personId: targetPersonId, displayName: "Target person" },
+ });
+ });
+
+ it("rejects an unknown group person", () => {
+ expect(
+ applyKnownGroupPerson(
+ {
+ type: "group.person.assign",
+ commandId: CommandId.make("command-unknown"),
+ groupId: GroupId.make("group-1"),
+ person: {
+ kind: "person",
+ personId: targetPersonId,
+ displayName: "Unknown",
+ },
+ },
+ [],
+ ),
+ ).toBeNull();
+ });
+
+ it("allows an administrator to unassign a revoked person", () => {
+ const command = {
+ type: "group.person.unassign" as const,
+ commandId: CommandId.make("command-unassign-revoked"),
+ groupId: GroupId.make("group-1"),
+ personId: targetPersonId,
+ };
+
+ expect(applyKnownGroupPerson(command, [])).toEqual(command);
+ });
+
+ it("requires access write to assign or unassign people", () => {
+ const assign = {
+ type: "group.person.assign" as const,
+ commandId: CommandId.make("command-assign-scope"),
+ groupId: GroupId.make("group-1"),
+ person: {
+ kind: "person" as const,
+ personId: targetPersonId,
+ displayName: "Target person",
+ },
+ };
+ const unassign = {
+ type: "group.person.unassign" as const,
+ commandId: CommandId.make("command-unassign-scope"),
+ groupId: GroupId.make("group-1"),
+ personId: targetPersonId,
+ };
+
+ expect(canManageGroupPeople(assign, ["orchestration:operate"])).toBe(false);
+ expect(canManageGroupPeople(unassign, ["orchestration:operate"])).toBe(false);
+ expect(canManageGroupPeople(assign, ["access:write"])).toBe(true);
+ expect(canManageGroupPeople(unassign, ["access:write"])).toBe(true);
+ expect(canManageGroupPeople(assign, new Set(["access:write"] as const))).toBe(true);
+ });
+
+ it("keeps leaving a group available without access write", () => {
+ expect(
+ canManageGroupPeople(
+ {
+ type: "group.leave",
+ commandId: CommandId.make("command-leave-scope"),
+ groupId: GroupId.make("group-1"),
+ personId: currentPersonId,
+ },
+ ["orchestration:operate"],
+ ),
+ ).toBe(true);
+ });
+});
diff --git a/apps/server/src/orchestration/AuthenticatedCommand.ts b/apps/server/src/orchestration/AuthenticatedCommand.ts
new file mode 100644
index 000000000..cb351cb00
--- /dev/null
+++ b/apps/server/src/orchestration/AuthenticatedCommand.ts
@@ -0,0 +1,71 @@
+import {
+ AuthAccessWriteScope,
+ type AuthClientSession,
+ type AuthEnvironmentScope,
+ type AuthSessionId,
+ type OrchestrationCommand,
+} from "@t3tools/contracts";
+
+export interface AuthenticatedCommandActor {
+ readonly personId: AuthSessionId;
+ readonly displayName: string;
+ readonly canManageGroups: boolean;
+}
+
+export function canManageGroupPeople(
+ command: OrchestrationCommand,
+ scopes: Iterable<AuthEnvironmentScope>,
+): boolean {
+ if (command.type !== "group.person.assign" && command.type !== "group.person.unassign") {
+ return true;
+ }
+ return [...scopes].includes(AuthAccessWriteScope);
+}
+
+export function applyKnownGroupPerson(
+ command: OrchestrationCommand,
+ clientSessions: ReadonlyArray<AuthClientSession>,
+): OrchestrationCommand | null {
+ if (command.type === "group.person.unassign") return command;
+ if (command.type !== "group.person.assign") return command;
+ const clientSession = clientSessions.find(
+ (candidate) => candidate.sessionId === command.person.personId,
+ );
+ if (!clientSession) return null;
+ return {
+ ...command,
+ person: {
+ kind: "person",
+ personId: clientSession.sessionId,
+ displayName: clientSession.client.label ?? "Paired person",
+ },
+ };
+}
+
+export function applyAuthenticatedCommandActor(
+ command: OrchestrationCommand,
+ actor: AuthenticatedCommandActor,
+): OrchestrationCommand {
+ switch (command.type) {
+ case "group.create":
+ return {
+ ...command,
+ creator: {
+ kind: "person",
+ personId: actor.personId,
+ displayName: actor.displayName,
+ },
+ };
+ case "group.leave":
+ return { ...command, personId: actor.personId };
+ case "thread.turn.start":
+ return {
+ ...command,
+ senderPersonId: actor.personId,
+ senderDisplayName: actor.displayName,
+ senderCanManageGroups: actor.canManageGroups,
+ };
+ default:
+ return command;
+ }
+}
diff --git a/apps/server/src/orchestration/Layers/BotPersistence.test.ts b/apps/server/src/orchestration/Layers/BotPersistence.test.ts
index aeb3bbd8a..806db488f 100644
--- a/apps/server/src/orchestration/Layers/BotPersistence.test.ts
+++ b/apps/server/src/orchestration/Layers/BotPersistence.test.ts
@@ -1,4 +1,5 @@
import {
+ AuthSessionId,
BotId,
CommandId,
GroupId,
@@ -72,14 +73,6 @@ it.layer(TestLayer)("bot persistence", (it) => {
groupId: null,
createdAt,
});
- yield* engine.dispatch({
- type: "group.create",
- commandId: CommandId.make("cmd-group-create"),
- groupId,
- name: "Product",
- bossBotId: botId,
- createdAt,
- });
yield* engine.dispatch({
type: "bot.update",
commandId: CommandId.make("cmd-bot-update"),
@@ -111,6 +104,14 @@ it.layer(TestLayer)("bot persistence", (it) => {
commandId: CommandId.make("cmd-bot-restore"),
botId,
});
+ yield* engine.dispatch({
+ type: "group.create",
+ commandId: CommandId.make("cmd-group-create"),
+ groupId,
+ name: "Product",
+ bossBotId: botId,
+ createdAt,
+ });
yield* engine.dispatch({
type: "group.rename",
commandId: CommandId.make("cmd-group-rename"),
@@ -133,7 +134,8 @@ it.layer(TestLayer)("bot persistence", (it) => {
runtimeMode: "approval-required",
usageCap: { unit: "tokens", limit: 50_000 },
voiceEnabled: true,
- groupId,
+ channelBindings: [],
+ groupId: null,
archivedAt: null,
createdAt,
updatedAt: restored.bots[0]!.updatedAt,
@@ -144,7 +146,7 @@ it.layer(TestLayer)("bot persistence", (it) => {
id: groupId,
name: "Discovery",
bossBotId: botId,
- members: [{ botId, role: "boss" }],
+ members: [{ kind: "bot", botId, role: "boss" }],
createdAt,
updatedAt: restored.groups[0]!.updatedAt,
},
@@ -296,6 +298,7 @@ it.layer(TestLayer)("bot persistence", (it) => {
const bossBotId = BotId.make("bot-routing-boss");
const specialistBotId = BotId.make("bot-routing-specialist");
const threadId = ThreadId.make("thread-group-routing");
+ const personId = AuthSessionId.make("person-routing");
const createdAt = "2026-01-04T00:00:00.000Z";
const modelSelection = {
instanceId: ProviderInstanceId.make("codex"),
@@ -334,6 +337,7 @@ it.layer(TestLayer)("bot persistence", (it) => {
name: "Routing group",
bossBotId,
specialistBotIds: [specialistBotId],
+ creator: { kind: "person", personId, displayName: "Routing person" },
createdAt,
});
yield* engine.dispatch({
@@ -363,6 +367,8 @@ it.layer(TestLayer)("bot persistence", (it) => {
},
runtimeMode: "full-access",
interactionMode: "default",
+ senderPersonId: personId,
+ senderDisplayName: "Routing person",
createdAt,
});
diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.ts
index 9beb24fc9..f43005ecc 100644
--- a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts
+++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.ts
@@ -43,6 +43,7 @@ import { OrchestrationProjectionPipeline } from "../Services/ProjectionPipeline.
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import {
OrchestrationEngineService,
+ type OrchestrationDispatchActor,
type OrchestrationEngineShape,
} from "../Services/OrchestrationEngine.ts";
const isOrchestrationCommandPreviouslyRejectedError = Schema.is(
@@ -53,6 +54,7 @@ const isOrchestrationCommandInvariantError = Schema.is(OrchestrationCommandInvar
interface CommandEnvelope {
command: OrchestrationCommand;
+ actor: OrchestrationDispatchActor | undefined;
origin: OrchestrationClientOrigin | undefined;
result: Deferred.Deferred<{ sequence: number }, OrchestrationDispatchError>;
startedAtMs: number;
@@ -83,6 +85,9 @@ function commandToAggregateRef(command: OrchestrationCommand): {
case "group.delete":
case "group.member.assign":
case "group.member.unassign":
+ case "group.person.assign":
+ case "group.person.unassign":
+ case "group.leave":
case "group.boss.set":
return {
aggregateKind: "group",
@@ -208,6 +213,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
const eventBase = yield* decideOrchestrationCommand({
command: envelope.command,
readModel: commandReadModel,
+ ...(envelope.actor !== undefined ? { actor: envelope.actor } : {}),
}).pipe(
Effect.provideService(Crypto.Crypto, crypto),
Effect.mapError((cause) =>
@@ -381,6 +387,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
const result = yield* Deferred.make<{ sequence: number }, OrchestrationDispatchError>();
yield* Queue.offer(commandQueue, {
command,
+ actor: options?.actor,
origin: options?.origin,
result,
startedAtMs: yield* Clock.currentTimeMillis,
diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
index 9826927db..cf124fdd5 100644
--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
@@ -1,5 +1,6 @@
import {
ApprovalRequestId,
+ isGroupBotMember,
type ChatAttachment,
type OrchestrationEvent,
type OrchestrationSessionStatus,
@@ -605,6 +606,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
runtimeMode: event.payload.runtimeMode,
usageCap: event.payload.usageCap,
voiceEnabled: event.payload.voiceEnabled,
+ channelBindings: event.payload.channelBindings,
groupId: event.payload.groupId,
archivedAt: null,
createdAt: event.payload.createdAt,
@@ -635,6 +637,9 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
...(event.payload.voiceEnabled !== undefined
? { voiceEnabled: event.payload.voiceEnabled }
: {}),
+ ...(event.payload.channelBindings !== undefined
+ ? { channelBindings: event.payload.channelBindings }
+ : {}),
...(event.payload.groupId !== undefined ? { groupId: event.payload.groupId } : {}),
updatedAt: event.payload.updatedAt,
});
@@ -697,10 +702,12 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
});
if (Option.isNone(existing)) return;
const members = existing.value.members.some(
- (member) => member.botId === event.payload.member.botId,
+ (member) => isGroupBotMember(member) && member.botId === event.payload.member.botId,
)
? existing.value.members.map((member) =>
- member.botId === event.payload.member.botId ? event.payload.member : member,
+ isGroupBotMember(member) && member.botId === event.payload.member.botId
+ ? event.payload.member
+ : member,
)
: [...existing.value.members, event.payload.member];
yield* projectionGroupRepository.upsert({
@@ -722,7 +729,43 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
yield* projectionGroupRepository.upsert({
...existing.value,
members: existing.value.members.filter(
- (member) => member.botId !== event.payload.botId,
+ (member) => !isGroupBotMember(member) || member.botId !== event.payload.botId,
+ ),
+ updatedAt: event.payload.updatedAt,
+ });
+ return;
+ }
+ case "group.person-assigned": {
+ const existing = yield* projectionGroupRepository.getById({
+ groupId: event.payload.groupId,
+ });
+ if (Option.isNone(existing)) return;
+ const members = existing.value.members.some(
+ (member) =>
+ member.kind === "person" && member.personId === event.payload.person.personId,
+ )
+ ? existing.value.members.map((member) =>
+ member.kind === "person" && member.personId === event.payload.person.personId
+ ? event.payload.person
+ : member,
+ )
+ : [...existing.value.members, event.payload.person];
+ yield* projectionGroupRepository.upsert({
+ ...existing.value,
+ members,
+ updatedAt: event.payload.updatedAt,
+ });
+ return;
+ }
+ case "group.person-unassigned": {
+ const existing = yield* projectionGroupRepository.getById({
+ groupId: event.payload.groupId,
+ });
+ if (Option.isNone(existing)) return;
+ yield* projectionGroupRepository.upsert({
+ ...existing.value,
+ members: existing.value.members.filter(
+ (member) => member.kind !== "person" || member.personId !== event.payload.personId,
),
updatedAt: event.payload.updatedAt,
});
@@ -734,23 +777,28 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
});
if (Option.isNone(existing)) return;
let members = existing.value.members.filter(
- (member) => member.botId !== event.payload.bossBotId,
+ (member) => !isGroupBotMember(member) || member.botId !== event.payload.bossBotId,
);
if (event.payload.previousBossBotId !== null) {
members = members.filter(
- (member) => member.botId !== event.payload.previousBossBotId,
+ (member) =>
+ !isGroupBotMember(member) || member.botId !== event.payload.previousBossBotId,
);
if (event.payload.previousBossRole === "specialist") {
members = [
...members,
- { botId: event.payload.previousBossBotId, role: "specialist" },
+ {
+ kind: "bot",
+ botId: event.payload.previousBossBotId,
+ role: "specialist",
+ },
];
}
}
yield* projectionGroupRepository.upsert({
...existing.value,
bossBotId: event.payload.bossBotId,
- members: [...members, { botId: event.payload.bossBotId, role: "boss" }],
+ members: [...members, { kind: "bot", botId: event.payload.bossBotId, role: "boss" }],
updatedAt: event.payload.updatedAt,
});
return;
@@ -888,6 +936,20 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
});
return;
+ case "thread.ownership-updated": {
+ const existingRow = yield* projectionThreadRepository.getById({
+ threadId: event.payload.threadId,
+ });
+ if (Option.isNone(existingRow)) return;
+ yield* projectionThreadRepository.upsert({
+ ...existingRow.value,
+ botId: event.payload.botId,
+ groupId: event.payload.groupId,
+ updatedAt: event.payload.updatedAt,
+ });
+ return;
+ }
+
case "thread.archived": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
@@ -1261,6 +1323,10 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
turnId: event.payload.turnId,
respondingBotId:
event.payload.respondingBotId ?? previousMessage?.respondingBotId ?? null,
+ authorPersonId: event.payload.authorPersonId ?? previousMessage?.authorPersonId ?? null,
+ authorDisplayName:
+ event.payload.authorDisplayName ?? previousMessage?.authorDisplayName ?? null,
+ channelOrigin: event.payload.channelOrigin ?? previousMessage?.channelOrigin ?? null,
role: event.payload.role,
text: nextText,
...(nextAttachments !== undefined ? { attachments: [...nextAttachments] } : {}),
diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts
index ca2164944..9d91150cc 100644
--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts
+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts
@@ -189,6 +189,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
turn_id,
role,
text,
+ author_person_id,
+ author_display_name,
is_streaming,
created_at,
updated_at
@@ -199,6 +201,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
'turn-1',
'assistant',
'hello from projection',
+ 'person-1',
+ 'Leo',
0,
'2026-02-24T00:00:04.000Z',
'2026-02-24T00:00:05.000Z'
diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
index a5ddee189..12e86146f 100644
--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
@@ -4,7 +4,9 @@ import {
BotEngine,
BotId,
BotUsageCap,
+ ChannelBinding,
ChatAttachment,
+ ChannelMessageOrigin,
CheckpointRef,
GroupMembership,
IsoDateTime,
@@ -94,6 +96,7 @@ const ProjectionBotDbRowSchema = ProjectionBot.mapFields(
engine: Schema.NullOr(Schema.fromJsonString(BotEngine)),
usageCap: Schema.NullOr(Schema.fromJsonString(BotUsageCap)),
disabledMcpServerIds: Schema.fromJsonString(Schema.Array(McpServerId)),
+ channelBindings: Schema.fromJsonString(Schema.Array(ChannelBinding)),
voiceEnabled: Schema.Number,
}),
);
@@ -386,6 +389,7 @@ function mapBotRow(row: Schema.Schema.Type<typeof ProjectionBotDbRowSchema>): Or
runtimeMode: row.runtimeMode,
usageCap: row.usageCap,
voiceEnabled: row.voiceEnabled === 1,
+ channelBindings: row.channelBindings ?? [],
groupId: row.groupId,
archivedAt: row.archivedAt,
createdAt: row.createdAt,
@@ -495,7 +499,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
bot_id AS "botId", name, title, label, description,
disabled_mcp_server_ids_json AS "disabledMcpServerIds", avatar_json AS "avatar",
engine_json AS "engine", sandbox, runtime_mode AS "runtimeMode",
- usage_cap_json AS "usageCap", voice_enabled AS "voiceEnabled", group_id AS "groupId",
+ usage_cap_json AS "usageCap", voice_enabled AS "voiceEnabled",
+ channel_bindings_json AS "channelBindings", group_id AS "groupId",
archived_at AS "archivedAt", created_at AS "createdAt", updated_at AS "updatedAt"
FROM projection_bots
ORDER BY created_at ASC, bot_id ASC
@@ -661,6 +666,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
thread_id AS "threadId",
turn_id AS "turnId",
responding_bot_id AS "respondingBotId",
+ author_person_id AS "authorPersonId",
+ author_display_name AS "authorDisplayName",
role,
text,
attachments_json AS "attachments",
@@ -1135,6 +1142,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
thread_id AS "threadId",
turn_id AS "turnId",
responding_bot_id AS "respondingBotId",
+ author_person_id AS "authorPersonId",
+ author_display_name AS "authorDisplayName",
role,
text,
attachments_json AS "attachments",
@@ -1383,6 +1392,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
thread_id AS "threadId",
turn_id AS "turnId",
responding_bot_id AS "respondingBotId",
+ author_person_id AS "authorPersonId",
+ author_display_name AS "authorDisplayName",
role,
text,
attachments_json AS "attachments",
diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
index 6d14d8d8c..b0185d7af 100644
--- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
+++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
@@ -27,6 +27,7 @@ import * as Cache from "effect/Cache";
import * as Cause from "effect/Cause";
import * as Crypto from "effect/Crypto";
import * as Duration from "effect/Duration";
+import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
@@ -55,6 +56,13 @@ import { ServerConfig } from "../../config.ts";
import { BotInboxService } from "../../bot-inbox/service.ts";
import { BotUsageLedger } from "../../usage/BotUsageLedger.ts";
import { resolveControllerBotId } from "./ProviderCommandReactor.ts";
+import * as ServerSecretStore from "../../auth/ServerSecretStore.ts";
+import * as ChannelDeliveryStore from "../../channels/ChannelDeliveryStore.ts";
+import * as ChannelRuntime from "../../channels/ChannelRuntime.ts";
+
+type AutomaticChannelReplyTarget = NonNullable<
+ Awaited<ReturnType<typeof ChannelRuntime.resolveCompletedChannelReply>>
+>;
const providerTurnKey = (threadId: ThreadId, turnId: TurnId) => `${threadId}:${turnId}`;
const providerTaskKey = (threadId: ThreadId, taskId: string) => `${threadId}:${taskId}`;
@@ -935,6 +943,46 @@ const make = Effect.gen(function* () {
const projectionTurnRepository = yield* ProjectionTurnRepository;
const botUsageLedger = yield* BotUsageLedger;
const serverSettingsService = yield* ServerSettingsService;
+ const channelSecretStore = yield* Effect.serviceOption(ServerSecretStore.ServerSecretStore);
+ const channelDeliveryStore = yield* Effect.serviceOption(
+ ChannelDeliveryStore.ChannelDeliveryStore,
+ );
+ const channelRuntimeDependencies =
+ Option.isSome(channelSecretStore) && Option.isSome(channelDeliveryStore)
+ ? {
+ engine: orchestrationEngine,
+ secretStore: channelSecretStore.value,
+ settings: serverSettingsService,
+ deliveryStore: channelDeliveryStore.value,
+ readModel: () => Effect.runPromise(projectionSnapshotQuery.getCommandReadModel()),
+ readThread: (threadId: ThreadId) =>
+ Effect.runPromise(
+ projectionSnapshotQuery
+ .getThreadDetailById(threadId)
+ .pipe(Effect.map(Option.getOrNull)),
+ ),
+ nowIso: () => Effect.runPromise(DateTime.now.pipe(Effect.map(DateTime.formatIso))),
+ randomUuid: () => Effect.runPromise(crypto.randomUUIDv4),
+ }
+ : null;
+ const automaticChannelReplyWorker = yield* makeDrainableWorker(
+ (input: AutomaticChannelReplyTarget) => {
+ if (!channelRuntimeDependencies) {
+ return Effect.void;
+ }
+ return Effect.promise(() =>
+ ChannelRuntime.sendChannelMessage(channelRuntimeDependencies, input),
+ ).pipe(
+ Effect.asVoid,
+ Effect.catchCause((cause) =>
+ Effect.logWarning("failed to send automatic channel reply", {
+ threadId: input.threadId,
+ cause: Cause.pretty(cause),
+ }),
+ ),
+ );
+ },
+ );
const serverConfig = yield* ServerConfig;
const botInbox = BotInboxService.forSecretsDir(serverConfig.secretsDir);
const providerCommandId = (event: ProviderRuntimeEvent, tag: string) =>
@@ -2205,6 +2253,23 @@ const make = Effect.gen(function* () {
),
),
).pipe(Effect.asVoid);
+
+ if (
+ event.type === "turn.completed" &&
+ event.payload.state === "completed" &&
+ shouldApplyThreadLifecycle &&
+ eventTurnId &&
+ channelRuntimeDependencies
+ ) {
+ const target = yield* Effect.promise(() =>
+ ChannelRuntime.resolveCompletedChannelReply(
+ channelRuntimeDependencies,
+ thread.id,
+ eventTurnId,
+ ),
+ );
+ if (target) yield* automaticChannelReplyWorker.enqueue(target);
+ }
});
const processDomainEvent = (_event: TurnStartRequestedDomainEvent) => Effect.void;
@@ -2248,7 +2313,7 @@ const make = Effect.gen(function* () {
return {
start,
- drain: worker.drain,
+ drain: worker.drain.pipe(Effect.andThen(automaticChannelReplyWorker.drain)),
} satisfies ProviderRuntimeIngestionShape;
});
diff --git a/apps/server/src/orchestration/Schemas.ts b/apps/server/src/orchestration/Schemas.ts
index 1f9bd3a07..6f84fce34 100644
--- a/apps/server/src/orchestration/Schemas.ts
+++ b/apps/server/src/orchestration/Schemas.ts
@@ -11,6 +11,8 @@ import {
GroupDeletedPayload as ContractsGroupDeletedPayloadSchema,
GroupMemberAssignedPayload as ContractsGroupMemberAssignedPayloadSchema,
GroupMemberUnassignedPayload as ContractsGroupMemberUnassignedPayloadSchema,
+ GroupPersonAssignedPayload as ContractsGroupPersonAssignedPayloadSchema,
+ GroupPersonUnassignedPayload as ContractsGroupPersonUnassignedPayloadSchema,
GroupBossSetPayload as ContractsGroupBossSetPayloadSchema,
McpServerCreatedPayload as ContractsMcpServerCreatedPayloadSchema,
McpServerUpdatedPayload as ContractsMcpServerUpdatedPayloadSchema,
@@ -18,6 +20,7 @@ import {
McpServerEnabledPayload as ContractsMcpServerEnabledPayloadSchema,
McpServerDisabledPayload as ContractsMcpServerDisabledPayloadSchema,
ThreadCreatedPayload as ContractsThreadCreatedPayloadSchema,
+ ThreadOwnershipUpdatedPayload as ContractsThreadOwnershipUpdatedPayloadSchema,
ThreadArchivedPayload as ContractsThreadArchivedPayloadSchema,
ThreadSettledPayload as ContractsThreadSettledPayloadSchema,
ThreadMetaUpdatedPayload as ContractsThreadMetaUpdatedPayloadSchema,
@@ -59,6 +62,8 @@ export const GroupRenamedPayload = ContractsGroupRenamedPayloadSchema;
export const GroupDeletedPayload = ContractsGroupDeletedPayloadSchema;
export const GroupMemberAssignedPayload = ContractsGroupMemberAssignedPayloadSchema;
export const GroupMemberUnassignedPayload = ContractsGroupMemberUnassignedPayloadSchema;
+export const GroupPersonAssignedPayload = ContractsGroupPersonAssignedPayloadSchema;
+export const GroupPersonUnassignedPayload = ContractsGroupPersonUnassignedPayloadSchema;
export const GroupBossSetPayload = ContractsGroupBossSetPayloadSchema;
export const McpServerCreatedPayload = ContractsMcpServerCreatedPayloadSchema;
export const McpServerUpdatedPayload = ContractsMcpServerUpdatedPayloadSchema;
@@ -67,6 +72,7 @@ export const McpServerEnabledPayload = ContractsMcpServerEnabledPayloadSchema;
export const McpServerDisabledPayload = ContractsMcpServerDisabledPayloadSchema;
export const ThreadCreatedPayload = ContractsThreadCreatedPayloadSchema;
+export const ThreadOwnershipUpdatedPayload = ContractsThreadOwnershipUpdatedPayloadSchema;
export const ThreadArchivedPayload = ContractsThreadArchivedPayloadSchema;
export const ThreadSettledPayload = ContractsThreadSettledPayloadSchema;
export const ThreadMetaUpdatedPayload = ContractsThreadMetaUpdatedPayloadSchema;
diff --git a/apps/server/src/orchestration/Services/OrchestrationEngine.ts b/apps/server/src/orchestration/Services/OrchestrationEngine.ts
index 5f7cb34f6..8515f77ca 100644
--- a/apps/server/src/orchestration/Services/OrchestrationEngine.ts
+++ b/apps/server/src/orchestration/Services/OrchestrationEngine.ts
@@ -11,6 +11,7 @@
* @module OrchestrationEngineService
*/
import type {
+ AuthSessionId,
OrchestrationClientOrigin,
OrchestrationCommand,
OrchestrationEvent,
@@ -22,6 +23,11 @@ import type * as Stream from "effect/Stream";
import type { OrchestrationDispatchError } from "../Errors.ts";
import type { OrchestrationEventStoreError } from "../../persistence/Errors.ts";
+export interface OrchestrationDispatchActor {
+ readonly personId: AuthSessionId;
+ readonly canManageGroups: boolean;
+}
+
/**
* OrchestrationEngineShape - Service API for orchestration command and event flow.
*/
@@ -45,8 +51,8 @@ export interface OrchestrationEngineShape {
* Dispatch a validated orchestration command.
*
* @param command - Valid orchestration command.
- * @param options - Optional client origin (surface/app version) stamped into
- * the metadata of every event the command produces.
+ * @param options - Optional client identity and origin. Trusted internal
+ * dispatches omit the actor.
* @returns Effect containing the sequence of the persisted event.
*
* Dispatch is serialized through an internal queue and deduplicated via
@@ -54,7 +60,10 @@ export interface OrchestrationEngineShape {
*/
readonly dispatch: (
command: OrchestrationCommand,
- options?: { readonly origin?: OrchestrationClientOrigin },
+ options?: {
+ readonly actor?: OrchestrationDispatchActor;
+ readonly origin?: OrchestrationClientOrigin;
+ },
) => Effect.Effect<{ sequence: number }, OrchestrationDispatchError, never>;
/**
diff --git a/apps/server/src/orchestration/commandInvariants.ts b/apps/server/src/orchestration/commandInvariants.ts
index 461ae8759..8bd9620c5 100644
--- a/apps/server/src/orchestration/commandInvariants.ts
+++ b/apps/server/src/orchestration/commandInvariants.ts
@@ -1,3 +1,4 @@
+import { isGroupBotMember } from "@t3tools/contracts";
import type {
AkeruDelegationRecord,
BotId,
@@ -18,6 +19,7 @@ import { normalizeProjectPathForComparison } from "@t3tools/shared/path";
import * as Effect from "effect/Effect";
import { OrchestrationCommandInvariantError } from "./Errors.ts";
+import type { OrchestrationDispatchActor } from "./Services/OrchestrationEngine.ts";
function invariantError(commandType: string, detail: string): OrchestrationCommandInvariantError {
return new OrchestrationCommandInvariantError({
@@ -280,6 +282,56 @@ export function requireGroup(input: {
);
}
+function requireMutationActorAuthorized(input: {
+ readonly group: OrchestrationGroup;
+ readonly command: OrchestrationCommand;
+ readonly actor: OrchestrationDispatchActor | undefined;
+}): Effect.Effect<void, OrchestrationCommandInvariantError> {
+ const actor = input.actor;
+ if (
+ actor === undefined ||
+ actor.canManageGroups ||
+ input.group.members.some(
+ (member) => member.kind === "person" && member.personId === actor.personId,
+ )
+ ) {
+ return Effect.void;
+ }
+ return Effect.fail(
+ invariantError(
+ input.command.type,
+ `Person '${actor.personId}' is not a member of group '${input.group.id}'.`,
+ ),
+ );
+}
+
+export function requireGroupThreadCreateAuthorized(input: {
+ readonly group: OrchestrationGroup;
+ readonly command: Extract<OrchestrationCommand, { readonly type: "thread.create" }>;
+ readonly actor: OrchestrationDispatchActor | undefined;
+}): Effect.Effect<void, OrchestrationCommandInvariantError> {
+ return requireMutationActorAuthorized(input);
+}
+
+export function requireGroupOwnedThreadMutationAuthorized(input: {
+ readonly readModel: OrchestrationReadModel;
+ readonly thread: OrchestrationThread;
+ readonly command: OrchestrationCommand;
+ readonly actor: OrchestrationDispatchActor | undefined;
+}): Effect.Effect<void, OrchestrationCommandInvariantError> {
+ if (input.thread.groupId == null) return Effect.void;
+ const group = findGroupById(input.readModel, input.thread.groupId);
+ if (!group) {
+ return Effect.fail(
+ invariantError(
+ input.command.type,
+ `Group '${input.thread.groupId}' does not exist for command '${input.command.type}'.`,
+ ),
+ );
+ }
+ return requireMutationActorAuthorized({ group, command: input.command, actor: input.actor });
+}
+
export function requireGroupAbsent(input: {
readonly readModel: OrchestrationReadModel;
readonly command: OrchestrationCommand;
@@ -303,7 +355,9 @@ export function requireGroupMember(input: {
}): Effect.Effect<OrchestrationBot, OrchestrationCommandInvariantError> {
return Effect.gen(function* () {
const group = yield* requireGroup(input);
- const member = group.members.find((entry) => entry.botId === input.botId);
+ const member = group.members.find(
+ (entry) => isGroupBotMember(entry) && entry.botId === input.botId,
+ );
if (!member) {
return yield* Effect.fail(
invariantError(
diff --git a/apps/server/src/orchestration/decider.groups.test.ts b/apps/server/src/orchestration/decider.groups.test.ts
index 99a1b4f06..b5670ba49 100644
--- a/apps/server/src/orchestration/decider.groups.test.ts
+++ b/apps/server/src/orchestration/decider.groups.test.ts
@@ -1,4 +1,5 @@
import {
+ AuthSessionId,
BotId,
CommandId,
EventId,
@@ -9,6 +10,7 @@ import {
ProviderInstanceId,
ThreadId,
type OrchestrationBot,
+ type OrchestrationCommand,
type OrchestrationGroup,
type OrchestrationReadModel,
type OrchestrationThread,
@@ -24,7 +26,9 @@ import { createEmptyReadModel, projectEvent } from "./projector.ts";
const NOW = "2026-08-27T12:00:00.000Z";
const BOSS_ID = BotId.make("bot-boss");
const SPECIALIST_ID = BotId.make("bot-specialist");
+const OTHER_SPECIALIST_ID = BotId.make("bot-other-specialist");
const GROUP_ID = GroupId.make("group-product");
+const PERSON_ID = AuthSessionId.make("person-member");
const decodeOrchestrationEvent = Schema.decodeUnknownEffect(OrchestrationEvent);
function makeBot(input: {
@@ -47,6 +51,7 @@ function makeBot(input: {
runtimeMode: "full-access",
usageCap: null,
voiceEnabled: false,
+ channelBindings: [],
groupId: input.groupId ?? null,
archivedAt: input.archivedAt ?? null,
createdAt: NOW,
@@ -65,8 +70,9 @@ function makeGroup(
name: "Product",
bossBotId: input.bossBotId ?? BOSS_ID,
members: input.members ?? [
- { botId: BOSS_ID, role: "boss" },
- { botId: SPECIALIST_ID, role: "specialist" },
+ { kind: "bot", botId: BOSS_ID, role: "boss" },
+ { kind: "bot", botId: SPECIALIST_ID, role: "specialist" },
+ { kind: "person", personId: PERSON_ID, displayName: "Member" },
],
createdAt: NOW,
updatedAt: NOW,
@@ -114,7 +120,10 @@ function makeReadModel(input: {
};
}
-const startTurnCommand = (respondingBotId?: BotId) => ({
+const startTurnCommand = (
+ respondingBotId?: BotId,
+ senderPersonId: AuthSessionId | null = PERSON_ID,
+) => ({
type: "thread.turn.start" as const,
commandId: CommandId.make("cmd-turn-start"),
threadId: ThreadId.make("thread-group"),
@@ -127,6 +136,9 @@ const startTurnCommand = (respondingBotId?: BotId) => ({
runtimeMode: "full-access" as const,
interactionMode: "default" as const,
...(respondingBotId !== undefined ? { respondingBotId } : {}),
+ ...(senderPersonId !== null
+ ? { senderPersonId, senderDisplayName: senderPersonId === PERSON_ID ? "Member" : "Outsider" }
+ : {}),
createdAt: NOW,
});
@@ -169,21 +181,469 @@ it.layer(NodeServices.layer)("group membership decider", (it) => {
});
const events = Array.isArray(result) ? result : [result];
- expect(events.map((event) => event.type)).toEqual([
- "group.created",
- "bot.updated",
- "bot.updated",
- ]);
+ expect(events.map((event) => event.type)).toEqual(["group.created"]);
const created = events[0];
if (created?.type !== "group.created") throw new Error("Expected group.created");
expect(created.payload.bossBotId).toBe(BOSS_ID);
expect(created.payload.members).toEqual([
- { botId: BOSS_ID, role: "boss" },
- { botId: SPECIALIST_ID, role: "specialist" },
+ { kind: "bot", botId: BOSS_ID, role: "boss" },
+ { kind: "bot", botId: SPECIALIST_ID, role: "specialist" },
]);
}),
);
+ it.effect("rejects group creation with fewer than two distinct active bots", () =>
+ Effect.gen(function* () {
+ const error = yield* decideOrchestrationCommand({
+ command: {
+ type: "group.create",
+ commandId: CommandId.make("cmd-group-create-one-bot"),
+ groupId: GROUP_ID,
+ name: "Product",
+ bossBotId: BOSS_ID,
+ specialistBotIds: [BOSS_ID],
+ createdAt: NOW,
+ },
+ readModel: makeReadModel({ bots: [makeBot({ id: BOSS_ID })] }),
+ }).pipe(Effect.flip);
+
+ if (error._tag !== "OrchestrationCommandInvariantError") {
+ throw new Error("Expected minimum group size invariant error");
+ }
+ expect(error.detail).toContain("at least two active bots");
+ }),
+ );
+
+ it.effect("adds the creator as a person member", () =>
+ Effect.gen(function* () {
+ const creator = {
+ kind: "person" as const,
+ personId: AuthSessionId.make("person-creator"),
+ displayName: "Creator",
+ };
+ const result = yield* decideOrchestrationCommand({
+ command: {
+ type: "group.create",
+ commandId: CommandId.make("cmd-group-create-with-creator"),
+ groupId: GROUP_ID,
+ name: "Product",
+ bossBotId: BOSS_ID,
+ specialistBotIds: [SPECIALIST_ID],
+ creator,
+ createdAt: NOW,
+ },
+ readModel: makeReadModel({
+ bots: [makeBot({ id: BOSS_ID }), makeBot({ id: SPECIALIST_ID })],
+ }),
+ });
+ const events = Array.isArray(result) ? result : [result];
+ const created = events.find((event) => event.type === "group.created");
+
+ if (created?.type !== "group.created") throw new Error("Expected group.created");
+ expect(created.payload.members).toContainEqual(creator);
+ }),
+ );
+
+ it.effect("assigns one bot to several groups", () =>
+ Effect.gen(function* () {
+ const otherGroupId = GroupId.make("group-other");
+ const result = yield* decideOrchestrationCommand({
+ command: {
+ type: "group.member.assign",
+ commandId: CommandId.make("cmd-multi-group-member"),
+ groupId: GROUP_ID,
+ botId: SPECIALIST_ID,
+ role: "specialist",
+ },
+ readModel: makeReadModel({
+ bots: [makeBot({ id: BOSS_ID }), makeBot({ id: SPECIALIST_ID, groupId: otherGroupId })],
+ groups: [
+ makeGroup({ members: [{ kind: "bot", botId: BOSS_ID, role: "boss" }] }),
+ {
+ ...makeGroup({
+ bossBotId: SPECIALIST_ID,
+ members: [{ kind: "bot", botId: SPECIALIST_ID, role: "boss" }],
+ }),
+ id: otherGroupId,
+ },
+ ],
+ }),
+ });
+ const events = Array.isArray(result) ? result : [result];
+
+ expect(events.map((event) => event.type)).toEqual(["group.member-assigned"]);
+ }),
+ );
+
+ it.effect("rejects archiving a current group boss", () =>
+ Effect.gen(function* () {
+ const error = yield* decideOrchestrationCommand({
+ command: {
+ type: "bot.archive",
+ commandId: CommandId.make("cmd-archive-group-boss"),
+ botId: BOSS_ID,
+ },
+ readModel: makeReadModel({
+ bots: [makeBot({ id: BOSS_ID })],
+ groups: [makeGroup()],
+ }),
+ }).pipe(Effect.flip);
+
+ if (error._tag !== "OrchestrationCommandInvariantError") {
+ throw new Error("Expected boss archive invariant error");
+ }
+ expect(error.detail).toContain("Set a new boss before archiving it");
+ }),
+ );
+
+ it.effect("rejects archiving a bot when its group would have fewer than two active bots", () =>
+ Effect.gen(function* () {
+ const error = yield* decideOrchestrationCommand({
+ command: {
+ type: "bot.archive",
+ commandId: CommandId.make("cmd-archive-group-specialist"),
+ botId: SPECIALIST_ID,
+ },
+ readModel: makeReadModel({
+ bots: [makeBot({ id: BOSS_ID }), makeBot({ id: SPECIALIST_ID })],
+ groups: [makeGroup()],
+ }),
+ }).pipe(Effect.flip);
+
+ if (error._tag !== "OrchestrationCommandInvariantError") {
+ throw new Error("Expected minimum group size invariant error");
+ }
+ expect(error.detail).toContain("at least two active bots");
+ }),
+ );
+
+ it.effect("rejects a legacy bot group move that would leave one active bot", () =>
+ Effect.gen(function* () {
+ const targetGroupId = GroupId.make("group-target");
+ const error = yield* decideOrchestrationCommand({
+ command: {
+ type: "bot.update",
+ commandId: CommandId.make("cmd-move-group-specialist"),
+ botId: SPECIALIST_ID,
+ groupId: targetGroupId,
+ },
+ readModel: makeReadModel({
+ bots: [
+ makeBot({ id: BOSS_ID, groupId: GROUP_ID }),
+ makeBot({ id: SPECIALIST_ID, groupId: GROUP_ID }),
+ makeBot({ id: OTHER_SPECIALIST_ID, groupId: targetGroupId }),
+ ],
+ groups: [
+ makeGroup(),
+ {
+ ...makeGroup({
+ bossBotId: OTHER_SPECIALIST_ID,
+ members: [{ kind: "bot", botId: OTHER_SPECIALIST_ID, role: "boss" }],
+ }),
+ id: targetGroupId,
+ },
+ ],
+ }),
+ }).pipe(Effect.flip);
+
+ if (error._tag !== "OrchestrationCommandInvariantError") {
+ throw new Error("Expected minimum group size invariant error");
+ }
+ expect(error.detail).toContain("at least two active bots");
+ }),
+ );
+
+ it.effect("clears group-owned thread ownership when deleting a group", () =>
+ Effect.gen(function* () {
+ const result = yield* decideOrchestrationCommand({
+ command: {
+ type: "group.delete",
+ commandId: CommandId.make("cmd-delete-group"),
+ groupId: GROUP_ID,
+ },
+ readModel: makeReadModel({
+ bots: [makeBot({ id: BOSS_ID }), makeBot({ id: SPECIALIST_ID })],
+ groups: [makeGroup()],
+ threads: [makeGroupThread()],
+ }),
+ });
+ const events = Array.isArray(result) ? result : [result];
+ const ownership = events.find((event) => event.type === "thread.ownership-updated");
+
+ if (ownership?.type !== "thread.ownership-updated") {
+ throw new Error("Expected thread.ownership-updated");
+ }
+ expect(ownership.payload).toMatchObject({ botId: null, groupId: null });
+ }),
+ );
+
+ it.effect("lets paired clients configure groups but not create group-owned threads", () =>
+ Effect.gen(function* () {
+ const outsiderId = AuthSessionId.make("person-outsider");
+ const actor = { personId: outsiderId, canManageGroups: false } as const;
+ const readModel = {
+ ...makeReadModel({
+ bots: [
+ makeBot({ id: BOSS_ID }),
+ makeBot({ id: SPECIALIST_ID }),
+ makeBot({ id: OTHER_SPECIALIST_ID }),
+ ],
+ groups: [
+ makeGroup({
+ members: [
+ { kind: "bot", botId: BOSS_ID, role: "boss" },
+ { kind: "bot", botId: SPECIALIST_ID, role: "specialist" },
+ { kind: "bot", botId: OTHER_SPECIALIST_ID, role: "specialist" },
+ { kind: "person", personId: PERSON_ID, displayName: "Member" },
+ ],
+ }),
+ ],
+ }),
+ projects: [
+ {
+ id: ProjectId.make("project-1"),
+ title: "Project",
+ workspaceRoot: "/tmp/project",
+ defaultModelSelection: null,
+ scripts: [],
+ createdAt: NOW,
+ updatedAt: NOW,
+ deletedAt: null,
+ },
+ ],
+ };
+ const results = yield* Effect.all([
+ Effect.result(
+ decideOrchestrationCommand({
+ command: {
+ type: "group.rename",
+ commandId: CommandId.make("cmd-outsider-rename"),
+ groupId: GROUP_ID,
+ name: "Renamed",
+ },
+ readModel,
+ actor,
+ }),
+ ),
+ Effect.result(
+ decideOrchestrationCommand({
+ command: {
+ type: "group.delete",
+ commandId: CommandId.make("cmd-outsider-delete"),
+ groupId: GROUP_ID,
+ },
+ readModel,
+ actor,
+ }),
+ ),
+ Effect.result(
+ decideOrchestrationCommand({
+ command: {
+ type: "group.member.assign",
+ commandId: CommandId.make("cmd-outsider-assign"),
+ groupId: GROUP_ID,
+ botId: SPECIALIST_ID,
+ role: "specialist",
+ },
+ readModel,
+ actor,
+ }),
+ ),
+ Effect.result(
+ decideOrchestrationCommand({
+ command: {
+ type: "group.member.unassign",
+ commandId: CommandId.make("cmd-outsider-unassign"),
+ groupId: GROUP_ID,
+ botId: SPECIALIST_ID,
+ },
+ readModel,
+ actor,
+ }),
+ ),
+ Effect.result(
+ decideOrchestrationCommand({
+ command: {
+ type: "group.boss.set",
+ commandId: CommandId.make("cmd-outsider-boss"),
+ groupId: GROUP_ID,
+ bossBotId: SPECIALIST_ID,
+ },
+ readModel,
+ actor,
+ }),
+ ),
+ Effect.result(
+ decideOrchestrationCommand({
+ command: {
+ type: "thread.create",
+ commandId: CommandId.make("cmd-outsider-thread"),
+ threadId: ThreadId.make("thread-outsider"),
+ projectId: ProjectId.make("project-1"),
+ groupId: GROUP_ID,
+ title: "Outsider thread",
+ modelSelection: {
+ instanceId: ProviderInstanceId.make("default"),
+ model: "default-model",
+ },
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ createdAt: NOW,
+ },
+ readModel,
+ actor,
+ }),
+ ),
+ ]);
+
+ expect(results.map((result) => result._tag)).toEqual([
+ "Success",
+ "Success",
+ "Success",
+ "Success",
+ "Success",
+ "Failure",
+ ]);
+ }),
+ );
+
+ it.effect("lets an administrator mutate a group without membership", () =>
+ Effect.gen(function* () {
+ const result = yield* decideOrchestrationCommand({
+ command: {
+ type: "group.rename",
+ commandId: CommandId.make("cmd-admin-rename"),
+ groupId: GROUP_ID,
+ name: "Admin renamed",
+ },
+ readModel: makeReadModel({ groups: [makeGroup()] }),
+ actor: {
+ personId: AuthSessionId.make("person-admin"),
+ canManageGroups: true,
+ },
+ });
+
+ if (!("type" in result)) throw new Error("Expected one group.renamed event");
+ expect(result.type).toBe("group.renamed");
+ }),
+ );
+
+ it.effect("rejects group-owned thread mutations from an authenticated outsider", () =>
+ Effect.gen(function* () {
+ const actor = {
+ personId: AuthSessionId.make("person-outsider"),
+ canManageGroups: false,
+ } as const;
+ const readModel = makeReadModel({
+ groups: [makeGroup()],
+ threads: [makeGroupThread()],
+ });
+ const commands = [
+ {
+ type: "thread.delete",
+ commandId: CommandId.make("cmd-outsider-thread-delete"),
+ threadId: ThreadId.make("thread-group"),
+ },
+ {
+ type: "thread.archive",
+ commandId: CommandId.make("cmd-outsider-thread-archive"),
+ threadId: ThreadId.make("thread-group"),
+ },
+ {
+ type: "thread.unarchive",
+ commandId: CommandId.make("cmd-outsider-thread-unarchive"),
+ threadId: ThreadId.make("thread-group"),
+ },
+ {
+ type: "thread.settle",
+ commandId: CommandId.make("cmd-outsider-thread-settle"),
+ threadId: ThreadId.make("thread-group"),
+ },
+ {
+ type: "thread.meta.update",
+ commandId: CommandId.make("cmd-outsider-thread-meta"),
+ threadId: ThreadId.make("thread-group"),
+ title: "Outsider title",
+ },
+ {
+ type: "thread.session.stop",
+ commandId: CommandId.make("cmd-outsider-thread-stop"),
+ threadId: ThreadId.make("thread-group"),
+ createdAt: NOW,
+ },
+ ] satisfies ReadonlyArray<OrchestrationCommand>;
+ const errors = yield* Effect.all(
+ commands.map((command) =>
+ decideOrchestrationCommand({ command, readModel, actor }).pipe(Effect.flip),
+ ),
+ );
+
+ for (const error of errors) {
+ if (error._tag !== "OrchestrationCommandInvariantError") {
+ throw new Error("Expected group thread authorization error");
+ }
+ expect(error.detail).toContain(`Person '${actor.personId}' is not a member`);
+ }
+ }),
+ );
+
+ it.effect("lets a member mutate a group-owned thread", () =>
+ Effect.gen(function* () {
+ const result = yield* decideOrchestrationCommand({
+ command: {
+ type: "thread.meta.update",
+ commandId: CommandId.make("cmd-member-thread-meta"),
+ threadId: ThreadId.make("thread-group"),
+ title: "Member title",
+ },
+ readModel: makeReadModel({ groups: [makeGroup()], threads: [makeGroupThread()] }),
+ actor: { personId: PERSON_ID, canManageGroups: false },
+ });
+
+ if (!("type" in result)) throw new Error("Expected one thread.meta-updated event");
+ expect(result.type).toBe("thread.meta-updated");
+ }),
+ );
+
+ it.effect("lets an administrator mutate a group-owned thread without membership", () =>
+ Effect.gen(function* () {
+ const result = yield* decideOrchestrationCommand({
+ command: {
+ type: "thread.delete",
+ commandId: CommandId.make("cmd-admin-thread-delete"),
+ threadId: ThreadId.make("thread-group"),
+ },
+ readModel: makeReadModel({ groups: [makeGroup()], threads: [makeGroupThread()] }),
+ actor: {
+ personId: AuthSessionId.make("person-admin"),
+ canManageGroups: true,
+ },
+ });
+
+ if (!("type" in result)) throw new Error("Expected one thread.deleted event");
+ expect(result.type).toBe("thread.deleted");
+ }),
+ );
+
+ it.effect("keeps trusted internal group-thread mutations actorless", () =>
+ Effect.gen(function* () {
+ const result = yield* decideOrchestrationCommand({
+ command: {
+ type: "thread.session.stop",
+ commandId: CommandId.make("cmd-internal-thread-stop"),
+ threadId: ThreadId.make("thread-group"),
+ createdAt: NOW,
+ },
+ readModel: makeReadModel({ groups: [makeGroup()], threads: [makeGroupThread()] }),
+ });
+
+ if (!("type" in result)) throw new Error("Expected one thread.session-stop-requested event");
+ expect(result.type).toBe("thread.session-stop-requested");
+ }),
+ );
+
it.effect("rejects assigning an archived bot", () =>
Effect.gen(function* () {
const error = yield* decideOrchestrationCommand({
@@ -202,7 +662,7 @@ it.layer(NodeServices.layer)("group membership decider", (it) => {
archivedAt: NOW,
}),
],
- groups: [makeGroup({ members: [{ botId: BOSS_ID, role: "boss" }] })],
+ groups: [makeGroup({ members: [{ kind: "bot", botId: BOSS_ID, role: "boss" }] })],
}),
}).pipe(Effect.flip);
@@ -224,7 +684,7 @@ it.layer(NodeServices.layer)("group membership decider", (it) => {
},
readModel: makeReadModel({
bots: [makeBot({ id: BOSS_ID, groupId: GROUP_ID })],
- groups: [makeGroup({ members: [{ botId: BOSS_ID, role: "boss" }] })],
+ groups: [makeGroup({ members: [{ kind: "bot", botId: BOSS_ID, role: "boss" }] })],
}),
}).pipe(Effect.flip);
@@ -236,6 +696,51 @@ it.layer(NodeServices.layer)("group membership decider", (it) => {
}),
);
+ it.effect("rejects unassigning a bot when the group would have fewer than two active bots", () =>
+ Effect.gen(function* () {
+ const error = yield* decideOrchestrationCommand({
+ command: {
+ type: "group.member.unassign",
+ commandId: CommandId.make("cmd-member-unassign-specialist"),
+ groupId: GROUP_ID,
+ botId: SPECIALIST_ID,
+ },
+ readModel: makeReadModel({
+ bots: [makeBot({ id: BOSS_ID }), makeBot({ id: SPECIALIST_ID })],
+ groups: [makeGroup()],
+ }),
+ }).pipe(Effect.flip);
+
+ if (error._tag !== "OrchestrationCommandInvariantError") {
+ throw new Error("Expected minimum group size invariant error");
+ }
+ expect(error.detail).toContain("at least two active bots");
+ }),
+ );
+
+ it.effect("rejects replacing and removing the boss when one active bot would remain", () =>
+ Effect.gen(function* () {
+ const error = yield* decideOrchestrationCommand({
+ command: {
+ type: "group.boss.set",
+ commandId: CommandId.make("cmd-boss-set-one-remaining"),
+ groupId: GROUP_ID,
+ bossBotId: SPECIALIST_ID,
+ unassignPreviousBoss: true,
+ },
+ readModel: makeReadModel({
+ bots: [makeBot({ id: BOSS_ID }), makeBot({ id: SPECIALIST_ID })],
+ groups: [makeGroup()],
+ }),
+ }).pipe(Effect.flip);
+
+ if (error._tag !== "OrchestrationCommandInvariantError") {
+ throw new Error("Expected minimum group size invariant error");
+ }
+ expect(error.detail).toContain("at least two active bots");
+ }),
+ );
+
it.effect("sets a new boss and unassigns the previous boss atomically", () =>
Effect.gen(function* () {
const result = yield* decideOrchestrationCommand({
@@ -250,13 +755,22 @@ it.layer(NodeServices.layer)("group membership decider", (it) => {
bots: [
makeBot({ id: BOSS_ID, groupId: GROUP_ID }),
makeBot({ id: SPECIALIST_ID, groupId: GROUP_ID }),
+ makeBot({ id: OTHER_SPECIALIST_ID, groupId: GROUP_ID }),
+ ],
+ groups: [
+ makeGroup({
+ members: [
+ { kind: "bot", botId: BOSS_ID, role: "boss" },
+ { kind: "bot", botId: SPECIALIST_ID, role: "specialist" },
+ { kind: "bot", botId: OTHER_SPECIALIST_ID, role: "specialist" },
+ ],
+ }),
],
- groups: [makeGroup()],
}),
});
const events = Array.isArray(result) ? result : [result];
- expect(events.map((event) => event.type)).toEqual(["group.boss-set", "bot.updated"]);
+ expect(events.map((event) => event.type)).toEqual(["group.boss-set"]);
const bossSet = events[0];
if (bossSet?.type !== "group.boss-set") throw new Error("Expected group.boss-set");
expect(bossSet.payload.previousBossRole).toBe("unassigned");
@@ -351,6 +865,111 @@ it.layer(NodeServices.layer)("group membership decider", (it) => {
}),
);
+ it.effect("rejects a group turn from a person who is not a member", () =>
+ Effect.gen(function* () {
+ const outsiderId = AuthSessionId.make("person-outsider");
+ const error = yield* decideOrchestrationCommand({
+ command: {
+ ...startTurnCommand(),
+ senderPersonId: outsiderId,
+ senderDisplayName: "Outsider",
+ },
+ readModel: makeReadModel({
+ bots: [makeBot({ id: BOSS_ID }), makeBot({ id: SPECIALIST_ID })],
+ groups: [makeGroup()],
+ threads: [makeGroupThread()],
+ }),
+ }).pipe(Effect.flip);
+
+ if (error._tag !== "OrchestrationCommandInvariantError") {
+ throw new Error("Expected sender membership invariant error");
+ }
+ expect(error.detail).toContain(`Person '${outsiderId}' is not a member`);
+ }),
+ );
+
+ it.effect("lets an administrator claim a legacy bot-only group on the first turn", () =>
+ Effect.gen(function* () {
+ const result = yield* decideOrchestrationCommand({
+ command: {
+ ...startTurnCommand(),
+ senderCanManageGroups: true,
+ },
+ readModel: makeReadModel({
+ bots: [makeBot({ id: BOSS_ID }), makeBot({ id: SPECIALIST_ID })],
+ groups: [
+ makeGroup({
+ members: [
+ { kind: "bot", botId: BOSS_ID, role: "boss" },
+ { kind: "bot", botId: SPECIALIST_ID, role: "specialist" },
+ ],
+ }),
+ ],
+ threads: [makeGroupThread()],
+ }),
+ });
+ const events = Array.isArray(result) ? result : [result];
+
+ expect(events.map((event) => event.type)).toEqual([
+ "group.person-assigned",
+ "thread.message-sent",
+ "thread.turn-start-requested",
+ ]);
+ const assigned = events[0];
+ if (assigned?.type !== "group.person-assigned") {
+ throw new Error("Expected group person assignment");
+ }
+ expect(assigned.payload.person.personId).toBe(PERSON_ID);
+ expect(assigned.payload.person.displayName).toBe("Member");
+ }),
+ );
+
+ it.effect("rejects an ordinary person from a legacy bot-only group", () =>
+ Effect.gen(function* () {
+ const error = yield* decideOrchestrationCommand({
+ command: {
+ ...startTurnCommand(),
+ senderCanManageGroups: false,
+ },
+ readModel: makeReadModel({
+ bots: [makeBot({ id: BOSS_ID }), makeBot({ id: SPECIALIST_ID })],
+ groups: [
+ makeGroup({
+ members: [
+ { kind: "bot", botId: BOSS_ID, role: "boss" },
+ { kind: "bot", botId: SPECIALIST_ID, role: "specialist" },
+ ],
+ }),
+ ],
+ threads: [makeGroupThread()],
+ }),
+ }).pipe(Effect.flip);
+
+ if (error._tag !== "OrchestrationCommandInvariantError") {
+ throw new Error("Expected sender membership invariant error");
+ }
+ expect(error.detail).toContain(`Person '${PERSON_ID}' is not a member`);
+ }),
+ );
+
+ it.effect("rejects a group turn without an authenticated sender", () =>
+ Effect.gen(function* () {
+ const error = yield* decideOrchestrationCommand({
+ command: startTurnCommand(undefined, null),
+ readModel: makeReadModel({
+ bots: [makeBot({ id: BOSS_ID }), makeBot({ id: SPECIALIST_ID })],
+ groups: [makeGroup()],
+ threads: [makeGroupThread()],
+ }),
+ }).pipe(Effect.flip);
+
+ if (error._tag !== "OrchestrationCommandInvariantError") {
+ throw new Error("Expected missing sender invariant error");
+ }
+ expect(error.detail).toContain("A person member must send turns");
+ }),
+ );
+
it.effect("replays group.created events from before membership", () =>
Effect.gen(function* () {
const event = yield* decodeOrchestrationEvent({
diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts
index af2eec8fe..73968b0d7 100644
--- a/apps/server/src/orchestration/decider.ts
+++ b/apps/server/src/orchestration/decider.ts
@@ -8,6 +8,7 @@ import {
DEFAULT_RUNTIME_MODE,
EventId,
GroupId,
+ isGroupBotMember,
ProviderInstanceId,
type OrchestrationCommand,
type OrchestrationEvent,
@@ -20,6 +21,7 @@ import * as Effect from "effect/Effect";
import type * as PlatformError from "effect/PlatformError";
import { OrchestrationCommandInvariantError } from "./Errors.ts";
+import type { OrchestrationDispatchActor } from "./Services/OrchestrationEngine.ts";
import {
listThreadsByProjectId,
requireActiveGroupMember,
@@ -32,6 +34,8 @@ import {
requireDelegationAbsent,
requireGroup,
requireGroupAbsent,
+ requireGroupThreadCreateAuthorized,
+ requireGroupOwnedThreadMutationAuthorized,
requireMcpServer,
requireMcpServerAbsent,
requireProject,
@@ -236,6 +240,21 @@ function threadHasQueuedTurnStart(
);
}
+function activeGroupBotIds(
+ readModel: OrchestrationReadModel,
+ group: OrchestrationReadModel["groups"][number],
+): Set<BotId> {
+ const activeBotIds = new Set(
+ readModel.bots.filter((bot) => bot.archivedAt === null).map((bot) => bot.id),
+ );
+ return new Set(
+ group.members
+ .filter(isGroupBotMember)
+ .map((member) => member.botId)
+ .filter((botId) => activeBotIds.has(botId)),
+ );
+}
+
function botGroupUpdatedEvent(input: {
readonly botId: BotId;
readonly groupId: GroupId | null;
@@ -299,9 +318,11 @@ type DecideOrchestrationCommandResult =
export const decideCommandSequence = Effect.fn("decideCommandSequence")(function* ({
commands,
readModel,
+ actor,
}: {
readonly commands: ReadonlyArray<OrchestrationCommand>;
readonly readModel: OrchestrationReadModel;
+ readonly actor?: OrchestrationDispatchActor;
}): Effect.fn.Return<
ReadonlyArray<PlannedOrchestrationEvent>,
OrchestrationCommandInvariantError | PlatformError.PlatformError,
@@ -315,6 +336,7 @@ export const decideCommandSequence = Effect.fn("decideCommandSequence")(function
const decided = yield* decideOrchestrationCommand({
command: nextCommand,
readModel: nextReadModel,
+ ...(actor !== undefined ? { actor } : {}),
});
const nextEvents = Array.isArray(decided) ? decided : [decided];
for (const nextEvent of nextEvents) {
@@ -333,14 +355,42 @@ export const decideCommandSequence = Effect.fn("decideCommandSequence")(function
export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand")(function* ({
command,
readModel,
+ actor,
}: {
readonly command: OrchestrationCommand;
readonly readModel: OrchestrationReadModel;
+ readonly actor?: OrchestrationDispatchActor;
}): Effect.fn.Return<
DecideOrchestrationCommandResult,
OrchestrationCommandInvariantError | PlatformError.PlatformError,
Crypto.Crypto
> {
+ switch (command.type) {
+ case "thread.delete":
+ case "thread.archive":
+ case "thread.unarchive":
+ case "thread.settle":
+ case "thread.unsettle":
+ case "thread.snooze":
+ case "thread.unsnooze":
+ case "thread.pin":
+ case "thread.unpin":
+ case "thread.pin.reorder":
+ case "thread.meta.update":
+ case "thread.runtime-mode.set":
+ case "thread.interaction-mode.set":
+ case "thread.voice-transcript.append":
+ case "thread.turn.interrupt":
+ case "thread.approval.respond":
+ case "thread.user-input.respond":
+ case "thread.checkpoint.revert":
+ case "thread.session.stop": {
+ const thread = yield* requireThread({ readModel, command, threadId: command.threadId });
+ yield* requireGroupOwnedThreadMutationAuthorized({ readModel, thread, command, actor });
+ break;
+ }
+ }
+
switch (command.type) {
case "project.create": {
yield* requireProjectAbsent({
@@ -434,6 +484,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
if (activeThreads.length > 0) {
return yield* decideCommandSequence({
readModel,
+ ...(actor !== undefined ? { actor } : {}),
commands: [
...activeThreads.map(
(thread): Extract<OrchestrationCommand, { type: "thread.delete" }> => ({
@@ -498,12 +549,16 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
: DEFAULT_RUNTIME_MODE),
usageCap: command.usageCap,
voiceEnabled: command.voiceEnabled ?? false,
+ channelBindings: [],
groupId: command.groupId,
createdAt: command.createdAt,
updatedAt: command.createdAt,
},
};
- if (group === null || group.members.some((member) => member.botId === command.botId)) {
+ if (
+ group === null ||
+ group.members.some((member) => isGroupBotMember(member) && member.botId === command.botId)
+ ) {
return botCreatedEvent;
}
return [
@@ -517,7 +572,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
type: "group.member-assigned",
payload: {
groupId: group.id,
- member: { botId: command.botId, role: "specialist" },
+ member: { kind: "bot", botId: command.botId, role: "specialist" },
updatedAt: command.createdAt,
},
},
@@ -538,7 +593,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
command.groupId !== undefined && bot.groupId !== null && bot.groupId !== command.groupId
? readModel.groups.find((group) => group.id === bot.groupId)
: undefined;
- const sourceMembership = sourceGroup?.members.find((member) => member.botId === bot.id);
+ const sourceMembership = sourceGroup?.members
+ .filter(isGroupBotMember)
+ .find((member) => member.botId === bot.id);
if (sourceGroup && (sourceMembership?.role === "boss" || sourceGroup.bossBotId === bot.id)) {
return yield* Effect.fail(
new OrchestrationCommandInvariantError({
@@ -547,6 +604,18 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
}),
);
}
+ if (sourceGroup && sourceMembership) {
+ const remainingBotIds = activeGroupBotIds(readModel, sourceGroup);
+ remainingBotIds.delete(bot.id);
+ if (remainingBotIds.size < 2) {
+ return yield* Effect.fail(
+ new OrchestrationCommandInvariantError({
+ commandType: command.type,
+ detail: `Group '${sourceGroup.id}' requires at least two active bots.`,
+ }),
+ );
+ }
+ }
const occurredAt = yield* nowIso;
const events: PlannedOrchestrationEvent[] = [];
@@ -566,7 +635,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
command.groupId !== undefined &&
targetGroup !== null &&
targetGroup.id !== bot.groupId &&
- !targetGroup.members.some((member) => member.botId === bot.id)
+ !targetGroup.members.some((member) => isGroupBotMember(member) && member.botId === bot.id)
) {
events.push({
...(yield* withEventBase({
@@ -578,7 +647,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
type: "group.member-assigned",
payload: {
groupId: targetGroup.id,
- member: { botId: bot.id, role: "specialist" },
+ member: { kind: "bot", botId: bot.id, role: "specialist" },
updatedAt: occurredAt,
},
});
@@ -606,6 +675,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
...(command.runtimeMode !== undefined ? { runtimeMode: command.runtimeMode } : {}),
...(command.usageCap !== undefined ? { usageCap: command.usageCap } : {}),
...(command.voiceEnabled !== undefined ? { voiceEnabled: command.voiceEnabled } : {}),
+ ...(command.channelBindings !== undefined
+ ? { channelBindings: command.channelBindings }
+ : {}),
...(command.groupId !== undefined ? { groupId: command.groupId } : {}),
updatedAt: occurredAt,
},
@@ -615,6 +687,35 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
case "bot.archive": {
yield* requireBotNotArchived({ readModel, command, botId: command.botId });
+ const bossGroup = readModel.groups.find((group) => group.bossBotId === command.botId);
+ if (bossGroup) {
+ return yield* Effect.fail(
+ new OrchestrationCommandInvariantError({
+ commandType: command.type,
+ detail: `Bot '${command.botId}' is the boss of group '${bossGroup.id}'. Set a new boss before archiving it.`,
+ }),
+ );
+ }
+ const undersizedGroup = readModel.groups.find((group) => {
+ if (
+ !group.members.some(
+ (member) => isGroupBotMember(member) && member.botId === command.botId,
+ )
+ ) {
+ return false;
+ }
+ const remainingBotIds = activeGroupBotIds(readModel, group);
+ remainingBotIds.delete(command.botId);
+ return remainingBotIds.size < 2;
+ });
+ if (undersizedGroup) {
+ return yield* Effect.fail(
+ new OrchestrationCommandInvariantError({
+ commandType: command.type,
+ detail: `Group '${undersizedGroup.id}' requires at least two active bots.`,
+ }),
+ );
+ }
const occurredAt = yield* nowIso;
return {
...(yield* withEventBase({
@@ -665,15 +766,14 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
command.bossBotId,
...new Set((command.specialistBotIds ?? []).filter((botId) => botId !== command.bossBotId)),
];
- const memberBots = yield* Effect.forEach(memberBotIds, (botId) =>
+ yield* Effect.forEach(memberBotIds, (botId) =>
requireBotNotArchived({ readModel, command, botId }),
);
- const assignedBot = memberBots.find((bot) => bot.groupId !== null);
- if (assignedBot) {
+ if (memberBotIds.length < 2) {
return yield* Effect.fail(
new OrchestrationCommandInvariantError({
commandType: command.type,
- detail: `Bot '${assignedBot.id}' already belongs to group '${assignedBot.groupId}'.`,
+ detail: `Group '${command.groupId}' requires at least two active bots.`,
}),
);
}
@@ -690,27 +790,23 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
groupId: command.groupId,
name: command.name,
bossBotId: command.bossBotId,
- members: memberBotIds.map((botId) => ({
- botId,
- role: botId === command.bossBotId ? ("boss" as const) : ("specialist" as const),
- })),
+ members: [
+ ...memberBotIds.map((botId) => ({
+ kind: "bot" as const,
+ botId,
+ role: botId === command.bossBotId ? ("boss" as const) : ("specialist" as const),
+ })),
+ ...(command.creator === undefined ? [] : [command.creator]),
+ ],
createdAt: command.createdAt,
updatedAt: command.createdAt,
},
};
- const botUpdatedEvents = yield* Effect.forEach(memberBotIds, (botId) =>
- botGroupUpdatedEvent({
- botId,
- groupId: command.groupId,
- occurredAt: command.createdAt,
- commandId: command.commandId,
- }),
- );
- return [groupCreatedEvent, ...botUpdatedEvents];
+ return groupCreatedEvent;
}
case "group.rename": {
- yield* requireGroup({ readModel, command, groupId: command.groupId });
+ const group = yield* requireGroup({ readModel, command, groupId: command.groupId });
const occurredAt = yield* nowIso;
return {
...(yield* withEventBase({
@@ -745,10 +841,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
},
};
const botUpdatedEvents = yield* Effect.forEach(
- group.members.filter(
- (member) =>
- readModel.bots.find((bot) => bot.id === member.botId)?.groupId === command.groupId,
- ),
+ group.members
+ .filter(isGroupBotMember)
+ .filter(
+ (member) =>
+ readModel.bots.find((bot) => bot.id === member.botId)?.groupId === command.groupId,
+ ),
(member) =>
botGroupUpdatedEvent({
botId: member.botId,
@@ -757,20 +855,32 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
commandId: command.commandId,
}),
);
- return [deletedEvent, ...botUpdatedEvents];
+ const threadUpdatedEvents = yield* Effect.forEach(
+ readModel.threads.filter((thread) => thread.groupId === command.groupId),
+ Effect.fn(function* (thread) {
+ return {
+ ...(yield* withEventBase({
+ aggregateKind: "thread",
+ aggregateId: thread.id,
+ occurredAt,
+ commandId: command.commandId,
+ })),
+ type: "thread.ownership-updated" as const,
+ payload: {
+ threadId: thread.id,
+ botId: null,
+ groupId: null,
+ updatedAt: occurredAt,
+ },
+ };
+ }),
+ );
+ return [...botUpdatedEvents, ...threadUpdatedEvents, deletedEvent];
}
case "group.member.assign": {
const group = yield* requireGroup({ readModel, command, groupId: command.groupId });
const bot = yield* requireBotNotArchived({ readModel, command, botId: command.botId });
- if (bot.groupId !== null && bot.groupId !== command.groupId) {
- return yield* Effect.fail(
- new OrchestrationCommandInvariantError({
- commandType: command.type,
- detail: `Bot '${bot.id}' already belongs to group '${bot.groupId}'.`,
- }),
- );
- }
if (command.role === "boss" && group.bossBotId !== null && group.bossBotId !== bot.id) {
return yield* Effect.fail(
new OrchestrationCommandInvariantError({
@@ -798,25 +908,18 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
type: "group.member-assigned",
payload: {
groupId: group.id,
- member: { botId: bot.id, role: command.role },
+ member: { kind: "bot", botId: bot.id, role: command.role },
updatedAt: occurredAt,
},
};
- if (bot.groupId === group.id) return assignedEvent;
- return [
- assignedEvent,
- yield* botGroupUpdatedEvent({
- botId: bot.id,
- groupId: group.id,
- occurredAt,
- commandId: command.commandId,
- }),
- ];
+ return assignedEvent;
}
case "group.member.unassign": {
const group = yield* requireGroup({ readModel, command, groupId: command.groupId });
- const member = group.members.find((entry) => entry.botId === command.botId);
+ const member = group.members
+ .filter(isGroupBotMember)
+ .find((entry) => entry.botId === command.botId);
if (!member) {
return yield* Effect.fail(
new OrchestrationCommandInvariantError({
@@ -833,6 +936,16 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
}),
);
}
+ const remainingBotIds = activeGroupBotIds(readModel, group);
+ remainingBotIds.delete(command.botId);
+ if (remainingBotIds.size < 2) {
+ return yield* Effect.fail(
+ new OrchestrationCommandInvariantError({
+ commandType: command.type,
+ detail: `Group '${group.id}' requires at least two active bots.`,
+ }),
+ );
+ }
const occurredAt = yield* nowIso;
const unassignedEvent: PlannedOrchestrationEvent = {
...(yield* withEventBase({
@@ -848,34 +961,66 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
updatedAt: occurredAt,
},
};
- const bot = yield* requireBot({ readModel, command, botId: command.botId });
- if (bot.groupId !== group.id) return unassignedEvent;
- return [
- unassignedEvent,
- yield* botGroupUpdatedEvent({
- botId: bot.id,
- groupId: null,
+ return unassignedEvent;
+ }
+
+ case "group.person.assign": {
+ const group = yield* requireGroup({ readModel, command, groupId: command.groupId });
+ const occurredAt = yield* nowIso;
+ return {
+ ...(yield* withEventBase({
+ aggregateKind: "group",
+ aggregateId: group.id,
occurredAt,
commandId: command.commandId,
- }),
- ];
+ })),
+ type: "group.person-assigned",
+ payload: {
+ groupId: group.id,
+ person: command.person,
+ updatedAt: occurredAt,
+ },
+ };
}
- case "group.boss.set": {
+ case "group.person.unassign":
+ case "group.leave": {
const group = yield* requireGroup({ readModel, command, groupId: command.groupId });
- const nextBoss = yield* requireBotNotArchived({
- readModel,
- command,
- botId: command.bossBotId,
- });
- if (nextBoss.groupId !== null && nextBoss.groupId !== group.id) {
+ const person = group.members.find(
+ (member) => member.kind === "person" && member.personId === command.personId,
+ );
+ if (!person) {
return yield* Effect.fail(
new OrchestrationCommandInvariantError({
commandType: command.type,
- detail: `Bot '${nextBoss.id}' already belongs to group '${nextBoss.groupId}'.`,
+ detail: `Person '${command.personId}' is not a member of group '${group.id}'.`,
}),
);
}
+ const occurredAt = yield* nowIso;
+ return {
+ ...(yield* withEventBase({
+ aggregateKind: "group",
+ aggregateId: group.id,
+ occurredAt,
+ commandId: command.commandId,
+ })),
+ type: "group.person-unassigned",
+ payload: {
+ groupId: group.id,
+ personId: command.personId,
+ updatedAt: occurredAt,
+ },
+ };
+ }
+
+ case "group.boss.set": {
+ const group = yield* requireGroup({ readModel, command, groupId: command.groupId });
+ const nextBoss = yield* requireBotNotArchived({
+ readModel,
+ command,
+ botId: command.bossBotId,
+ });
if (group.bossBotId === nextBoss.id && command.unassignPreviousBoss === true) {
return yield* Effect.fail(
new OrchestrationCommandInvariantError({
@@ -884,6 +1029,19 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
}),
);
}
+ if (command.unassignPreviousBoss === true) {
+ const remainingBotIds = activeGroupBotIds(readModel, group);
+ if (group.bossBotId !== null) remainingBotIds.delete(group.bossBotId);
+ remainingBotIds.add(nextBoss.id);
+ if (remainingBotIds.size < 2) {
+ return yield* Effect.fail(
+ new OrchestrationCommandInvariantError({
+ commandType: command.type,
+ detail: `Group '${group.id}' requires at least two active bots.`,
+ }),
+ );
+ }
+ }
const occurredAt = yield* nowIso;
const previousBossBotId = group.bossBotId;
@@ -909,31 +1067,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
updatedAt: occurredAt,
},
};
- const events: PlannedOrchestrationEvent[] = [bossSetEvent];
- if (nextBoss.groupId !== group.id) {
- events.push(
- yield* botGroupUpdatedEvent({
- botId: nextBoss.id,
- groupId: group.id,
- occurredAt,
- commandId: command.commandId,
- }),
- );
- }
- if (previousBossRole === "unassigned" && previousBossBotId !== null) {
- const previousBoss = readModel.bots.find((bot) => bot.id === previousBossBotId);
- if (previousBoss?.groupId === group.id) {
- events.push(
- yield* botGroupUpdatedEvent({
- botId: previousBoss.id,
- groupId: null,
- occurredAt,
- commandId: command.commandId,
- }),
- );
- }
- }
- return events;
+ return bossSetEvent;
}
case "mcp-server.create": {
@@ -1287,7 +1421,8 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
yield* requireBotNotArchived({ readModel, command, botId: command.botId });
}
if (command.groupId != null) {
- yield* requireGroup({ readModel, command, groupId: command.groupId });
+ const group = yield* requireGroup({ readModel, command, groupId: command.groupId });
+ yield* requireGroupThreadCreateAuthorized({ group, command, actor });
}
yield* requireThreadAbsent({
readModel,
@@ -1931,6 +2066,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
respondingBotId === null
? null
: yield* requireBot({ readModel, command, botId: respondingBotId });
+ let personAssignedEvent: Omit<OrchestrationEvent, "sequence"> | null = null;
if (targetThread.groupId !== null && targetThread.groupId !== undefined) {
const group = yield* requireGroup({
readModel,
@@ -1953,6 +2089,47 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
botId: selectedBotId,
});
respondingBotId = selectedBotId;
+ const personMembers = group.members.filter((member) => member.kind === "person");
+ const senderIsMember = personMembers.some(
+ (member) => member.personId === command.senderPersonId,
+ );
+ if (command.senderPersonId === undefined) {
+ return yield* Effect.fail(
+ new OrchestrationCommandInvariantError({
+ commandType: command.type,
+ detail: `A person member must send turns to group '${group.id}'.`,
+ }),
+ );
+ }
+ if (!senderIsMember) {
+ if (personMembers.length === 0 && command.senderCanManageGroups === true) {
+ personAssignedEvent = {
+ ...(yield* withEventBase({
+ aggregateKind: "group",
+ aggregateId: group.id,
+ occurredAt: command.createdAt,
+ commandId: command.commandId,
+ })),
+ type: "group.person-assigned",
+ payload: {
+ groupId: group.id,
+ person: {
+ kind: "person",
+ personId: command.senderPersonId,
+ displayName: command.senderDisplayName ?? "Host",
+ },
+ updatedAt: command.createdAt,
+ },
+ };
+ } else {
+ return yield* Effect.fail(
+ new OrchestrationCommandInvariantError({
+ commandType: command.type,
+ detail: `Person '${command.senderPersonId}' is not a member of group '${group.id}'.`,
+ }),
+ );
+ }
+ }
} else if (command.respondingBotId !== undefined) {
return yield* Effect.fail(
new OrchestrationCommandInvariantError({
@@ -1976,7 +2153,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
role: "user",
text: command.message.text,
attachments: command.message.attachments,
+ ...(command.message.channelOrigin !== undefined
+ ? { channelOrigin: command.message.channelOrigin }
+ : {}),
turnId: null,
+ authorPersonId: command.senderPersonId ?? null,
+ authorDisplayName: command.senderDisplayName ?? null,
streaming: false,
createdAt: command.createdAt,
updatedAt: command.createdAt,
@@ -2050,7 +2232,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
},
});
}
- return [...lifecycleResetEvents, userMessageEvent, turnStartRequestedEvent];
+ return [
+ ...(personAssignedEvent === null ? [] : [personAssignedEvent]),
+ ...lifecycleResetEvents,
+ userMessageEvent,
+ turnStartRequestedEvent,
+ ];
}
case "thread.turn.interrupt": {
diff --git a/apps/server/src/orchestration/decider.voiceTranscript.test.ts b/apps/server/src/orchestration/decider.voiceTranscript.test.ts
index 0af1a4982..eb82edeeb 100644
--- a/apps/server/src/orchestration/decider.voiceTranscript.test.ts
+++ b/apps/server/src/orchestration/decider.voiceTranscript.test.ts
@@ -34,6 +34,7 @@ function makeBot(): OrchestrationBot {
runtimeMode: "full-access",
usageCap: null,
voiceEnabled: true,
+ channelBindings: [],
groupId: null,
archivedAt: null,
createdAt: NOW,
diff --git a/apps/server/src/orchestration/http.ts b/apps/server/src/orchestration/http.ts
index f7147106c..fb7ceb884 100644
--- a/apps/server/src/orchestration/http.ts
+++ b/apps/server/src/orchestration/http.ts
@@ -1,16 +1,33 @@
+import { randomUUID } from "node:crypto";
+
import {
+ AuthAccessWriteScope,
AuthOrchestrationOperateScope,
AuthOrchestrationReadScope,
EnvironmentHttpApi,
} from "@t3tools/contracts";
+import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
+import * as ChannelCommand from "../channels/ChannelCommand.ts";
+import * as ChannelDeliveryStore from "../channels/ChannelDeliveryStore.ts";
+import * as ChannelRuntime from "../channels/ChannelRuntime.ts";
+import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
+import * as ServerRuntimeStartup from "../serverRuntimeStartup.ts";
+import * as ServerSettings from "../serverSettings.ts";
import { projectThreadDetailSnapshot } from "./ActivityPayloadProjection.ts";
+import {
+ applyAuthenticatedCommandActor,
+ applyKnownGroupPerson,
+ canManageGroupPeople,
+} from "./AuthenticatedCommand.ts";
import { cleanupFailedUploadedAttachments, normalizeDispatchCommand } from "./Normalizer.ts";
+import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
import {
annotateEnvironmentRequest,
+ failEnvironmentScopeRequired,
failEnvironmentInternal,
failEnvironmentInvalidRequest,
failEnvironmentNotFound,
@@ -25,6 +42,13 @@ export const orchestrationHttpApiLayer = HttpApiBuilder.group(
Effect.fnUntraced(function* (handlers) {
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const orchestrationEngine = yield* OrchestrationEngineService;
+ const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
+ const serverSettings = yield* Effect.serviceOption(ServerSettings.ServerSettingsService);
+ const secretStore = yield* Effect.serviceOption(ServerSecretStore.ServerSecretStore);
+ const channelDeliveryStore = yield* Effect.serviceOption(
+ ChannelDeliveryStore.ChannelDeliveryStore,
+ );
+ const startup = yield* Effect.serviceOption(ServerRuntimeStartup.ServerRuntimeStartup);
return handlers
.handle(
@@ -51,13 +75,18 @@ export const orchestrationHttpApiLayer = HttpApiBuilder.group(
Effect.fn("environment.orchestration.shellSnapshot")(function* (args) {
yield* annotateEnvironmentRequest(args.endpoint.name);
yield* requireEnvironmentScope(AuthOrchestrationReadScope);
- return yield* projectionSnapshotQuery
- .getShellSnapshot()
- .pipe(
- Effect.catch((cause) =>
- failEnvironmentInternal("orchestration_snapshot_failed", cause),
- ),
- );
+ return yield* projectionSnapshotQuery.getShellSnapshot().pipe(
+ Effect.map((snapshot) => ({
+ ...snapshot,
+ bots: snapshot.bots.map((bot) => ({
+ ...bot,
+ channelBindings: ChannelRuntime.channelBindingsForRuntime(bot.channelBindings),
+ })),
+ })),
+ Effect.catch((cause) =>
+ failEnvironmentInternal("orchestration_snapshot_failed", cause),
+ ),
+ );
}),
)
.handle(
@@ -92,11 +121,92 @@ export const orchestrationHttpApiLayer = HttpApiBuilder.group(
"dispatch",
Effect.fn("environment.orchestration.dispatch")(function* (args) {
yield* annotateEnvironmentRequest(args.endpoint.name);
- yield* requireEnvironmentScope(AuthOrchestrationOperateScope);
- const normalizedCommand = yield* normalizeDispatchCommand(args.payload).pipe(
+ const principal = yield* requireEnvironmentScope(AuthOrchestrationOperateScope);
+ const command = args.payload;
+ if (ChannelCommand.isChannelCommand(command)) {
+ if (!principal.scopes.has(AuthAccessWriteScope)) {
+ yield* requireEnvironmentScope(AuthAccessWriteScope);
+ }
+ const services = Option.all({
+ secretStore,
+ serverSettings,
+ channelDeliveryStore,
+ startup,
+ });
+ if (Option.isNone(services)) {
+ return yield* failEnvironmentInternal(
+ "orchestration_dispatch_failed",
+ new Error("Channel services are unavailable."),
+ );
+ }
+ return yield* services.value.startup
+ .enqueueCommand(
+ Effect.tryPromise(() =>
+ ChannelCommand.executeChannelCommand(
+ {
+ engine: orchestrationEngine,
+ secretStore: services.value.secretStore,
+ settings: services.value.serverSettings,
+ deliveryStore: services.value.channelDeliveryStore,
+ readModel: () =>
+ Effect.runPromise(projectionSnapshotQuery.getCommandReadModel()),
+ readThread: (threadId) =>
+ Effect.runPromise(
+ projectionSnapshotQuery
+ .getThreadDetailById(threadId)
+ .pipe(Effect.map(Option.getOrNull)),
+ ),
+ nowIso: () =>
+ Effect.runPromise(DateTime.now.pipe(Effect.map(DateTime.formatIso))),
+ randomUuid: async () => randomUUID(),
+ },
+ command,
+ ),
+ ),
+ )
+ .pipe(
+ Effect.catch((cause) =>
+ failEnvironmentInternal("orchestration_dispatch_failed", cause),
+ ),
+ );
+ }
+ const decodedCommand = yield* normalizeDispatchCommand(command).pipe(
Effect.catch(() => failEnvironmentInvalidRequest("invalid_command")),
);
- return yield* orchestrationEngine.dispatch(normalizedCommand).pipe(
+ if (!canManageGroupPeople(decodedCommand, principal.scopes)) {
+ return yield* failEnvironmentScopeRequired(AuthAccessWriteScope);
+ }
+ const needsPeople =
+ decodedCommand.type === "group.create" ||
+ decodedCommand.type === "group.leave" ||
+ decodedCommand.type === "group.person.assign" ||
+ decodedCommand.type === "group.person.unassign" ||
+ decodedCommand.type === "thread.turn.start";
+ const clientSessions = needsPeople
+ ? yield* serverAuth
+ .listClientSessions(principal.sessionId)
+ .pipe(
+ Effect.catch((cause) =>
+ failEnvironmentInternal("orchestration_dispatch_failed", cause),
+ ),
+ )
+ : [];
+ const currentClient = clientSessions.find(
+ (session) => session.sessionId === principal.sessionId,
+ );
+ const actor = {
+ personId: principal.sessionId,
+ displayName:
+ currentClient?.client.label ??
+ (principal.scopes.has(AuthAccessWriteScope) ? "Host" : "Paired person"),
+ canManageGroups: principal.scopes.has(AuthAccessWriteScope),
+ };
+ const actorCommand = applyAuthenticatedCommandActor(decodedCommand, actor);
+ const normalizedCommand = applyKnownGroupPerson(actorCommand, clientSessions);
+ if (!normalizedCommand) {
+ return yield* failEnvironmentInvalidRequest("invalid_command");
+ }
+ return yield* orchestrationEngine.dispatch(normalizedCommand, { actor }).pipe(
Effect.tapError(() =>
cleanupFailedUploadedAttachments(args.payload, normalizedCommand),
),
diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts
index 834a04b90..6586683d4 100644
--- a/apps/server/src/orchestration/projector.ts
+++ b/apps/server/src/orchestration/projector.ts
@@ -28,6 +28,8 @@ import {
GroupDeletedPayload,
GroupMemberAssignedPayload,
GroupMemberUnassignedPayload,
+ GroupPersonAssignedPayload,
+ GroupPersonUnassignedPayload,
GroupRenamedPayload,
McpServerCreatedPayload,
McpServerDeletedPayload,
@@ -38,6 +40,7 @@ import {
ThreadActivityAppendedPayload,
ThreadArchivedPayload,
ThreadCreatedPayload,
+ ThreadOwnershipUpdatedPayload,
ThreadDeletedPayload,
ThreadInteractionModeSetPayload,
ThreadMessageReactionSetPayload,
@@ -357,6 +360,7 @@ export function projectEvent(
runtimeMode: payload.runtimeMode,
usageCap: payload.usageCap,
voiceEnabled: payload.voiceEnabled,
+ channelBindings: payload.channelBindings,
groupId: payload.groupId,
archivedAt: null,
createdAt: payload.createdAt,
@@ -390,6 +394,9 @@ export function projectEvent(
...(payload.runtimeMode !== undefined ? { runtimeMode: payload.runtimeMode } : {}),
...(payload.usageCap !== undefined ? { usageCap: payload.usageCap } : {}),
...(payload.voiceEnabled !== undefined ? { voiceEnabled: payload.voiceEnabled } : {}),
+ ...(payload.channelBindings !== undefined
+ ? { channelBindings: payload.channelBindings }
+ : {}),
...(payload.groupId !== undefined ? { groupId: payload.groupId } : {}),
updatedAt: payload.updatedAt,
}),
@@ -456,9 +463,13 @@ export function projectEvent(
Effect.map((payload) => {
const group = nextBase.groups.find((entry) => entry.id === payload.groupId);
if (!group) return nextBase;
- const members = group.members.some((member) => member.botId === payload.member.botId)
+ const members = group.members.some(
+ (member) => isGroupBotMember(member) && member.botId === payload.member.botId,
+ )
? group.members.map((member) =>
- member.botId === payload.member.botId ? payload.member : member,
+ isGroupBotMember(member) && member.botId === payload.member.botId
+ ? payload.member
+ : member,
)
: [...group.members, payload.member];
return {
@@ -485,7 +496,51 @@ export function projectEvent(
members:
nextBase.groups
.find((group) => group.id === payload.groupId)
- ?.members.filter((member) => member.botId !== payload.botId) ?? [],
+ ?.members.filter(
+ (member) => !isGroupBotMember(member) || member.botId !== payload.botId,
+ ) ?? [],
+ updatedAt: payload.updatedAt,
+ }),
+ })),
+ );
+
+ case "group.person-assigned":
+ return decodeForEvent(GroupPersonAssignedPayload, event.payload, event.type, "payload").pipe(
+ Effect.map((payload) => {
+ const group = nextBase.groups.find((entry) => entry.id === payload.groupId);
+ if (!group) return nextBase;
+ const members = [
+ ...group.members.filter(
+ (member) => member.kind !== "person" || member.personId !== payload.person.personId,
+ ),
+ payload.person,
+ ];
+ return {
+ ...nextBase,
+ groups: updateGroup(nextBase.groups, payload.groupId, {
+ members,
+ updatedAt: payload.updatedAt,
+ }),
+ };
+ }),
+ );
+
+ case "group.person-unassigned":
+ return decodeForEvent(
+ GroupPersonUnassignedPayload,
+ event.payload,
+ event.type,
+ "payload",
+ ).pipe(
+ Effect.map((payload) => ({
+ ...nextBase,
+ groups: updateGroup(nextBase.groups, payload.groupId, {
+ members:
+ nextBase.groups
+ .find((group) => group.id === payload.groupId)
+ ?.members.filter(
+ (member) => member.kind !== "person" || member.personId !== payload.personId,
+ ) ?? [],
updatedAt: payload.updatedAt,
}),
})),
@@ -496,14 +551,21 @@ export function projectEvent(
Effect.map((payload) => {
const group = nextBase.groups.find((entry) => entry.id === payload.groupId);
if (!group) return nextBase;
- let members = group.members.filter((member) => member.botId !== payload.bossBotId);
+ let members = group.members.filter(
+ (member) => !isGroupBotMember(member) || member.botId !== payload.bossBotId,
+ );
if (payload.previousBossBotId !== null) {
- members = members.filter((member) => member.botId !== payload.previousBossBotId);
+ members = members.filter(
+ (member) => !isGroupBotMember(member) || member.botId !== payload.previousBossBotId,
+ );
if (payload.previousBossRole === "specialist") {
- members = [...members, { botId: payload.previousBossBotId, role: "specialist" }];
+ members = [
+ ...members,
+ { kind: "bot", botId: payload.previousBossBotId, role: "specialist" },
+ ];
}
}
- members = [...members, { botId: payload.bossBotId, role: "boss" }];
+ members = [...members, { kind: "bot", botId: payload.bossBotId, role: "boss" }];
return {
...nextBase,
groups: updateGroup(nextBase.groups, payload.groupId, {
@@ -601,6 +663,23 @@ export function projectEvent(
};
});
+ case "thread.ownership-updated":
+ return decodeForEvent(
+ ThreadOwnershipUpdatedPayload,
+ event.payload,
+ event.type,
+ "payload",
+ ).pipe(
+ Effect.map((payload) => ({
+ ...nextBase,
+ threads: updateThread(nextBase.threads, payload.threadId, {
+ botId: payload.botId,
+ groupId: payload.groupId,
+ updatedAt: payload.updatedAt,
+ }),
+ })),
+ );
+
case "thread.deleted":
return decodeForEvent(ThreadDeletedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
@@ -804,6 +883,15 @@ export function projectEvent(
...(payload.respondingBotId !== undefined
? { respondingBotId: payload.respondingBotId }
: {}),
+ ...(payload.authorPersonId !== undefined
+ ? { authorPersonId: payload.authorPersonId }
+ : {}),
+ ...(payload.authorDisplayName !== undefined
+ ? { authorDisplayName: payload.authorDisplayName }
+ : {}),
+ ...(payload.channelOrigin !== undefined
+ ? { channelOrigin: payload.channelOrigin }
+ : {}),
streaming: payload.streaming,
createdAt: payload.createdAt,
updatedAt: payload.updatedAt,
diff --git a/apps/server/src/orchestration/runtimeLayer.ts b/apps/server/src/orchestration/runtimeLayer.ts
index 8d79d7be4..d2ba891bd 100644
--- a/apps/server/src/orchestration/runtimeLayer.ts
+++ b/apps/server/src/orchestration/runtimeLayer.ts
@@ -1,5 +1,6 @@
import * as Layer from "effect/Layer";
+import { ChannelDeliveryStoreLive } from "../channels/ChannelDeliveryStore.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../persistence/Layers/OrchestrationCommandReceipts.ts";
import { OrchestrationEventStoreLive } from "../persistence/Layers/OrchestrationEventStore.ts";
import { ProjectionBotRepositoryLive } from "../persistence/Layers/ProjectionBots.ts";
diff --git a/apps/server/src/persistence/Layers/ProjectionBots.ts b/apps/server/src/persistence/Layers/ProjectionBots.ts
index eb4224a92..b15df9014 100644
--- a/apps/server/src/persistence/Layers/ProjectionBots.ts
+++ b/apps/server/src/persistence/Layers/ProjectionBots.ts
@@ -1,4 +1,4 @@
-import { BotAvatar, BotEngine, BotUsageCap, McpServerId } from "@t3tools/contracts";
+import { BotAvatar, BotEngine, BotUsageCap, ChannelBinding, McpServerId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
@@ -21,6 +21,7 @@ const ProjectionBotDbRow = ProjectionBot.mapFields(
engine: Schema.NullOr(Schema.fromJsonString(BotEngine)),
usageCap: Schema.NullOr(Schema.fromJsonString(BotUsageCap)),
disabledMcpServerIds: Schema.fromJsonString(Schema.Array(McpServerId)),
+ channelBindings: Schema.fromJsonString(Schema.Array(ChannelBinding)),
voiceEnabled: Schema.Number,
}),
);
@@ -38,13 +39,15 @@ const makeProjectionBotRepository = Effect.gen(function* () {
INSERT INTO projection_bots (
bot_id, name, title, label, description, disabled_mcp_server_ids_json,
avatar_json, engine_json, sandbox, runtime_mode, usage_cap_json, voice_enabled,
+ channel_bindings_json,
group_id, archived_at, created_at, updated_at
) VALUES (
${row.botId}, ${row.name}, ${row.title}, ${row.label}, ${row.description},
${JSON.stringify(row.disabledMcpServerIds)}, ${JSON.stringify(row.avatar)},
${row.engine === null ? null : JSON.stringify(row.engine)}, ${row.sandbox},
${row.runtimeMode}, ${row.usageCap === null ? null : JSON.stringify(row.usageCap)},
- ${row.voiceEnabled ? 1 : 0}, ${row.groupId}, ${row.archivedAt}, ${row.createdAt},
+ ${row.voiceEnabled ? 1 : 0}, ${JSON.stringify(row.channelBindings ?? [])}, ${row.groupId},
+ ${row.archivedAt}, ${row.createdAt},
${row.updatedAt}
)
ON CONFLICT (bot_id) DO UPDATE SET
@@ -59,6 +62,7 @@ const makeProjectionBotRepository = Effect.gen(function* () {
runtime_mode = excluded.runtime_mode,
usage_cap_json = excluded.usage_cap_json,
voice_enabled = excluded.voice_enabled,
+ channel_bindings_json = excluded.channel_bindings_json,
group_id = excluded.group_id,
archived_at = excluded.archived_at,
created_at = excluded.created_at,
@@ -74,7 +78,8 @@ const makeProjectionBotRepository = Effect.gen(function* () {
bot_id AS "botId", name, title, label, description,
disabled_mcp_server_ids_json AS "disabledMcpServerIds", avatar_json AS "avatar",
engine_json AS "engine", sandbox, runtime_mode AS "runtimeMode",
- usage_cap_json AS "usageCap", voice_enabled AS "voiceEnabled", group_id AS "groupId",
+ usage_cap_json AS "usageCap", voice_enabled AS "voiceEnabled",
+ channel_bindings_json AS "channelBindings", group_id AS "groupId",
archived_at AS "archivedAt", created_at AS "createdAt", updated_at AS "updatedAt"
FROM projection_bots
WHERE bot_id = ${botId}
@@ -89,7 +94,8 @@ const makeProjectionBotRepository = Effect.gen(function* () {
bot_id AS "botId", name, title, label, description,
disabled_mcp_server_ids_json AS "disabledMcpServerIds", avatar_json AS "avatar",
engine_json AS "engine", sandbox, runtime_mode AS "runtimeMode",
- usage_cap_json AS "usageCap", voice_enabled AS "voiceEnabled", group_id AS "groupId",
+ usage_cap_json AS "usageCap", voice_enabled AS "voiceEnabled",
+ channel_bindings_json AS "channelBindings", group_id AS "groupId",
archived_at AS "archivedAt", created_at AS "createdAt", updated_at AS "updatedAt"
FROM projection_bots
ORDER BY created_at ASC, bot_id ASC
diff --git a/apps/server/src/persistence/Layers/ProjectionThreadMessages.test.ts b/apps/server/src/persistence/Layers/ProjectionThreadMessages.test.ts
index b1f394a9e..0dfacd72e 100644
--- a/apps/server/src/persistence/Layers/ProjectionThreadMessages.test.ts
+++ b/apps/server/src/persistence/Layers/ProjectionThreadMessages.test.ts
@@ -28,6 +28,11 @@ layer("ProjectionThreadMessageRepository", (it) => {
sizeBytes: 5,
},
];
+ const channelOrigin = {
+ provider: "telegram" as const,
+ externalThreadId: "telegram-chat-1",
+ externalSenderId: "telegram-user-7",
+ };
yield* repository.upsert({
messageId,
@@ -36,6 +41,7 @@ layer("ProjectionThreadMessageRepository", (it) => {
role: "user",
text: "initial",
attachments: persistedAttachments,
+ channelOrigin,
isStreaming: false,
createdAt,
updatedAt,
@@ -56,12 +62,14 @@ layer("ProjectionThreadMessageRepository", (it) => {
assert.equal(rows.length, 1);
assert.equal(rows[0]?.text, "updated");
assert.deepEqual(rows[0]?.attachments, persistedAttachments);
+ assert.deepEqual(rows[0]?.channelOrigin, channelOrigin);
const rowById = yield* repository.getByMessageId({ messageId });
assert.equal(rowById._tag, "Some");
if (rowById._tag === "Some") {
assert.equal(rowById.value.text, "updated");
assert.deepEqual(rowById.value.attachments, persistedAttachments);
+ assert.deepEqual(rowById.value.channelOrigin, channelOrigin);
}
}),
);
@@ -79,6 +87,7 @@ layer("ProjectionThreadMessageRepository", (it) => {
turnId: null,
role: "assistant",
text: "with attachment",
+ channelOrigin: null,
attachments: [
{
type: "image",
@@ -109,6 +118,7 @@ layer("ProjectionThreadMessageRepository", (it) => {
assert.equal(rows.length, 1);
assert.equal(rows[0]?.text, "cleared");
assert.deepEqual(rows[0]?.attachments, []);
+ assert.equal(rows[0]?.channelOrigin, null);
}),
);
});
diff --git a/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts b/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts
index a8c9e2db2..e77374c34 100644
--- a/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts
+++ b/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts
@@ -33,6 +33,9 @@ function toProjectionThreadMessage(
threadId: row.threadId,
turnId: row.turnId,
respondingBotId: row.respondingBotId ?? null,
+ authorPersonId: row.authorPersonId ?? null,
+ authorDisplayName: row.authorDisplayName ?? null,
+ channelOrigin: row.channelOrigin,
role: row.role,
text: row.text,
isStreaming: row.isStreaming === 1,
@@ -58,6 +61,9 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
thread_id,
turn_id,
responding_bot_id,
+ author_person_id,
+ author_display_name,
+ channel_origin_json,
role,
text,
attachments_json,
@@ -71,6 +77,9 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
${row.threadId},
${row.turnId},
${row.respondingBotId ?? null},
+ ${row.authorPersonId ?? null},
+ ${row.authorDisplayName ?? null},
+ ${row.channelOrigin == null ? null : JSON.stringify(row.channelOrigin)},
${row.role},
${row.text},
COALESCE(
@@ -91,6 +100,12 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
thread_id = excluded.thread_id,
turn_id = excluded.turn_id,
responding_bot_id = excluded.responding_bot_id,
+ author_person_id = excluded.author_person_id,
+ author_display_name = excluded.author_display_name,
+ channel_origin_json = COALESCE(
+ excluded.channel_origin_json,
+ projection_thread_messages.channel_origin_json
+ ),
role = excluded.role,
text = excluded.text,
attachments_json = COALESCE(
@@ -115,6 +130,9 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
thread_id AS "threadId",
turn_id AS "turnId",
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",
@@ -138,6 +156,9 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
thread_id AS "threadId",
turn_id AS "turnId",
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",
diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts
index 16ff578b7..f4172ccbb 100644
--- a/apps/server/src/persistence/Migrations.ts
+++ b/apps/server/src/persistence/Migrations.ts
@@ -73,6 +73,7 @@ import Migration0057 from "./Migrations/057_AkeruMemoryCandidateUpdates.ts";
import Migration0058 from "./Migrations/058_ProjectionDelegations.ts";
import Migration0059 from "./Migrations/059_ProjectionThreadSessionMcpServers.ts";
import Migration0060 from "./Migrations/060_ProjectionMessageReactions.ts";
+import Migration0061 from "./Migrations/061_ExternalChannels.ts";
/**
* Migration loader with all migrations defined inline.
@@ -145,6 +146,7 @@ export const migrationEntries = [
[58, "ProjectionDelegations", Migration0058],
[59, "ProjectionThreadSessionMcpServers", Migration0059],
[60, "ProjectionMessageReactions", Migration0060],
+ [61, "ExternalChannels", Migration0061],
] as const;
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
diff --git a/apps/server/src/persistence/Migrations/061_ExternalChannels.ts b/apps/server/src/persistence/Migrations/061_ExternalChannels.ts
new file mode 100644
index 000000000..e7b8fdd3f
--- /dev/null
+++ b/apps/server/src/persistence/Migrations/061_ExternalChannels.ts
@@ -0,0 +1,43 @@
+import * as Effect from "effect/Effect";
+import * as SqlClient from "effect/unstable/sql/SqlClient";
+
+export default Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ const botColumns = yield* sql<{ readonly name: string }>`PRAGMA table_info(projection_bots)`;
+ if (!botColumns.some((column) => column.name === "channel_bindings_json")) {
+ yield* sql`
+ ALTER TABLE projection_bots
+ ADD COLUMN channel_bindings_json TEXT NOT NULL DEFAULT '[]'
+ `;
+ }
+
+ const messageColumns = yield* sql<{ readonly name: string }>`
+ PRAGMA table_info(projection_thread_messages)
+ `;
+ if (!messageColumns.some((column) => column.name === "author_person_id")) {
+ yield* sql`ALTER TABLE projection_thread_messages ADD COLUMN author_person_id TEXT`;
+ }
+ if (!messageColumns.some((column) => column.name === "author_display_name")) {
+ yield* sql`ALTER TABLE projection_thread_messages ADD COLUMN author_display_name TEXT`;
+ }
+ if (!messageColumns.some((column) => column.name === "channel_origin_json")) {
+ yield* sql`ALTER TABLE projection_thread_messages ADD COLUMN channel_origin_json TEXT`;
+ }
+
+ yield* sql`
+ CREATE TABLE IF NOT EXISTS 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')),
+ 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`
+ CREATE INDEX IF NOT EXISTS idx_channel_deliveries_bot_provider
+ ON channel_deliveries (bot_id, provider, status)
+ `;
+});
diff --git a/apps/server/src/persistence/Services/ProjectionBots.ts b/apps/server/src/persistence/Services/ProjectionBots.ts
index 10d89fa8a..ecfa238a2 100644
--- a/apps/server/src/persistence/Services/ProjectionBots.ts
+++ b/apps/server/src/persistence/Services/ProjectionBots.ts
@@ -4,6 +4,7 @@ import {
BotId,
PersistedBotSandbox,
BotUsageCap,
+ ChannelBinding,
GroupId,
IsoDateTime,
McpServerId,
@@ -29,6 +30,7 @@ export const ProjectionBot = Schema.Struct({
runtimeMode: RuntimeMode,
usageCap: Schema.NullOr(BotUsageCap),
voiceEnabled: Schema.Boolean,
+ channelBindings: Schema.optional(Schema.Array(ChannelBinding)),
groupId: Schema.NullOr(GroupId),
archivedAt: Schema.NullOr(IsoDateTime),
createdAt: IsoDateTime,
diff --git a/apps/server/src/persistence/Services/ProjectionThreadMessages.ts b/apps/server/src/persistence/Services/ProjectionThreadMessages.ts
index 51396d708..995d2a866 100644
--- a/apps/server/src/persistence/Services/ProjectionThreadMessages.ts
+++ b/apps/server/src/persistence/Services/ProjectionThreadMessages.ts
@@ -8,7 +8,9 @@
*/
import {
BotId,
+ AuthSessionId,
ChatAttachment,
+ ChannelMessageOrigin,
MessageId,
OrchestrationMessageReaction,
OrchestrationMessageRole,
@@ -28,6 +30,9 @@ export const ProjectionThreadMessage = Schema.Struct({
threadId: ThreadId,
turnId: Schema.NullOr(TurnId),
respondingBotId: Schema.optional(Schema.NullOr(BotId)),
+ authorPersonId: Schema.optional(Schema.NullOr(AuthSessionId)),
+ authorDisplayName: Schema.optional(Schema.NullOr(Schema.String)),
+ channelOrigin: Schema.optional(Schema.NullOr(ChannelMessageOrigin)),
role: OrchestrationMessageRole,
text: Schema.String,
attachments: Schema.optional(Schema.Array(ChatAttachment)),
diff --git a/apps/server/src/portability.test.ts b/apps/server/src/portability.test.ts
index 5c73e348b..62dbff470 100644
--- a/apps/server/src/portability.test.ts
+++ b/apps/server/src/portability.test.ts
@@ -1,4 +1,5 @@
import {
+ AuthSessionId,
BotId,
DEFAULT_SERVER_SETTINGS,
EventId,
@@ -10,7 +11,6 @@ import {
ProviderInstanceId,
ThreadId,
type OrchestrationReadModel,
- type PortabilityArchive,
type PortabilityArchiveRecord,
type ServerSettings,
} from "@t3tools/contracts";
@@ -146,6 +146,7 @@ function makeSnapshot(overrides: Partial<OrchestrationReadModel> = {}): Orchestr
runtimeMode: "full-access",
usageCap: null,
voiceEnabled: true,
+ channelBindings: [],
groupId: GROUP_ID,
archivedAt: null,
createdAt: NOW,
@@ -157,7 +158,7 @@ function makeSnapshot(overrides: Partial<OrchestrationReadModel> = {}): Orchestr
id: GROUP_ID,
name: "Builders",
bossBotId: BOT_ID,
- members: [{ botId: BOT_ID, role: "boss" }],
+ members: [{ kind: "bot", botId: BOT_ID, role: "boss" }],
createdAt: NOW,
updatedAt: NOW,
},
@@ -270,9 +271,9 @@ function makeSettings(): ServerSettings {
}
function resignArchive(
- archive: PortabilityArchive,
+ archive: ReturnType<typeof createPortabilityArchive>,
records: readonly PortabilityArchiveRecord[],
-): PortabilityArchive {
+): ReturnType<typeof createPortabilityArchive> {
const signedRecords = records.map((record) => {
const { checksum: _checksum, ...core } = record;
return { ...core, checksum: portabilityChecksum(core) } as PortabilityArchiveRecord;
@@ -406,6 +407,94 @@ describe("portability archive", () => {
expect(text).toContain('"proposedPlans"');
});
+ it("omits paired people while preserving bot group membership", () => {
+ const snapshot = makeSnapshot();
+ const source = {
+ ...snapshot,
+ groups: [
+ {
+ ...snapshot.groups[0]!,
+ members: [
+ ...snapshot.groups[0]!.members,
+ {
+ kind: "person" as const,
+ personId: AuthSessionId.make("person-portable"),
+ displayName: "Paired person",
+ },
+ ],
+ },
+ ],
+ };
+ const archive = createPortabilityArchive(source, makeSettings(), NOW);
+ const group = archive.records.find((record) => record.type === "group");
+
+ expect(group?.data.members).toEqual([{ kind: "bot", botId: BOT_ID, role: "boss" }]);
+ const commandTypes = commandsForPortabilityImport(
+ archive,
+ source,
+ makeSettings(),
+ AVAILABLE_PROVIDER_IDS,
+ ).commands.map((command) => command.type);
+
+ expect(commandTypes).not.toContain("group.person.assign");
+ expect(commandTypes).not.toContain("group.person.unassign");
+ });
+
+ it("rejects paired identities in imported group records", () => {
+ const archive = createPortabilityArchive(makeSnapshot(), makeSettings(), NOW);
+ const withPerson = resignArchive(
+ archive,
+ archive.records.map((record) =>
+ record.type === "group"
+ ? ({
+ ...record,
+ data: {
+ ...record.data,
+ members: [
+ ...record.data.members,
+ {
+ kind: "person",
+ personId: AuthSessionId.make("person-imported"),
+ displayName: "Imported person",
+ },
+ ],
+ },
+ } as unknown as PortabilityArchiveRecord)
+ : record,
+ ),
+ );
+
+ expect(() => parsePortabilityArchive(serializePortabilityArchive(withPerson))).toThrow();
+ });
+
+ it("allows one bot to belong to multiple groups", () => {
+ const secondGroupId = GroupId.make("group-second");
+ const source = makeSnapshot({
+ groups: [
+ makeSnapshot().groups[0]!,
+ {
+ ...makeSnapshot().groups[0]!,
+ id: secondGroupId,
+ name: "Second group",
+ },
+ ],
+ });
+ const archive = parsePortabilityArchive(
+ serializePortabilityArchive(createPortabilityArchive(source, makeSettings(), NOW)),
+ );
+ const preview = previewPortabilityImport(
+ archive,
+ makeSnapshot(),
+ makeSettings(),
+ AVAILABLE_PROVIDER_IDS,
+ );
+
+ expect(preview.additions).toContainEqual(
+ expect.objectContaining({ recordType: "group", id: secondGroupId }),
+ );
+ expect(preview.conflicts).not.toContainEqual(expect.objectContaining({ recordType: "group" }));
+ });
+
it("omits deleted threads and projects and does not restore over them", () => {
const base = makeSnapshot();
const deletedProjectId = ProjectId.make("project-deleted");
@@ -680,31 +769,6 @@ describe("portability import", () => {
).not.toContainEqual(expect.objectContaining({ type: "thread.history.restore" }));
});
- it("conflicts a group whose member belongs to another target group", () => {
- const otherGroupId = GroupId.make("group-other");
- const snapshot = makeSnapshot({
- bots: [{ ...makeSnapshot().bots[0]!, groupId: otherGroupId }],
- groups: [
- {
- ...makeSnapshot().groups[0]!,
- id: otherGroupId,
- bossBotId: BOT_ID,
- members: [{ botId: BOT_ID, role: "boss" }],
- },
- ],
- });
- const preview = previewPortabilityImport(
- createPortabilityArchive(makeSnapshot(), makeSettings(), NOW),
- snapshot,
- makeSettings(),
- AVAILABLE_PROVIDER_IDS,
- );
-
- expect(preview.conflicts).toContainEqual(
- expect.objectContaining({ recordType: "group", id: GROUP_ID }),
- );
- });
-
it("does not overwrite newer server settings", () => {
const preview = previewPortabilityImport(
createPortabilityArchive(makeSnapshot(), makeSettings(), NOW),
@@ -1342,8 +1406,8 @@ describe("portability import", () => {
...makeSnapshot().groups[0]!,
bossBotId: secondBotId,
members: [
- { botId: secondBotId, role: "boss" },
- { botId: BOT_ID, role: "specialist" },
+ { kind: "bot", botId: secondBotId, role: "boss" },
+ { kind: "bot", botId: BOT_ID, role: "specialist" },
],
},
],
diff --git a/apps/server/src/portability.ts b/apps/server/src/portability.ts
index 64487ecc3..150d376c3 100644
--- a/apps/server/src/portability.ts
+++ b/apps/server/src/portability.ts
@@ -13,6 +13,7 @@ import {
PortabilityArchive,
ProjectId,
ThreadId,
+ isGroupBotMember,
type PortabilityArchiveRecord,
type PortabilityImportItem,
type PortabilityImportPreview,
@@ -415,7 +416,9 @@ export function portableRecords(
data: {
name: safeText(group.name),
bossBotId: group.bossBotId,
- members: [...group.members].sort((left, right) => left.botId.localeCompare(right.botId)),
+ members: group.members
+ .filter(isGroupBotMember)
+ .sort((left, right) => left.botId.localeCompare(right.botId)),
},
})),
...snapshot.projects
@@ -737,7 +740,6 @@ export function parsePortabilityArchive(contents: string) {
const groupIds = new Set(
archive.records.filter((record) => record.type === "group").map((record) => record.id),
);
- const groupByBotId = new Map<string, string>();
for (const record of archive.records) {
if (record.type === "bot") {
const missing = record.data.disabledMcpServerIds.find((id) => !mcpIds.has(id));
@@ -764,15 +766,6 @@ export function parsePortabilityArchive(contents: string) {
];
const missing = referenced.find((id) => id !== null && !botIds.has(id));
if (missing) throw new Error(`Group '${record.id}' references missing bot '${missing}'.`);
- for (const member of record.data.members) {
- const existingGroupId = groupByBotId.get(member.botId);
- if (existingGroupId && existingGroupId !== record.id) {
- throw new Error(
- `Bot '${member.botId}' belongs to both group '${existingGroupId}' and '${record.id}'.`,
- );
- }
- groupByBotId.set(member.botId, record.id);
- }
}
if (record.type === "thread") {
if (!projectIds.has(record.data.projectId)) {
@@ -1091,7 +1084,6 @@ export function previewPortabilityImport(
const deletedThreadIds = new Set<string>(
snapshot.threads.filter((thread) => thread.deletedAt !== null).map((thread) => thread.id),
);
- const currentBotGroupIds = new Map(snapshot.bots.map((bot) => [bot.id, bot.groupId]));
const enabledMcpServerIds = new Set(
(snapshot.mcpServers ?? []).filter((server) => server.enabled).map((server) => server.id),
);
@@ -1141,13 +1133,7 @@ export function previewPortabilityImport(
const hasUnavailableMember = record.data.members.some((member) =>
unavailableBotIds.has(member.botId),
);
- const hasAssignedMember = record.data.members.some((member) => {
- const groupId = currentBotGroupIds.get(member.botId);
- return groupId !== undefined && groupId !== null && groupId !== record.id;
- });
- return record.data.bossBotId === null || hasUnavailableMember || hasAssignedMember
- ? [record.id]
- : [];
+ return record.data.bossBotId === null || hasUnavailableMember ? [record.id] : [];
}),
);
for (const record of archive.records) {
@@ -1312,6 +1298,9 @@ function itemForCommand(
case "group.delete":
case "group.member.assign":
case "group.member.unassign":
+ case "group.person.assign":
+ case "group.person.unassign":
+ case "group.leave":
case "group.boss.set":
return `group:${command.groupId}`;
case "mcp-server.create":
@@ -1596,7 +1585,9 @@ export function commandsForPortabilityImport(
});
}
const desired = new Map(record.data.members.map((member) => [member.botId, member.role]));
- const predicted = new Map(existing.members.map((member) => [member.botId, member.role]));
+ const predicted = new Map(
+ existing.members.filter(isGroupBotMember).map((member) => [member.botId, member.role]),
+ );
if (record.data.bossBotId && existing.bossBotId !== record.data.bossBotId) {
const unassignPreviousBoss = existing.bossBotId !== null && !desired.has(existing.bossBotId);
commands.push({
diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts
index ebbd8aa7e..06c6f98d0 100644
--- a/apps/server/src/server.test.ts
+++ b/apps/server/src/server.test.ts
@@ -144,6 +144,7 @@ import * as GitWorkflowService from "./git/GitWorkflowService.ts";
import * as ReviewService from "./review/ReviewService.ts";
import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
+import * as ChannelDeliveryStore from "./channels/ChannelDeliveryStore.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
@@ -249,6 +250,26 @@ const makeDefaultOrchestrationReadModel = () => {
};
};
+const makeChannelTestBot = () => ({
+ id: BotId.make("bot-channel-test"),
+ name: "Channel bot",
+ title: "Agent",
+ label: null,
+ description: null,
+ disabledMcpServerIds: [],
+ avatar: { kind: "dither" as const, seed: "channel-bot" },
+ engine: null,
+ sandbox: "local" as const,
+ runtimeMode: "full-access" as const,
+ usageCap: null,
+ voiceEnabled: false,
+ channelBindings: [],
+ groupId: null,
+ archivedAt: null,
+ createdAt: "2026-01-01T00:00:00.000Z",
+ updatedAt: "2026-01-01T00:00:00.000Z",
+});
+
const makeDefaultOrchestrationThreadShell = (
overrides: Partial<OrchestrationThreadShell> = {},
): OrchestrationThreadShell => {
@@ -417,6 +438,7 @@ const buildAppUnderTest = (options?: {
browserTraceCollector?: Partial<BrowserTraceCollector.BrowserTraceCollector["Service"]>;
serverLifecycleEvents?: Partial<ServerLifecycleEvents.ServerLifecycleEvents["Service"]>;
serverRuntimeStartup?: Partial<ServerRuntimeStartup.ServerRuntimeStartup["Service"]>;
+ channelDeliveryStore?: ChannelDeliveryStore.ChannelDeliveryStoreShape | null;
serverEnvironment?: Partial<ServerEnvironment.ServerEnvironment["Service"]>;
repositoryIdentityResolver?: Partial<
RepositoryIdentityResolver.RepositoryIdentityResolver["Service"]
@@ -975,6 +997,15 @@ const buildAppUnderTest = (options?: {
),
Layer.provideMerge(makeAuthTestLayer()),
Layer.provideMerge(ServerSecretStore.layer),
+ Layer.provideMerge(
+ options?.layers?.channelDeliveryStore === null
+ ? Layer.empty
+ : Layer.succeed(
+ ChannelDeliveryStore.ChannelDeliveryStore,
+ options?.layers?.channelDeliveryStore ??
+ ChannelDeliveryStore.makeMemoryChannelDeliveryStore(),
+ ),
+ ),
Layer.provide(workspaceAndProjectServicesLayer),
Layer.provideMerge(FetchHttpClient.layer),
Layer.provide(layerConfig),
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 80755ab33..cc5f86732 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -6,6 +6,7 @@ import { FetchHttpClient, HttpRouter, HttpServer } from "effect/unstable/http";
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
+import { whatsAppWebhookRouteLayer } from "./channels/ChannelRuntime.ts";
import * as HostPowerMonitor from "./background/HostPowerMonitor.ts";
import * as ServerConfig from "./config.ts";
import {
@@ -441,6 +442,7 @@ const makeRoutesLayerWithSharedMcpRegistry = Layer.mergeAll(
Layer.provide(environmentAuthenticatedAuthLayer),
),
otlpTracesProxyRouteLayer,
+ whatsAppWebhookRouteLayer,
assetRouteLayer,
attachmentUploadRouteLayer,
staticAndDevRouteLayer,
diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts
index b7045793f..e64847d54 100644
--- a/apps/server/src/serverRuntimeStartup.ts
+++ b/apps/server/src/serverRuntimeStartup.ts
@@ -24,6 +24,9 @@ import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as ServerConfig from "./config.ts";
+import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
+import * as ChannelDeliveryStore from "./channels/ChannelDeliveryStore.ts";
+import * as ChannelRuntime from "./channels/ChannelRuntime.ts";
import * as Keybindings from "./keybindings.ts";
import * as ExternalLauncher from "./process/externalLauncher.ts";
import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
@@ -370,12 +373,22 @@ export const make = (options?: StartupOptions) =>
const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
const crypto = yield* Crypto.Crypto;
const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
+ const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;
+ const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
+ const secretStore = yield* Effect.serviceOption(ServerSecretStore.ServerSecretStore);
+ const channelDeliveryStore = yield* Effect.serviceOption(
+ ChannelDeliveryStore.ChannelDeliveryStore,
+ );
const commandGate = yield* makeCommandGate;
const httpListening = yield* Deferred.make<void>();
const reactorScope = yield* Scope.make("sequential");
- yield* Effect.addFinalizer(() => Scope.close(reactorScope, Exit.void));
+ yield* Effect.addFinalizer(() =>
+ Effect.promise(ChannelRuntime.shutdownAllChannels).pipe(
+ Effect.andThen(Scope.close(reactorScope, Exit.void)),
+ ),
+ );
const startup = Effect.gen(function* () {
yield* Effect.logDebug("startup phase: starting keybindings runtime");
@@ -414,11 +427,58 @@ export const make = (options?: StartupOptions) =>
Effect.gen(function* () {
yield* orchestrationReactor.start().pipe(Scope.provide(reactorScope));
yield* providerSessionReaper.start().pipe(Scope.provide(reactorScope));
+ yield* forkParked(
+ ChannelRuntime.stopArchivedBotChannels(orchestrationEngine.streamDomainEvents),
+ ).pipe(Scope.provide(reactorScope));
}),
);
yield* runStartupPhase("provider-sessions.reconcile", reconcileProviderSessions);
+ yield* runStartupPhase(
+ "channels.restore",
+ Option.all({ secretStore, channelDeliveryStore }).pipe(
+ Option.match({
+ onNone: () => Effect.void,
+ onSome: ({ secretStore, channelDeliveryStore }) =>
+ Effect.promise(() =>
+ ChannelRuntime.restoreConnectedChannels({
+ engine: orchestrationEngine,
+ secretStore,
+ settings: serverSettings,
+ deliveryStore: channelDeliveryStore,
+ readModel: () => Effect.runPromise(projectionSnapshotQuery.getCommandReadModel()),
+ readThread: (threadId) =>
+ Effect.runPromise(
+ projectionSnapshotQuery
+ .getThreadDetailById(threadId)
+ .pipe(Effect.map(Option.getOrNull)),
+ ),
+ nowIso: () =>
+ Effect.runPromise(DateTime.now.pipe(Effect.map(DateTime.formatIso))),
+ randomUuid: () => Effect.runPromise(crypto.randomUUIDv4),
+ }),
+ ).pipe(
+ Effect.flatMap((failures) =>
+ Effect.forEach(
+ failures,
+ (failure) =>
+ Effect.logWarning("failed to restore external channel", {
+ botId: failure.botId,
+ provider: failure.provider,
+ cause: failure.cause,
+ }),
+ { discard: true },
+ ),
+ ),
+ Effect.catchCause((cause) =>
+ Effect.logWarning("external channel startup restore failed", { cause }),
+ ),
+ ),
+ }),
+ ),
+ );
+
const welcomeBase = yield* resolveWelcomeBase;
const environment = yield* serverEnvironment.getDescriptor;
yield* Effect.logDebug("startup phase: preparing welcome payload");
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index 56b6370e0..292725343 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -16,6 +16,7 @@ import {
AkeruMemoryUserId,
type AkeruMemoryThreadAccess,
DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL,
+ AuthAccessWriteScope,
AuthAccessStreamError,
type AuthAccessStreamEvent,
type AuthEnvironmentScope,
@@ -85,6 +86,9 @@ import { syncAccessIncidents, syncConnectorIncidents } from "./bot-inbox/connect
import { HttpRouter, HttpServerRequest, HttpServerRespondable } from "effect/unstable/http";
import { RpcSerialization, RpcServer } from "effect/unstable/rpc";
+import * as ChannelCommand from "./channels/ChannelCommand.ts";
+import * as ChannelDeliveryStore from "./channels/ChannelDeliveryStore.ts";
+import * as ChannelRuntime from "./channels/ChannelRuntime.ts";
import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";
import * as ServerConfig from "./config.ts";
import * as Keybindings from "./keybindings.ts";
@@ -93,6 +97,11 @@ import {
projectActivityEvent,
projectThreadDetailSnapshot,
} from "./orchestration/ActivityPayloadProjection.ts";
+import {
+ applyAuthenticatedCommandActor,
+ applyKnownGroupPerson,
+ canManageGroupPeople,
+} from "./orchestration/AuthenticatedCommand.ts";
import {
cleanupFailedUploadedAttachments,
normalizeDispatchCommand,
@@ -136,6 +145,7 @@ import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts";
import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
+import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
import { requiredScopeForRpcMethod } from "./auth/RpcAuthorization.ts";
import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
@@ -488,6 +498,10 @@ const makeWsRpcLayer = (
// the client's request caused them.
const hasClientOrigin =
clientOrigin.surface !== undefined || clientOrigin.appVersion !== undefined;
+ const dispatchActor = {
+ personId: currentSessionId,
+ canManageGroups: currentSession.scopes.includes(AuthAccessWriteScope),
+ };
const dispatchFromClient: OrchestrationEngine.OrchestrationEngineShape["dispatch"] = (
command,
) =>
@@ -541,6 +555,10 @@ const makeWsRpcLayer = (
),
);
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
+ const secretStore = yield* ServerSecretStore.ServerSecretStore;
+ const channelDeliveryStore = yield* Effect.serviceOption(
+ ChannelDeliveryStore.ChannelDeliveryStore,
+ );
const sourceControlDiscovery = yield* SourceControlDiscovery.SourceControlDiscovery;
const automaticGitFetchInterval = serverSettings.getSettings.pipe(
Effect.map(
@@ -760,6 +778,33 @@ const makeWsRpcLayer = (
const serverCommandId = (tag: string) =>
randomUUID.pipe(Effect.map((uuid) => CommandId.make(`server:${tag}:${uuid}`)));
+ const loadEnvironmentPeople = () =>
+ serverAuth.listClientSessions(currentSessionId).pipe(
+ Effect.map((clientSessions) => {
+ const currentClient = clientSessions.find(
+ (session) => session.sessionId === currentSessionId,
+ );
+ const hostClient = clientSessions.find((session) =>
+ session.scopes.includes(AuthAccessWriteScope),
+ );
+ return {
+ current: {
+ personId: currentSessionId,
+ displayName:
+ currentClient?.client.label ??
+ (currentSession.scopes.includes(AuthAccessWriteScope) ? "Host" : "Paired person"),
+ },
+ host:
+ hostClient === undefined
+ ? undefined
+ : {
+ personId: hostClient.sessionId,
+ displayName: hostClient.client.label ?? "Host",
+ },
+ };
+ }),
+ );
+
const loadAuthAccessSnapshot = () =>
Effect.all({
pairingLinks: serverAuth.listPairingLinks(),
@@ -973,6 +1018,9 @@ const makeWsRpcLayer = (
runtimeMode: nextBot.runtimeMode,
usageCap: nextBot.usageCap,
voiceEnabled: nextBot.voiceEnabled,
+ channelBindings: ChannelRuntime.channelBindingsForRuntime(
+ nextBot.channelBindings ?? [],
+ ),
groupId: nextBot.groupId,
archivedAt: nextBot.archivedAt,
createdAt: nextBot.createdAt,
@@ -1463,7 +1511,78 @@ const makeWsRpcLayer = (
observeRpcEffect(
ORCHESTRATION_WS_METHODS.dispatchCommand,
Effect.gen(function* () {
- const normalizedCommand = yield* normalizeDispatchCommand(command);
+ if (ChannelCommand.isChannelCommand(command)) {
+ if (!currentSession.scopes.includes(AuthAccessWriteScope)) {
+ return yield* new OrchestrationDispatchCommandError({
+ message: "Only the environment host can manage external channels.",
+ });
+ }
+ if (Option.isNone(channelDeliveryStore)) {
+ return yield* new OrchestrationDispatchCommandError({
+ message: "Channel delivery storage is unavailable.",
+ });
+ }
+ return yield* startup.enqueueCommand(
+ Effect.tryPromise({
+ try: () =>
+ ChannelCommand.executeChannelCommand(
+ {
+ engine: orchestrationEngine,
+ secretStore,
+ settings: serverSettings,
+ deliveryStore: channelDeliveryStore.value,
+ readModel: () =>
+ Effect.runPromise(projectionSnapshotQuery.getCommandReadModel()),
+ readThread: (threadId) =>
+ Effect.runPromise(
+ projectionSnapshotQuery
+ .getThreadDetailById(threadId)
+ .pipe(Effect.map(Option.getOrNull)),
+ ),
+ nowIso: () => Effect.runPromise(nowIso),
+ randomUuid: () => Effect.runPromise(crypto.randomUUIDv4),
+ },
+ command,
+ ),
+ catch: (cause) =>
+ new OrchestrationDispatchCommandError({
+ message: cause instanceof Error ? cause.message : "Channel command failed.",
+ cause,
+ }),
+ }),
+ );
+ }
+ const decodedCommand = yield* normalizeDispatchCommand(command);
+ const currentPerson =
+ decodedCommand.type === "group.create" ||
+ decodedCommand.type === "group.leave" ||
+ decodedCommand.type === "thread.turn.start"
+ ? yield* loadEnvironmentPeople().pipe(Effect.map((people) => people.current))
+ : undefined;
+ const actorCommand = applyAuthenticatedCommandActor(decodedCommand, {
+ personId: currentSessionId,
+ displayName: currentPerson?.displayName ?? "Paired person",
+ canManageGroups: currentSession.scopes.includes(AuthAccessWriteScope),
+ });
+ let normalizedCommand = actorCommand;
+ if (
+ actorCommand.type === "group.person.assign" ||
+ actorCommand.type === "group.person.unassign"
+ ) {
+ if (!canManageGroupPeople(actorCommand, currentSession.scopes)) {
+ return yield* new OrchestrationDispatchCommandError({
+ message: "Managing group people requires access:write.",
+ });
+ }
+ const clientSessions = yield* serverAuth.listClientSessions(currentSessionId);
+ const knownPersonCommand = applyKnownGroupPerson(actorCommand, clientSessions);
+ if (!knownPersonCommand) {
+ return yield* new OrchestrationDispatchCommandError({
+ message: "Only a paired person can be changed in a group.",
+ });
+ }
+ normalizedCommand = knownPersonCommand;
+ }
// Archive and settle both mean "done with this thread", so a
// live provider session must not keep running background work
// (PR monitors, dev servers, subagent fleets) after either
@@ -1631,7 +1750,27 @@ const makeWsRpcLayer = (
);
const bufferedLiveStream = coalesceShellLiveStream(Stream.fromQueue(liveBuffer));
- const loadSnapshot = projectionSnapshotQuery.getShellSnapshot().pipe(
+ const loadSnapshot = Effect.all({
+ snapshot: projectionSnapshotQuery.getShellSnapshot(),
+ people: loadEnvironmentPeople(),
+ }).pipe(
+ Effect.map(({ snapshot, people }) => ({
+ ...snapshot,
+ currentPersonId: people.current.personId,
+ currentPersonDisplayName: people.current.displayName,
+ ...(people.host === undefined
+ ? {}
+ : {
+ environmentHostPersonId: people.host.personId,
+ environmentHostDisplayName: people.host.displayName,
+ }),
+ bots: snapshot.bots.map((bot) => ({
+ ...bot,
+ channelBindings: ChannelRuntime.channelBindingsForRuntime(
+ bot.channelBindings ?? [],
+ ),
+ })),
+ })),
Effect.tapError((cause) =>
Effect.logError("orchestration shell snapshot load failed", { cause }),
),
@@ -1716,6 +1855,15 @@ const makeWsRpcLayer = (
observeRpcEffect(
ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot,
projectionSnapshotQuery.getArchivedShellSnapshot().pipe(
+ Effect.map((snapshot) => ({
+ ...snapshot,
+ bots: snapshot.bots.map((bot) => ({
+ ...bot,
+ channelBindings: ChannelRuntime.channelBindingsForRuntime(
+ bot.channelBindings ?? [],
+ ),
+ })),
+ })),
Effect.tapError((cause) =>
Effect.logError("orchestration archived shell snapshot load failed", { cause }),
),
diff --git a/apps/web/package.json b/apps/web/package.json
index 5a90519f6..ab1ca0c30 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -21,6 +21,7 @@
"@fontsource-variable/geist": "^5.3.0",
"@fontsource-variable/geist-mono": "^5.3.0",
"@formkit/auto-animate": "^0.9.0",
+ "@hello-pangea/dnd": "18.0.1",
"@hugeicons/core-free-icons": "^4.3.0",
"@hugeicons/react": "^1.1.10",
"@legendapp/list": "catalog:",
diff --git a/apps/web/src/authBootstrap.test.ts b/apps/web/src/authBootstrap.test.ts
index 1a79f729b..3a05509f8 100644
--- a/apps/web/src/authBootstrap.test.ts
+++ b/apps/web/src/authBootstrap.test.ts
@@ -278,6 +278,21 @@ describe("resolveInitialServerAuthGateState", () => {
expect(testWindow.location.searchParams.get("token")).toBeNull();
});
+ it("exchanges an explicit pairing token when a browser session already exists", async () => {
+ const testWindow = installTestBrowser("http://localhost/#token=admin-bootstrap-token");
+ const testApi = await installAuthApi({
+ session: () => authenticatedSession(LOOPBACK_AUTH),
+ browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])),
+ });
+ const { resolveInitialServerAuthGateState } = await import("./environments/primary");
+
+ await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
+ status: "authenticated",
+ });
+ expect(testApi.calls.browserSession).toEqual([{ credential: "admin-bootstrap-token" }]);
+ expect(testWindow.location.hash).toBe("");
+ });
+
it("accepts query-string pairing tokens as a backward-compatible fallback", async () => {
const testWindow = installTestBrowser("http://localhost/?token=pairing-token");
const { takePairingTokenFromUrl } = await import("./environments/primary");
diff --git a/apps/web/src/channelAccess.ts b/apps/web/src/channelAccess.ts
new file mode 100644
index 000000000..1ae83425f
--- /dev/null
+++ b/apps/web/src/channelAccess.ts
@@ -0,0 +1,29 @@
+import {
+ AuthAccessWriteScope,
+ type AuthSessionState,
+ type ChannelBinding,
+ type ChannelProvider,
+} from "@t3tools/contracts";
+
+export function canManageChannels(
+ session: Pick<AuthSessionState, "authenticated" | "scopes"> | null,
+): boolean {
+ return session?.authenticated === true && session.scopes?.includes(AuthAccessWriteScope) === true;
+}
+
+export function resolveChannelSettingsAccess(input: {
+ readonly isPending: boolean;
+ readonly session: Pick<AuthSessionState, "authenticated" | "scopes"> | null;
+}): "pending" | "allowed" | "denied" {
+ if (input.session === null && input.isPending) return "pending";
+ return canManageChannels(input.session) ? "allowed" : "denied";
+}
+
+export function connectedChannelBinding(
+ bindings: ReadonlyArray<ChannelBinding> | undefined,
+ provider: ChannelProvider,
+): ChannelBinding | undefined {
+ return bindings?.find(
+ (binding) => binding.provider === provider && binding.status === "connected",
+ );
+}
diff --git a/apps/web/src/components/roster/BotChannelsSheet.tsx b/apps/web/src/components/roster/BotChannelsSheet.tsx
new file mode 100644
index 000000000..dcd89a58e
--- /dev/null
+++ b/apps/web/src/components/roster/BotChannelsSheet.tsx
@@ -0,0 +1,213 @@
+import { useAtomValue } from "@effect/atom-react";
+import {
+ BotId,
+ type ChannelConnectionId,
+ type ChannelConnectionProfile,
+ type ChannelProvider,
+ type EnvironmentId,
+ type OrchestrationBot,
+} from "@t3tools/contracts";
+import { useState } from "react";
+
+import { resolveChannelSettingsAccess } from "../../channelAccess";
+import { usePrimarySettings } from "../../hooks/useSettings";
+import { botEnvironment, environmentBotsAtom } from "../../state/bots";
+import { usePrimaryEnvironmentId } from "../../state/environments";
+import { useEnvironmentSessionState } from "../../state/session";
+import { openSettings } from "../../settingsDialogStore";
+import { useAtomCommand } from "../../state/use-atom-command";
+import { Badge } from "../ui/badge";
+import { Button } from "../ui/button";
+import { Sheet, SheetHeader, SheetPanel, SheetPopup, SheetTitle } from "../ui/sheet";
+import { Spinner } from "../ui/spinner";
+import { toastManager } from "../ui/toast";
+import type { Bot } from "./types";
+
+const NO_ENVIRONMENT = "" as EnvironmentId;
+
+const providerLabel = (provider: ChannelProvider) =>
+ provider === "imessage"
+ ? "Photon"
+ : provider === "whatsapp"
+ ? "Meta Cloud API"
+ : "Telegram Bot API";
+
+const assignedBotForConnection = (
+ connectionId: ChannelConnectionId,
+ bots: ReadonlyArray<Pick<OrchestrationBot, "id" | "name" | "channelBindings">>,
+) =>
+ bots.find((candidate) =>
+ (candidate.channelBindings ?? []).some(
+ (binding) => binding.connectionId === connectionId && binding.status !== "disconnected",
+ ),
+ );
+
+export function BotChannelsSheet({
+ bot,
+ open,
+ onOpenChange,
+}: {
+ readonly bot: Bot;
+ readonly open: boolean;
+ readonly onOpenChange: (open: boolean) => void;
+}) {
+ const environmentId = usePrimaryEnvironmentId();
+ const targetEnvironmentId = environmentId ?? NO_ENVIRONMENT;
+ const session = useEnvironmentSessionState(targetEnvironmentId);
+ const bots = useAtomValue(environmentBotsAtom(targetEnvironmentId));
+ const connections = usePrimarySettings((settings) => settings.channelConnections);
+ const attach = useAtomCommand(botEnvironment.channels.attach, { reportFailure: false });
+ const disconnect = useAtomCommand(botEnvironment.channels.disconnect, {
+ reportFailure: false,
+ });
+ const reconnect = useAtomCommand(botEnvironment.channels.reconnect, {
+ reportFailure: false,
+ });
+ const [busyId, setBusyId] = useState<string | null>(null);
+ const access = resolveChannelSettingsAccess({
+ isPending: session.isPending,
+ session: session.data,
+ });
+
+ const manage = async (connection: ChannelConnectionProfile) => {
+ if (!environmentId) return;
+ const owner = assignedBotForConnection(connection.id, bots);
+ if (owner && owner.id !== bot.id) return;
+ const binding = owner?.channelBindings?.find(
+ (candidate) => candidate.connectionId === connection.id,
+ );
+ setBusyId(connection.id);
+ const result =
+ binding?.status === "needs-reconnect"
+ ? await reconnect({
+ environmentId,
+ input: { botId: BotId.make(bot.id), provider: connection.provider },
+ })
+ : binding && binding.status !== "disconnected"
+ ? await disconnect({
+ environmentId,
+ input: { botId: BotId.make(bot.id), provider: connection.provider },
+ })
+ : await attach({
+ environmentId,
+ input: {
+ botId: BotId.make(bot.id),
+ connectionId: connection.id,
+ provider: connection.provider,
+ },
+ });
+ setBusyId(null);
+ if (result._tag === "Failure") {
+ toastManager.add({ type: "error", title: "Could not update channel" });
+ }
+ };
+
+ const openChannelSettings = () => {
+ onOpenChange(false);
+ openSettings("channels", null, environmentId);
+ };
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetPopup side="right" className="w-[min(94vw,28rem)]">
+ <SheetHeader>
+ <SheetTitle>{bot.name} channels</SheetTitle>
+ </SheetHeader>
+ <SheetPanel className="space-y-2 px-3">
+ {environmentId === null ? (
+ <div className="py-8 text-sm text-muted-foreground">Connect an environment first.</div>
+ ) : access === "pending" ? (
+ <div className="flex justify-center py-8">
+ <Spinner aria-label="Loading channel access" />
+ </div>
+ ) : access === "denied" ? (
+ <div className="py-8 text-sm text-muted-foreground">
+ Open this environment on its host 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>
+ <Button onClick={openChannelSettings}>Set up channels</Button>
+ </div>
+ ) : (
+ <>
+ {connections.map((connection) => {
+ const owner = assignedBotForConnection(connection.id, bots);
+ const binding = owner?.channelBindings?.find(
+ (candidate) => candidate.connectionId === connection.id,
+ );
+ const ownedByCurrentBot = owner?.id === bot.id;
+ const action =
+ owner && !ownedByCurrentBot
+ ? "Assigned"
+ : binding?.status === "needs-reconnect"
+ ? "Reconnect"
+ : binding && binding.status !== "disconnected"
+ ? "Disconnect"
+ : "Connect";
+ return (
+ <div
+ key={connection.id}
+ className="flex items-center justify-between 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}` : ""}
+ </div>
+ {owner ? (
+ <Badge
+ variant={binding?.status === "needs-reconnect" ? "warning" : "success"}
+ size="sm"
+ >
+ {binding?.status === "needs-reconnect"
+ ? "Needs reconnect"
+ : `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">
+ {connection.managementUrl ? (
+ <Button
+ variant="outline"
+ render={
+ <a href={connection.managementUrl} target="_blank" rel="noreferrer" />
+ }
+ >
+ Open Photon
+ </Button>
+ ) : null}
+ <Button
+ variant={ownedByCurrentBot ? "outline" : "default"}
+ disabled={busyId !== null || (owner !== undefined && !ownedByCurrentBot)}
+ onClick={() => void manage(connection)}
+ >
+ {action}
+ </Button>
+ </div>
+ </div>
+ );
+ })}
+ <Button variant="outline" onClick={openChannelSettings}>
+ Manage connections
+ </Button>
+ </>
+ )}
+ </SheetPanel>
+ </SheetPopup>
+ </Sheet>
+ );
+}
diff --git a/apps/web/src/components/roster/BotDetailsPanel.test.tsx b/apps/web/src/components/roster/BotDetailsPanel.test.tsx
index 102795ce9..62387389a 100644
--- a/apps/web/src/components/roster/BotDetailsPanel.test.tsx
+++ b/apps/web/src/components/roster/BotDetailsPanel.test.tsx
@@ -56,6 +56,9 @@ describe("BotDetailsPanel", () => {
expect(markup).toContain("Facts and history");
expect(markup).toContain(">Tools</div>");
expect(markup).toContain("No workspace tools");
+ expect(markup).toContain(">Channels</div>");
+ expect(markup).toContain('aria-label="Manage bot channels"');
+ expect(markup).toContain("No channels");
expect(markup).toContain(">Manage</span>");
expect(markup).toContain('aria-label="Collapse Akeru bot sidebar"');
expect(markup).toContain('aria-label="Open Akeru bot sidebar"');
@@ -97,7 +100,8 @@ describe("BotDetailsPanel", () => {
const source = NodeFS.readFileSync(new URL("./BotDetailsPanel.tsx", import.meta.url), "utf8");
expect(source).toContain('resolveShortcutCommand(event, keybindings) !== "rightPanel.toggle"');
- expect(source).toContain('shortcutLabelForCommand(keybindings, "rightPanel.toggle")');
+ expect(source).toContain("shortcutLabelForCommand(");
+ expect(source).toContain('"rightPanel.toggle"');
expect(source).toContain('window.addEventListener("keydown", onKeyDown, true)');
expect(source).toContain("RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY");
});
diff --git a/apps/web/src/components/roster/BotDetailsPanel.tsx b/apps/web/src/components/roster/BotDetailsPanel.tsx
index 30f065e30..1e45059e3 100644
--- a/apps/web/src/components/roster/BotDetailsPanel.tsx
+++ b/apps/web/src/components/roster/BotDetailsPanel.tsx
@@ -9,6 +9,7 @@ import {
Cancel01Icon,
Brain02Icon,
Edit02Icon,
+ Link02Icon,
PanelRightCloseIcon,
PanelRightIcon,
WrenchIcon,
@@ -42,7 +43,7 @@ import { Switch } from "../ui/switch";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { AvatarPickerDialog } from "./AvatarPickerDialog";
import { BotAvatarView } from "./BotAvatarView";
-import { BotBrowserPreview } from "./BotBrowserPreview";
+import { BotChannelsSheet } from "./BotChannelsSheet";
import { BotModelPicker } from "./BotModelPicker";
import { BotUsageSection } from "./BotUsageSection";
import { BotMemorySheet } from "./BotMemorySheet";
@@ -194,6 +195,9 @@ function BotProfileEditor({
const enabledToolCount = tools.filter(
(tool) => tool.workspaceEnabled && !disabledMcpServerIds.includes(tool.id),
).length;
+ const connectedChannelCount = (bot.channelBindings ?? []).filter(
+ (binding) => binding.status !== "disconnected",
+ ).length;
const toolOverridesDirty =
[...disabledMcpServerIds].sort().join("\u0000") !==
[...bot.disabledMcpServerIds].sort().join("\u0000");
@@ -388,6 +392,23 @@ function BotProfileEditor({
<span className="text-xs text-muted-foreground">Manage</span>
</button>
</div>
+
+ <div className="space-y-2">
+ <div className="text-sm font-medium">Channels</div>
+ <button
+ type="button"
+ aria-label="Manage bot channels"
+ aria-expanded={channelsOpen}
+ onClick={() => setChannelsOpen(true)}
+ className="flex min-h-10 w-full items-center gap-3 rounded-lg border border-border bg-muted/20 px-3 text-left outline-none transition-colors hover:bg-muted/40 focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <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`}
+ </span>
+ <span className="text-xs text-muted-foreground">Manage</span>
+ </button>
+ </div>
</div>
<div className="mt-7 flex items-center justify-end gap-3">
diff --git a/apps/web/src/components/roster/BotRosterSidebar.tsx b/apps/web/src/components/roster/BotRosterSidebar.tsx
index 2d54d79ca..689486a47 100644
--- a/apps/web/src/components/roster/BotRosterSidebar.tsx
+++ b/apps/web/src/components/roster/BotRosterSidebar.tsx
@@ -1,28 +1,19 @@
-import {
- DndContext,
- DragOverlay,
- PointerSensor,
- closestCenter,
- useDroppable,
- useSensor,
- useSensors,
- type DragEndEvent,
- type DragOverEvent,
- type DragStartEvent,
-} from "@dnd-kit/core";
-import { restrictToFirstScrollableAncestor, snapCenterToCursor } from "@dnd-kit/modifiers";
-import {
- SortableContext,
- rectSortingStrategy,
- useSortable,
- verticalListSortingStrategy,
-} from "@dnd-kit/sortable";
-import { CSS } from "@dnd-kit/utilities";
+import { DragDropContext, Draggable, Droppable, type DropResult } from "@hello-pangea/dnd";
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
-import { BotId, EnvironmentId, ThreadId } from "@t3tools/contracts";
+import { BotId, EnvironmentId, GroupId, ThreadId } from "@t3tools/contracts";
import { Link, useLocation, useNavigate } from "@tanstack/react-router";
-import { PlusIcon, SearchIcon } from "lucide-react";
-import { memo, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
+import {
+ BotIcon,
+ ChevronDownIcon,
+ ChevronRightIcon,
+ FolderInputIcon,
+ PinIcon,
+ PlusIcon,
+ SearchIcon,
+ Trash2Icon,
+ UsersIcon,
+} from "lucide-react";
+import { memo, useEffect, useMemo, useRef, useState } from "react";
import { useShallow } from "zustand/react/shallow";
import { isElectron } from "../../env";
@@ -34,6 +25,15 @@ import { usePrimaryEnvironmentId } from "../../state/environments";
import { useAtomCommand } from "../../state/use-atom-command";
import { SidebarChromeFooter } from "../sidebar/SidebarChrome";
import { Button } from "../ui/button";
+import {
+ Menu,
+ MenuItem,
+ MenuPopup,
+ MenuSub,
+ MenuSubPopup,
+ MenuSubTrigger,
+ MenuTrigger,
+} from "../ui/menu";
import { SidebarContent, SidebarGroup, SidebarHeader, SidebarTrigger } from "../ui/sidebar";
import { toastManager } from "../ui/toast";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
@@ -43,20 +43,25 @@ import { visibleBotChatMessages } from "./botConversationPresentation";
import { useBotPresence } from "./botPresence";
import { findLatestBotThreadTarget } from "./botThreadRuntime.logic";
import { NewBotDialog } from "./NewBotDialog";
+import { NewGroupDialog, type NewGroupInput } from "./NewGroupDialog";
+import { GroupMemberStack } from "./GroupMemberStack";
import {
- buildGroupedRosterSections,
- buildRosterStrip,
filterRosterBots,
+ filterRosterGroups,
formatRosterTimestamp,
isRecordableChatPath,
parseChatPath,
resolveLatestRosterMessage,
resolveRosterIndicator,
+ parseRosterBotDragId,
+ parseRosterGroupDropId,
+ rosterBotDragId,
+ rosterGroupDropId,
type RosterLastMessage,
type RosterPresence,
} from "./roster.logic";
-import { moveRosterBot, useRosterStore } from "./rosterStore";
-import type { Bot, BotAvatar } from "./types";
+import { useRosterStore, type RosterItemRef, type RosterSection } from "./rosterStore";
+import type { Bot, BotAvatar, Group } from "./types";
import { useServerRosterSync } from "./useServerRoster";
/** Avatar with a yellow needs-you light and a green working light. */
@@ -99,8 +104,12 @@ function RosterAvatar({
*/
const RosterSidebarHeader = memo(function RosterSidebarHeader({
onNewBot,
+ onNewGroup,
+ onNewSection,
}: {
onNewBot: () => void;
+ onNewGroup: () => void;
+ onNewSection: () => void;
}) {
return (
<SidebarHeader
@@ -122,14 +131,13 @@ const RosterSidebarHeader = memo(function RosterSidebarHeader({
</span>
</Link>
<div className="flex items-center justify-end">
- <Tooltip>
- <TooltipTrigger
+ <Menu>
+ <MenuTrigger
render={
<Button
- aria-label="New bot"
+ aria-label="Create"
data-testid="roster-new-bot"
className="size-[var(--workspace-titlebar-control-size)]! [-webkit-app-region:no-drag]"
- onClick={onNewBot}
size="icon"
variant="ghost"
>
@@ -137,52 +145,27 @@ const RosterSidebarHeader = memo(function RosterSidebarHeader({
</Button>
}
/>
- <TooltipPopup side="bottom">New bot</TooltipPopup>
- </Tooltip>
+ <MenuPopup align="end">
+ <MenuItem onClick={onNewBot}>
+ <BotIcon />
+ New bot
+ </MenuItem>
+ <MenuItem onClick={onNewGroup}>
+ <UsersIcon />
+ New group
+ </MenuItem>
+ <MenuItem onClick={onNewSection}>
+ <FolderInputIcon />
+ New section
+ </MenuItem>
+ </MenuPopup>
+ </Menu>
</div>
</div>
</SidebarHeader>
);
});
-const BotStripTile = memo(function BotStripTile({
- bot,
- isActive,
- onSelect,
-}: {
- bot: Bot;
- isActive: boolean;
- onSelect: (bot: Bot) => void;
-}) {
- const presence = useBotPresence(bot.id);
- const { listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: bot.id });
- return (
- <li
- ref={setNodeRef}
- className={cn("list-none touch-pan-y", isDragging && "opacity-0")}
- style={{ transform: CSS.Transform.toString(transform), transition }}
- {...listeners}
- >
- <button
- type="button"
- data-testid="roster-strip-tile"
- data-bot-hover
- aria-current={isActive || undefined}
- onClick={() => onSelect(bot)}
- className={cn(
- "flex w-20 cursor-grab flex-col items-center gap-2 rounded-xl px-1 pb-2 pt-3 outline-none select-none focus-visible:ring-2 focus-visible:ring-ring active:cursor-grabbing",
- isActive ? "bg-sidebar-row-active" : "bg-transparent hover:bg-sidebar-row-hover",
- )}
- >
- <RosterAvatar bot={bot} presence={presence} className="size-14" />
- <span className="w-full truncate text-center text-xs text-sidebar-foreground">
- {bot.name}
- </span>
- </button>
- </li>
- );
-});
-
function useLatestBotMessage(
botId: string,
fallback: RosterLastMessage | null,
@@ -212,58 +195,119 @@ const BotRosterRow = memo(function BotRosterRow({
lastMessage,
isActive,
onSelect,
+ index,
+ pinned,
+ sections,
+ onPin,
+ onMove,
+ dragDisabled,
}: {
bot: Bot;
lastMessage: RosterLastMessage | null;
isActive: boolean;
onSelect: (bot: Bot) => void;
+ index: number;
+ pinned: boolean;
+ sections: readonly RosterSection[];
+ onPin: (pinned: boolean) => void;
+ onMove: (sectionId: string | null) => void;
+ dragDisabled: boolean;
}) {
+ const menuTriggerRef = useRef<HTMLButtonElement>(null);
const timestampFormat = useClientSettings((s) => s.timestampFormat);
const presence = useBotPresence(bot.id);
const latestMessage = useLatestBotMessage(bot.id, lastMessage);
const { listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: bot.id });
return (
- <li
- ref={setNodeRef}
- className={cn("list-none touch-pan-y", isDragging && "opacity-0")}
- style={{ transform: CSS.Transform.toString(transform), transition }}
- {...listeners}
+ <Draggable
+ draggableId={rosterBotDragId(bot.id)}
+ index={index}
+ isDragDisabled={dragDisabled}
+ disableInteractiveElementBlocking
>
- <div
- data-testid="roster-bot-row"
- data-bot-hover
- className={cn(
- "flex w-full items-center rounded-lg outline-none select-none",
- isActive
- ? "bg-sidebar-row-active text-sidebar-foreground"
- : "bg-transparent text-sidebar-foreground hover:bg-sidebar-row-hover",
- )}
- >
- <button
- type="button"
- aria-current={isActive || undefined}
- onClick={() => onSelect(bot)}
- className="flex min-w-0 flex-1 cursor-pointer items-center gap-2.5 rounded-lg px-2 py-1.5 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ {(provided, snapshot) => (
+ <div
+ ref={provided.innerRef}
+ role="listitem"
+ className={cn("list-none touch-pan-y", snapshot.isDragging && "z-50")}
+ {...provided.draggableProps}
>
- <RosterAvatar bot={bot} presence={presence} className="size-10" />
- <span className="flex min-w-0 flex-1 flex-col">
- <span className="flex items-baseline gap-2">
- <span className="min-w-0 flex-1 truncate text-sm font-semibold">{bot.name}</span>
- {latestMessage ? (
- <span className="shrink-0 text-xs tabular-nums text-sidebar-muted-foreground">
- {formatRosterTimestamp(latestMessage.at, timestampFormat)}
+ <div
+ data-testid="roster-bot-row"
+ data-bot-hover
+ onContextMenu={(event) => {
+ event.preventDefault();
+ menuTriggerRef.current?.click();
+ }}
+ className={cn(
+ "relative flex w-full items-center rounded-lg outline-none select-none",
+ snapshot.isDragging
+ ? "bg-sidebar-row-active text-sidebar-foreground shadow-xl"
+ : isActive
+ ? "bg-sidebar-row-active text-sidebar-foreground"
+ : "bg-transparent text-sidebar-foreground hover:bg-sidebar-row-hover",
+ )}
+ >
+ <button
+ type="button"
+ aria-current={isActive || undefined}
+ onClick={() => onSelect(bot)}
+ className="flex min-w-0 flex-1 cursor-grab items-center gap-2.5 rounded-lg px-2 py-1.5 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring active:cursor-grabbing"
+ {...provided.dragHandleProps}
+ >
+ <RosterAvatar bot={bot} presence={presence} className="size-10" />
+ <span className="flex min-w-0 flex-1 flex-col">
+ <span className="flex items-baseline gap-2">
+ <span className="min-w-0 flex-1 truncate text-sm font-semibold">{bot.name}</span>
+ {latestMessage ? (
+ <span className="shrink-0 text-xs tabular-nums text-sidebar-muted-foreground">
+ {formatRosterTimestamp(latestMessage.at, timestampFormat)}
+ </span>
+ ) : null}
</span>
- ) : null}
- </span>
- {latestMessage ? (
- <span className="truncate text-[13px] text-sidebar-muted-foreground">
- {latestMessage.text}
+ {latestMessage ? (
+ <span className="truncate text-[13px] text-sidebar-muted-foreground">
+ {latestMessage.text}
+ </span>
+ ) : null}
</span>
- ) : null}
- </span>
- </button>
- </div>
- </li>
+ </button>
+ <Menu>
+ <MenuTrigger
+ render={
+ <button
+ ref={menuTriggerRef}
+ type="button"
+ aria-label={`Actions for ${bot.name}`}
+ className="absolute right-2 top-1/2 size-px -translate-y-1/2 overflow-hidden opacity-0 outline-none focus-visible:size-7 focus-visible:overflow-visible focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-ring"
+ />
+ }
+ />
+ <MenuPopup align="end">
+ <MenuItem onClick={() => onPin(!pinned)}>
+ <PinIcon />
+ {pinned ? "Unpin" : "Pin"}
+ </MenuItem>
+ <MenuSub>
+ <MenuSubTrigger>
+ <FolderInputIcon />
+ Move to
+ </MenuSubTrigger>
+ <MenuSubPopup>
+ {sections.map((section) => (
+ <MenuItem key={section.id} onClick={() => onMove(section.id)}>
+ {section.name}
+ </MenuItem>
+ ))}
+ <MenuItem onClick={() => onMove(null)}>Unassigned</MenuItem>
+ </MenuSubPopup>
+ </MenuSub>
+ </MenuPopup>
+ </Menu>
+ </div>
+ </div>
+ )}
+ </Draggable>
);
});
@@ -306,34 +350,164 @@ function RailBotButton({
);
}
-function RosterDropZone({
- id,
- className,
- children,
+function GroupRosterRow({
+ group,
+ bots,
+ isActive,
+ onSelect,
+ pinned,
+ onPin,
+ index,
+ sections,
+ onMove,
+ dragDisabled,
}: {
- id: "pinned-zone" | "unpinned-zone";
- className?: string;
- children: ReactNode;
+ group: Group;
+ bots: readonly Bot[];
+ isActive: boolean;
+ onSelect: () => void;
+ pinned: boolean;
+ onPin: (pinned: boolean) => void;
+ index: number;
+ sections: readonly RosterSection[];
+ onMove: (sectionId: string | null) => void;
+ dragDisabled: boolean;
}) {
- const { isOver, setNodeRef } = useDroppable({ id });
+ const menuTriggerRef = useRef<HTMLButtonElement>(null);
+ const members = group.members.filter(
+ (member) =>
+ member.kind === "bot" && bots.some((bot) => bot.id === member.botId && !bot.archivedAt),
+ ).length;
return (
- <div
- ref={setNodeRef}
- data-drop-zone={id}
- data-drag-over={isOver || undefined}
- className={className}
+ <Draggable
+ draggableId={rosterGroupDropId(group.id)}
+ index={index}
+ isDragDisabled={dragDisabled}
>
- {children}
- </div>
+ {(dragProvided, dragSnapshot) => (
+ <div
+ ref={dragProvided.innerRef}
+ {...dragProvided.draggableProps}
+ role="listitem"
+ data-testid="roster-group-card"
+ onContextMenu={(event) => {
+ event.preventDefault();
+ menuTriggerRef.current?.click();
+ }}
+ className={cn(
+ "relative flex touch-pan-y items-center rounded-lg",
+ dragSnapshot.isDragging && "z-50 bg-sidebar shadow-xl",
+ isActive && "bg-sidebar-row-active",
+ )}
+ >
+ <button
+ type="button"
+ aria-current={isActive || undefined}
+ onClick={onSelect}
+ {...dragProvided.dragHandleProps}
+ className="flex min-w-0 flex-1 cursor-grab items-center gap-2.5 rounded-lg px-2 py-1.5 text-left outline-none hover:bg-sidebar-row-hover focus-visible:ring-2 focus-visible:ring-ring active:cursor-grabbing"
+ >
+ <GroupMemberStack group={group} bots={bots} sizeClassName="size-10" />
+ <span className="min-w-0 flex-1 truncate text-sm font-semibold">{group.name}</span>
+ <span className="text-xs text-sidebar-muted-foreground">{members}</span>
+ </button>
+ <Menu>
+ <MenuTrigger
+ render={
+ <button
+ ref={menuTriggerRef}
+ type="button"
+ aria-label={`Actions for ${group.name}`}
+ className="absolute right-2 top-1/2 size-px -translate-y-1/2 overflow-hidden opacity-0 outline-none focus-visible:size-7 focus-visible:overflow-visible focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-ring"
+ />
+ }
+ />
+ <MenuPopup align="end">
+ <MenuItem onClick={() => onPin(!pinned)}>
+ <PinIcon />
+ {pinned ? "Unpin" : "Pin"}
+ </MenuItem>
+ <MenuSub>
+ <MenuSubTrigger>
+ <FolderInputIcon />
+ Move to
+ </MenuSubTrigger>
+ <MenuSubPopup>
+ {sections.map((section) => (
+ <MenuItem key={section.id} onClick={() => onMove(section.id)}>
+ {section.name}
+ </MenuItem>
+ ))}
+ <MenuItem onClick={() => onMove(null)}>Unassigned</MenuItem>
+ </MenuSubPopup>
+ </MenuSub>
+ </MenuPopup>
+ </Menu>
+ </div>
+ )}
+ </Draggable>
);
}
-function BotDragOverlay({ bot }: { bot: Bot }) {
- const presence = useBotPresence(bot.id);
+function PinnedRosterItem({
+ item,
+ bots,
+ groups,
+ onSelectBot,
+ onSelectGroup,
+}: {
+ item: RosterItemRef;
+ bots: readonly Bot[];
+ groups: readonly Group[];
+ onSelectBot: (bot: Bot) => void;
+ onSelectGroup: (group: Group) => void;
+}) {
+ const menuTriggerRef = useRef<HTMLButtonElement>(null);
+ const bot = item.kind === "bot" ? bots.find((candidate) => candidate.id === item.id) : null;
+ const group = item.kind === "group" ? groups.find((candidate) => candidate.id === item.id) : null;
+ if (!bot && !group) return null;
+ const label = bot?.name ?? group!.name;
return (
- <div className="flex w-20 cursor-grabbing flex-col items-center gap-2 rounded-xl bg-sidebar-row-hover px-1 pb-2 pt-3 text-sidebar-foreground shadow-xl select-none">
- <RosterAvatar bot={bot} presence={presence} className="size-14" />
- <span className="w-full truncate text-center text-xs">{bot.name}</span>
+ <div
+ className="relative w-20 shrink-0"
+ onContextMenu={(event) => {
+ event.preventDefault();
+ menuTriggerRef.current?.click();
+ }}
+ >
+ <button
+ type="button"
+ title={label}
+ onClick={() => (bot ? onSelectBot(bot) : onSelectGroup(group!))}
+ className="flex w-full flex-col items-center gap-1.5 rounded-xl px-1 py-2 text-sidebar-foreground outline-none hover:bg-sidebar-row-hover focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ {bot ? (
+ <BotAvatarView avatar={bot.avatar} name={bot.name} className="size-12" />
+ ) : (
+ <span className="flex size-14 items-center justify-center">
+ <GroupMemberStack group={group!} bots={bots} sizeClassName="size-14" />
+ </span>
+ )}
+ <span className="w-full truncate text-[11px] font-medium">{label}</span>
+ </button>
+ <Menu>
+ <MenuTrigger
+ render={
+ <button
+ ref={menuTriggerRef}
+ type="button"
+ aria-label={`Actions for pinned ${label}`}
+ className="absolute right-2 top-2 size-px overflow-hidden opacity-0 outline-none focus-visible:size-7 focus-visible:overflow-visible focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-ring"
+ />
+ }
+ />
+ <MenuPopup align="center">
+ <MenuItem onClick={() => useRosterStore.getState().setItemPinned(item, false)}>
+ <PinIcon />
+ Unpin
+ </MenuItem>
+ </MenuPopup>
+ </Menu>
</div>
);
}
@@ -342,29 +516,28 @@ export default function BotRosterSidebar() {
useServerRosterSync();
const navigate = useNavigate();
const environmentId = usePrimaryEnvironmentId();
- const createBotCommand = useAtomCommand(botEnvironment.create, { reportFailure: false });
+ const createBotCommand = useAtomCommand(botEnvironment.create, {
+ reportFailure: false,
+ });
+ const createGroupCommand = useAtomCommand(botEnvironment.groups.create, {
+ reportFailure: false,
+ });
const pathname = useLocation({ select: (location) => location.pathname });
- const { bots, groups, lastMessageByBotId, selectedBotId } = useRosterStore(
+ const { bots, groups, lastMessageByBotId, selectedBotId, sections, pinnedItems } = useRosterStore(
useShallow((state) => ({
bots: state.bots,
groups: state.groups,
lastMessageByBotId: state.lastMessageByBotId,
selectedBotId: state.selectedBotId,
+ sections: state.sections,
+ pinnedItems: state.pinnedItems,
})),
);
const [query, setQuery] = useState("");
- const [dragLayout, setDragLayout] = useState<Bot[] | null>(null);
- const dragLayoutRef = useRef<Bot[] | null>(null);
- const [activeBotId, setActiveBotId] = useState<string | null>(null);
- const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }));
- const strip = useMemo(
- () => buildRosterStrip(bots, lastMessageByBotId),
- [bots, lastMessageByBotId],
- );
const visibleBots = useMemo(
- () => filterRosterBots(dragLayout ?? bots, query).filter((bot) => bot.archivedAt === null),
- [bots, dragLayout, query],
+ () => filterRosterBots(bots, query).filter((bot) => bot.archivedAt === null),
+ [bots, query],
);
const pinnedBots = visibleBots.filter((bot) => bot.pinned);
const unpinnedBots = visibleBots.filter((bot) => !bot.pinned);
@@ -372,43 +545,94 @@ export default function BotRosterSidebar() {
() => buildGroupedRosterSections(dragLayout ?? bots, groups, query),
[bots, dragLayout, groups, query],
);
- const activeBot =
- activeBotId === null
- ? null
- : ((dragLayout ?? bots).find((bot) => bot.id === activeBotId) ?? null);
-
- const resolveDrop = (layout: readonly Bot[], overId: string) => {
- if (overId === "pinned-zone") return { overBotId: null, pinned: true } as const;
- if (overId === "unpinned-zone") return { overBotId: null, pinned: false } as const;
- const overBot = layout.find((bot) => bot.id === overId);
- return overBot ? { overBotId: overBot.id, pinned: overBot.pinned } : null;
- };
- const handleDragStart = ({ active }: DragStartEvent) => {
- dragLayoutRef.current = bots;
- setActiveBotId(String(active.id));
- setDragLayout(bots);
- };
- const handleDragOver = ({ active, over }: DragOverEvent) => {
- if (!over) return;
- setDragLayout((current) => {
- const layout = current ?? bots;
- const drop = resolveDrop(layout, String(over.id));
- if (!drop) return layout;
- const next = moveRosterBot(layout, String(active.id), drop.overBotId, drop.pinned) ?? layout;
- dragLayoutRef.current = next;
- return next;
- });
- };
- const finishDrag = () => {
- dragLayoutRef.current = null;
- setActiveBotId(null);
- setDragLayout(null);
- };
- const handleDragEnd = ({ over }: DragEndEvent) => {
- if (over && dragLayoutRef.current) {
- useRosterStore.getState().commitBotLayout(dragLayoutRef.current);
+ const groupRouteActive = pathname.startsWith("/groups/");
+ const pinnedBotIds = useMemo(
+ () => new Set(pinnedItems.filter((item) => item.kind === "bot").map((item) => item.id)),
+ [pinnedItems],
+ );
+ const assignedBotIds = useMemo(
+ () => new Set(sections.flatMap((section) => section.botIds)),
+ [sections],
+ );
+ const botsBySection = useMemo(
+ () =>
+ new Map(
+ sections.map((section) => [
+ section.id,
+ section.botIds
+ .map((id) => visibleBots.find((bot) => bot.id === id))
+ .filter((bot): bot is Bot => bot !== undefined && !pinnedBotIds.has(bot.id)),
+ ]),
+ ),
+ [pinnedBotIds, sections, visibleBots],
+ );
+ const unassignedBots = useMemo(
+ () => visibleBots.filter((bot) => !assignedBotIds.has(bot.id) && !pinnedBotIds.has(bot.id)),
+ [assignedBotIds, pinnedBotIds, visibleBots],
+ );
+ const pinnedGroupIds = useMemo(
+ () => new Set(pinnedItems.filter((item) => item.kind === "group").map((item) => item.id)),
+ [pinnedItems],
+ );
+ const assignedGroupIds = useMemo(
+ () => new Set(sections.flatMap((section) => section.groupIds ?? [])),
+ [sections],
+ );
+ const groupsBySection = useMemo(
+ () =>
+ new Map(
+ sections.map((section) => [
+ section.id,
+ (section.groupIds ?? [])
+ .map((id) => visibleGroups.find((group) => group.id === id))
+ .filter(
+ (group): group is Group => group !== undefined && !pinnedGroupIds.has(group.id),
+ ),
+ ]),
+ ),
+ [pinnedGroupIds, sections, visibleGroups],
+ );
+ const unassignedGroups = useMemo(
+ () =>
+ visibleGroups.filter(
+ (group) => !assignedGroupIds.has(group.id) && !pinnedGroupIds.has(group.id),
+ ),
+ [assignedGroupIds, pinnedGroupIds, visibleGroups],
+ );
+ const handleDragEnd = ({ draggableId, source, destination, type }: DropResult) => {
+ if (!destination) return;
+ if (type === "roster-section") {
+ useRosterStore.getState().reorderSections(source.index, destination.index);
+ return;
+ }
+ if (type === "roster-group") {
+ const groupId = parseRosterGroupDropId(draggableId);
+ if (!groupId) return;
+ if (destination.droppableId.startsWith("section-groups:")) {
+ useRosterStore
+ .getState()
+ .moveGroupToSection(
+ groupId,
+ destination.droppableId.slice("section-groups:".length),
+ destination.index,
+ );
+ } else if (destination.droppableId === "roster-unassigned-groups") {
+ useRosterStore.getState().moveGroupToSection(groupId, null, destination.index);
+ }
+ return;
+ }
+ const botId = parseRosterBotDragId(draggableId);
+ if (botId && destination.droppableId.startsWith("section:")) {
+ useRosterStore
+ .getState()
+ .moveBotToSection(
+ botId,
+ destination.droppableId.slice("section:".length),
+ destination.index,
+ );
+ } else if (botId && destination.droppableId === "roster-unassigned") {
+ useRosterStore.getState().moveBotToSection(botId, null, destination.index);
}
- finishDrag();
};
// Remember the chat route the selected bot lands on, so re-selecting the
@@ -433,11 +657,16 @@ export default function BotRosterSidebar() {
};
const [newBotOpen, setNewBotOpen] = useState(false);
+ const [newGroupOpen, setNewGroupOpen] = useState(false);
const [pendingCreatedBotId, setPendingCreatedBotId] = useState<string | null>(null);
const handleNewBot = () => setNewBotOpen(true);
+ const handleNewGroup = () => setNewGroupOpen(true);
const handleCreateBot = async ({ name, avatar }: { name: string; avatar: BotAvatar }) => {
if (environmentId === null) {
- toastManager.add({ type: "error", title: "Connect an environment first" });
+ toastManager.add({
+ type: "error",
+ title: "Connect an environment first",
+ });
return;
}
const botId = BotId.make(`bot-${randomUUID()}`);
@@ -465,6 +694,44 @@ export default function BotRosterSidebar() {
setPendingCreatedBotId(botId);
};
+ const handleCreateGroup = async (input: NewGroupInput) => {
+ if (environmentId === null) {
+ toastManager.add({
+ type: "error",
+ title: "Connect an environment first",
+ });
+ return;
+ }
+ const groupId = GroupId.make(`group-${randomUUID()}`);
+ const result = await createGroupCommand({
+ environmentId,
+ input: {
+ groupId,
+ name: input.name,
+ bossBotId: BotId.make(input.bossBotId),
+ specialistBotIds: input.specialistBotIds.map((botId) => BotId.make(botId)),
+ },
+ });
+ if (result._tag === "Failure") {
+ toastManager.add({ type: "error", title: "Could not create group" });
+ return;
+ }
+ setNewGroupOpen(false);
+ void navigate({ to: "/groups/$groupId", params: { groupId } });
+ };
+
+ const handleNewSection = () => {
+ const name = window.prompt("Section name");
+ if (name) useRosterStore.getState().createSection(name);
+ };
+
+ const handleSelectGroup = (group: Group) => {
+ void navigate({ to: "/groups/$groupId", params: { groupId: group.id } });
+ };
+
+ const isPinned = (item: RosterItemRef) =>
+ pinnedItems.some((candidate) => candidate.kind === item.kind && candidate.id === item.id);
+
useEffect(() => {
if (pendingCreatedBotId === null) return;
const bot = bots.find((candidate) => candidate.id === pendingCreatedBotId);
@@ -477,7 +744,11 @@ export default function BotRosterSidebar() {
return (
<>
- <RosterSidebarHeader onNewBot={handleNewBot} />
+ <RosterSidebarHeader
+ onNewBot={handleNewBot}
+ onNewGroup={handleNewGroup}
+ onNewSection={handleNewSection}
+ />
<SidebarContent
className="gap-0"
fixedHeader={
@@ -508,138 +779,370 @@ export default function BotRosterSidebar() {
</div>
) : (
<>
- {/* Icon-collapsed rail: every visible bot, recency order. */}
+ {/* Icon-collapsed rail: groups first, then every visible bot. */}
<SidebarGroup className="hidden items-center gap-1 px-0 pt-1 group-data-[collapsible=icon]:flex">
<ul data-testid="roster-rail" className="flex flex-col items-center gap-1">
- {strip.map((bot) => (
+ {visibleGroups.map((group) => (
+ <li key={group.id} className="list-none">
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <button
+ type="button"
+ aria-current={pathname === `/groups/${group.id}` || undefined}
+ onClick={() =>
+ void navigate({
+ to: "/groups/$groupId",
+ params: { groupId: group.id },
+ })
+ }
+ className={cn(
+ "flex size-9 items-center justify-center rounded-lg outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ pathname === `/groups/${group.id}`
+ ? "bg-sidebar-row-active"
+ : "hover:bg-sidebar-row-hover",
+ )}
+ >
+ <GroupMemberStack group={group} bots={bots} sizeClassName="size-5" />
+ </button>
+ }
+ />
+ <TooltipPopup side="right">{group.name}</TooltipPopup>
+ </Tooltip>
+ </li>
+ ))}
+ {visibleBots.map((bot) => (
<li key={bot.id} className="list-none">
<RailBotButton
bot={bot}
- isActive={selectedBotId === bot.id}
+ isActive={!groupRouteActive && selectedBotId === bot.id}
onSelect={handleSelect}
/>
</li>
))}
</ul>
</SidebarGroup>
- <DndContext
- collisionDetection={closestCenter}
- sensors={sensors}
- modifiers={[restrictToFirstScrollableAncestor]}
- onDragStart={handleDragStart}
- onDragOver={handleDragOver}
- onDragCancel={finishDrag}
- onDragEnd={handleDragEnd}
- >
- {pinnedBots.length > 0 || activeBotId !== null ? (
- <SidebarGroup className="px-4 pb-3 pt-2 group-data-[collapsible=icon]:hidden">
- <RosterDropZone
- id="pinned-zone"
- className="min-h-24 rounded-xl transition-colors data-[drag-over=true]:bg-sidebar-row-hover"
+ <DragDropContext onDragEnd={handleDragEnd}>
+ {pinnedItems.length > 0 ? (
+ <SidebarGroup className="px-[var(--sidebar-content-inset)] pb-3 pt-3 group-data-[collapsible=icon]:hidden">
+ <div
+ className="flex justify-center gap-2 overflow-x-auto px-2 py-1"
+ role="list"
+ aria-label="Pinned bots and groups"
>
- <SortableContext
- items={pinnedBots.map((bot) => bot.id)}
- strategy={rectSortingStrategy}
- >
- <ul
- data-testid="roster-strip"
- className={cn(
- "grid min-h-24 place-items-center gap-x-1 gap-y-2",
- pinnedBots.length === 1 ? "grid-cols-1" : "grid-cols-3",
- )}
- >
- {pinnedBots.map((bot) => (
- <BotStripTile
- key={bot.id}
- bot={bot}
- isActive={selectedBotId === bot.id}
- onSelect={handleSelect}
- />
- ))}
- </ul>
- </SortableContext>
- </RosterDropZone>
+ {pinnedItems.map((item) => (
+ <PinnedRosterItem
+ key={`${item.kind}:${item.id}`}
+ item={item}
+ bots={bots}
+ groups={groups}
+ onSelectBot={handleSelect}
+ onSelectGroup={handleSelectGroup}
+ />
+ ))}
+ </div>
</SidebarGroup>
) : null}
<SidebarGroup className="px-[var(--sidebar-content-inset)] pb-1 pt-1 group-data-[collapsible=icon]:hidden">
- <RosterDropZone
- id="unpinned-zone"
- className="min-h-12 rounded-lg transition-colors data-[drag-over=true]:bg-sidebar-row-hover"
- >
- <SortableContext
- items={unpinnedBots.map((bot) => bot.id)}
- strategy={verticalListSortingStrategy}
- >
- <div className="flex flex-col gap-2">
- {groupSections.map((section) => (
- <section key={section.id} aria-label={section.name}>
- <div className="mb-0.5 flex items-baseline gap-2 px-2 py-0.5">
- {section.id === "unassigned" ? (
- <span className="text-[13px] font-medium text-sidebar-muted-foreground">
- {section.name}
- </span>
- ) : (
- <button
- type="button"
- aria-current={pathname === `/groups/${section.id}` || undefined}
- className="rounded text-[13px] font-medium text-sidebar-muted-foreground outline-none hover:text-sidebar-foreground focus-visible:ring-2 focus-visible:ring-ring"
- onClick={() =>
- void navigate({
- to: "/groups/$groupId",
- params: { groupId: section.id },
- })
- }
+ <Droppable droppableId="roster-sections" type="roster-section">
+ {(sectionsProvided) => (
+ <div ref={sectionsProvided.innerRef} {...sectionsProvided.droppableProps}>
+ {sections.map((section, sectionIndex) => {
+ const sectionBots = botsBySection.get(section.id) ?? [];
+ const sectionGroups = groupsBySection.get(section.id) ?? [];
+ const collapsed = query.length === 0 && section.collapsed;
+ return (
+ <Draggable
+ key={section.id}
+ draggableId={`section:${section.id}`}
+ index={sectionIndex}
+ isDragDisabled={query.length > 0}
+ >
+ {(sectionProvided, sectionSnapshot) => (
+ <section
+ ref={sectionProvided.innerRef}
+ className={cn(
+ "mb-1 rounded-lg",
+ sectionSnapshot.isDragging && "bg-sidebar shadow-xl",
+ )}
+ {...sectionProvided.draggableProps}
>
- {section.name}
- </button>
+ <div
+ className="relative flex h-8 items-center rounded-md hover:bg-sidebar-row-hover"
+ onContextMenu={(event) => {
+ event.preventDefault();
+ event.currentTarget
+ .querySelector<HTMLButtonElement>("[data-section-actions]")
+ ?.click();
+ }}
+ >
+ <button
+ type="button"
+ aria-expanded={!collapsed}
+ onClick={() =>
+ useRosterStore.getState().toggleSection(section.id)
+ }
+ className="flex min-w-0 flex-1 cursor-grab items-center gap-1.5 px-2 text-left text-xs font-medium text-sidebar-muted-foreground active:cursor-grabbing"
+ {...sectionProvided.dragHandleProps}
+ >
+ {collapsed ? (
+ <ChevronRightIcon className="size-3.5" />
+ ) : (
+ <ChevronDownIcon className="size-3.5" />
+ )}
+ <span className="truncate">{section.name}</span>
+ <span className="tabular-nums">
+ {sectionBots.length + sectionGroups.length}
+ </span>
+ </button>
+ <Menu>
+ <MenuTrigger
+ render={
+ <button
+ type="button"
+ data-section-actions
+ aria-label={`Actions for ${section.name}`}
+ className="absolute right-2 top-1/2 size-px -translate-y-1/2 overflow-hidden opacity-0 outline-none focus-visible:size-7 focus-visible:overflow-visible focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-ring"
+ />
+ }
+ />
+ <MenuPopup align="end">
+ <MenuItem
+ variant="destructive"
+ onClick={() =>
+ useRosterStore.getState().deleteSection(section.id)
+ }
+ >
+ <Trash2Icon />
+ Delete section
+ </MenuItem>
+ </MenuPopup>
+ </Menu>
+ </div>
+ <Droppable
+ droppableId={`section-groups:${section.id}`}
+ type="roster-group"
+ >
+ {(provided, snapshot) => (
+ <div
+ ref={provided.innerRef}
+ role="list"
+ aria-label={`${section.name} groups`}
+ data-drag-over={snapshot.isDraggingOver || undefined}
+ className={cn(
+ "rounded-lg data-[drag-over=true]:bg-sidebar-row-hover",
+ collapsed
+ ? "min-h-2"
+ : sectionGroups.length > 0
+ ? "min-h-10"
+ : "min-h-1",
+ )}
+ {...provided.droppableProps}
+ >
+ {!collapsed
+ ? sectionGroups.map((group, index) => (
+ <GroupRosterRow
+ key={group.id}
+ group={group}
+ bots={bots}
+ index={index}
+ sections={sections}
+ dragDisabled={query.length > 0}
+ isActive={pathname === `/groups/${group.id}`}
+ onSelect={() => handleSelectGroup(group)}
+ pinned={false}
+ onPin={(pinned) =>
+ useRosterStore.getState().setItemPinned(
+ {
+ kind: "group",
+ id: group.id,
+ },
+ pinned,
+ )
+ }
+ onMove={(sectionId) =>
+ useRosterStore
+ .getState()
+ .moveGroupToSection(group.id, sectionId)
+ }
+ />
+ ))
+ : null}
+ {provided.placeholder}
+ </div>
+ )}
+ </Droppable>
+ <Droppable droppableId={`section:${section.id}`} type="roster-bot">
+ {(provided, snapshot) => (
+ <div
+ ref={provided.innerRef}
+ role="list"
+ aria-label={section.name}
+ data-drag-over={snapshot.isDraggingOver || undefined}
+ className={cn(
+ "rounded-lg data-[drag-over=true]:bg-sidebar-row-hover",
+ collapsed ? "min-h-2" : "min-h-10",
+ )}
+ {...provided.droppableProps}
+ >
+ {!collapsed
+ ? sectionBots.map((bot, index) => (
+ <BotRosterRow
+ key={bot.id}
+ bot={bot}
+ index={index}
+ lastMessage={lastMessageByBotId[bot.id] ?? null}
+ isActive={
+ !groupRouteActive && selectedBotId === bot.id
+ }
+ onSelect={handleSelect}
+ pinned={isPinned({
+ kind: "bot",
+ id: bot.id,
+ })}
+ sections={sections}
+ onPin={(pinned) =>
+ useRosterStore
+ .getState()
+ .setItemPinned(
+ { kind: "bot", id: bot.id },
+ pinned,
+ )
+ }
+ onMove={(sectionId) =>
+ useRosterStore
+ .getState()
+ .moveBotToSection(bot.id, sectionId)
+ }
+ dragDisabled={query.length > 0}
+ />
+ ))
+ : null}
+ {provided.placeholder}
+ </div>
+ )}
+ </Droppable>
+ </section>
)}
- </div>
- <ul className="flex min-h-12 flex-col gap-px">
- {section.bots.map((bot) => (
- <BotRosterRow
- key={bot.id}
- bot={bot}
- lastMessage={lastMessageByBotId[bot.id] ?? null}
- isActive={selectedBotId === bot.id}
- onSelect={handleSelect}
- />
- ))}
- </ul>
- </section>
+ </Draggable>
+ );
+ })}
+ {sectionsProvided.placeholder}
+ </div>
+ )}
+ </Droppable>
+ <div className="flex h-8 items-center gap-1.5 px-2 text-xs font-medium text-sidebar-muted-foreground">
+ <ChevronDownIcon className="size-3.5" />
+ <span>Unassigned</span>
+ <span className="tabular-nums">
+ {unassignedBots.length + unassignedGroups.length}
+ </span>
+ </div>
+ <Droppable droppableId="roster-unassigned-groups" type="roster-group">
+ {(provided, snapshot) => (
+ <div
+ ref={provided.innerRef}
+ role="list"
+ aria-label="Unassigned groups"
+ data-drag-over={snapshot.isDraggingOver || undefined}
+ className="min-h-1 rounded-lg data-[drag-over=true]:bg-sidebar-row-hover"
+ {...provided.droppableProps}
+ >
+ {unassignedGroups.map((group, index) => (
+ <GroupRosterRow
+ key={group.id}
+ group={group}
+ bots={bots}
+ index={index}
+ sections={sections}
+ dragDisabled={query.length > 0}
+ isActive={pathname === `/groups/${group.id}`}
+ onSelect={() => handleSelectGroup(group)}
+ pinned={false}
+ onPin={(pinned) =>
+ useRosterStore
+ .getState()
+ .setItemPinned({ kind: "group", id: group.id }, pinned)
+ }
+ onMove={(sectionId) =>
+ useRosterStore.getState().moveGroupToSection(group.id, sectionId)
+ }
+ />
))}
+ {provided.placeholder}
</div>
- </SortableContext>
- {unpinnedBots.length === 0 && pinnedBots.length === 0 ? (
- <div className="px-2 py-6 text-center text-sm text-sidebar-muted-foreground">
- No bots match
+ )}
+ </Droppable>
+ <Droppable droppableId="roster-unassigned" type="roster-bot">
+ {(provided, snapshot) => (
+ <div
+ ref={provided.innerRef}
+ role="list"
+ aria-label="Unassigned"
+ data-drag-over={snapshot.isDraggingOver || undefined}
+ className="min-h-10 rounded-lg data-[drag-over=true]:bg-sidebar-row-hover"
+ {...provided.droppableProps}
+ >
+ {unassignedBots.map((bot, index) => (
+ <BotRosterRow
+ key={bot.id}
+ bot={bot}
+ index={index}
+ lastMessage={lastMessageByBotId[bot.id] ?? null}
+ isActive={!groupRouteActive && selectedBotId === bot.id}
+ onSelect={handleSelect}
+ pinned={isPinned({ kind: "bot", id: bot.id })}
+ sections={sections}
+ onPin={(pinned) =>
+ useRosterStore
+ .getState()
+ .setItemPinned({ kind: "bot", id: bot.id }, pinned)
+ }
+ onMove={(sectionId) =>
+ useRosterStore.getState().moveBotToSection(bot.id, sectionId)
+ }
+ dragDisabled={query.length > 0}
+ />
+ ))}
+ {provided.placeholder}
</div>
- ) : null}
- </RosterDropZone>
+ )}
+ </Droppable>
+ {visibleBots.length === 0 && visibleGroups.length === 0 ? (
+ <div className="px-2 py-6 text-center text-sm text-sidebar-muted-foreground">
+ No bots match
+ </div>
+ ) : null}
</SidebarGroup>
- <DragOverlay modifiers={[snapCenterToCursor]}>
- {activeBot ? <BotDragOverlay bot={activeBot} /> : null}
- </DragOverlay>
- </DndContext>
+ </DragDropContext>
</>
)}
</SidebarContent>
- {/* Rail new-bot sits above the footer, like the expanded header's plus. */}
+ {/* Rail create menu sits above the footer, like the expanded header's plus. */}
<div className="hidden shrink-0 flex-col items-center pb-1 group-data-[collapsible=icon]:flex">
- <Tooltip>
- <TooltipTrigger
+ <Menu>
+ <MenuTrigger
render={
<button
type="button"
- aria-label="New bot"
- onClick={handleNewBot}
+ aria-label="Create"
className="flex size-9 cursor-pointer items-center justify-center rounded-lg text-sidebar-muted-foreground outline-none select-none hover:bg-sidebar-row-hover hover:text-sidebar-foreground focus-visible:ring-2 focus-visible:ring-ring"
>
<PlusIcon className="size-4" />
</button>
}
/>
- <TooltipPopup side="right">New bot</TooltipPopup>
- </Tooltip>
+ <MenuPopup align="end" side="right">
+ <MenuItem onClick={handleNewBot}>
+ <BotIcon />
+ New bot
+ </MenuItem>
+ <MenuItem onClick={handleNewGroup}>
+ <UsersIcon />
+ New group
+ </MenuItem>
+ </MenuPopup>
+ </Menu>
</div>
{newBotOpen ? (
<NewBotDialog
@@ -648,6 +1151,14 @@ export default function BotRosterSidebar() {
onCreate={(input) => void handleCreateBot(input)}
/>
) : null}
+ {newGroupOpen ? (
+ <NewGroupDialog
+ open
+ bots={bots}
+ onOpenChange={setNewGroupOpen}
+ onCreate={(input) => void handleCreateGroup(input)}
+ />
+ ) : null}
<SidebarChromeFooter />
</>
);
diff --git a/apps/web/src/components/roster/BotThreadLanding.tsx b/apps/web/src/components/roster/BotThreadLanding.tsx
index 8bd29e457..cf0b2a217 100644
--- a/apps/web/src/components/roster/BotThreadLanding.tsx
+++ b/apps/web/src/components/roster/BotThreadLanding.tsx
@@ -5,6 +5,7 @@ import { useEffect, useMemo, useState } from "react";
import { usePrimarySettings } from "../../hooks/useSettings";
import { selectOpenBotInboxItems } from "../../botInbox";
+import { canManageChannels, connectedChannelBinding } from "../../channelAccess";
import {
getCustomModelOptionsByInstance,
resolveAppModelSelectionState,
@@ -20,8 +21,10 @@ import { useThreadActivities } from "../../state/entities";
import { primaryServerProvidersAtom, serverEnvironment } from "../../state/server";
import { environmentSnapshotAtom } from "../../state/shell";
import { useEnvironmentQuery } from "../../state/query";
+import { useEnvironmentSessionState } from "../../state/session";
import { useAtomCommand } from "../../state/use-atom-command";
import { openSettings } from "../../settingsDialogStore";
+import { Button } from "../ui/button";
import { SidebarInset } from "../ui/sidebar";
import { toastManager } from "../ui/toast";
import ChatMarkdown from "../ChatMarkdown";
@@ -47,9 +50,61 @@ import { useRosterPendingApproval } from "./useRosterPendingApproval";
const NO_ENVIRONMENT = "" as EnvironmentId;
+function ChannelSendApproval({
+ environmentId,
+ botId,
+ origin,
+ threadId,
+ messageId,
+ sent,
+}: {
+ readonly environmentId: EnvironmentId;
+ readonly botId: BotId;
+ readonly origin: ChannelMessageOrigin;
+ readonly threadId: ThreadId;
+ readonly messageId: MessageId;
+ readonly sent: boolean;
+}) {
+ const send = useAtomCommand(botEnvironment.channels.send, { reportFailure: false });
+ const [busy, setBusy] = useState(false);
+ const [submitted, setSubmitted] = useState(false);
+ const delivered = sent || submitted;
+ const label = channelProviderLabel(origin.provider);
+ return (
+ <div className="mt-2 flex items-center gap-2 rounded-lg border border-border bg-muted/30 px-3 py-2 text-xs">
+ <span className="min-w-0 flex-1 text-muted-foreground">
+ {delivered ? `Sent to ${label}` : `Send this reply to ${label}?`}
+ </span>
+ {!delivered ? (
+ <Button
+ size="xs"
+ disabled={busy}
+ onClick={() => {
+ setBusy(true);
+ void send({
+ environmentId,
+ input: { botId, threadId, messageId },
+ }).then((result) => {
+ setBusy(false);
+ if (result._tag === "Failure") {
+ toastManager.add({ type: "error", title: `Could not send to ${label}` });
+ } else {
+ setSubmitted(true);
+ }
+ });
+ }}
+ >
+ {busy ? "Sending" : "Send"}
+ </Button>
+ ) : null}
+ </div>
+ );
+}
+
export function BotThreadLanding({ botId }: { readonly botId: string }) {
const navigate = useNavigate();
const environmentId = usePrimaryEnvironmentId();
+ const channelSession = useEnvironmentSessionState(environmentId ?? ("" as EnvironmentId));
const settings = usePrimarySettings();
const providers = useAtomValue(primaryServerProvidersAtom);
const updateBot = useAtomCommand(botEnvironment.update, { reportFailure: false });
@@ -159,7 +214,7 @@ export function BotThreadLanding({ botId }: { readonly botId: string }) {
<h1 className="text-lg font-medium">Message {bot.name}</h1>
</div>
) : (
- messages.map((message) =>
+ messages.map((message, messageIndex) =>
message.role === "assistant" ? (
<div
key={message.id}
@@ -182,14 +237,24 @@ export function BotThreadLanding({ botId }: { readonly botId: string }) {
text={message.text}
threadRef={runtime.linkedThreadRef ?? undefined}
/>
- {message.attachments?.length ? (
- <div className="mt-2">
- <BotMessageAttachments
- attachments={message.attachments}
- environmentId={environmentId ?? NO_ENVIRONMENT}
- />
- </div>
- ) : null}
+ {canManageChannelBindings && environmentId && runtime.linkedThreadRef
+ ? (() => {
+ const origin = channelOriginForAssistantMessage(messages, messageIndex);
+ const binding = origin
+ ? connectedChannelBinding(bot.channelBindings, origin.provider)
+ : undefined;
+ return origin && binding ? (
+ <ChannelSendApproval
+ environmentId={environmentId}
+ botId={BotId.make(bot.id)}
+ origin={origin}
+ threadId={runtime.linkedThreadRef.threadId}
+ messageId={message.id}
+ sent={binding.sentMessageIds.includes(message.id)}
+ />
+ ) : null;
+ })()
+ : null}
</div>
</div>
) : (
diff --git a/apps/web/src/components/roster/GroupDetailsPanel.test.tsx b/apps/web/src/components/roster/GroupDetailsPanel.test.tsx
new file mode 100644
index 000000000..44fd019ca
--- /dev/null
+++ b/apps/web/src/components/roster/GroupDetailsPanel.test.tsx
@@ -0,0 +1,31 @@
+// @effect-diagnostics nodeBuiltinImport:off - The route contract reads its source.
+import * as NodeFS from "node:fs";
+
+import { describe, expect, it } from "vite-plus/test";
+
+describe("GroupDetailsPanel", () => {
+ it("uses the bot sidebar behavior and group management commands", () => {
+ const source = NodeFS.readFileSync(new URL("./GroupDetailsPanel.tsx", import.meta.url), "utf8");
+ expect(source).toContain('resolveShortcutCommand(event, keybindings) !== "rightPanel.toggle"');
+ expect(source).toContain("RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY");
+ expect(source).toContain("botEnvironment.groups.rename");
+ expect(source).toContain("botEnvironment.groups.assignMember");
+ expect(source).toContain("botEnvironment.groups.unassignMember");
+ expect(source).toContain("botEnvironment.groups.setBoss");
+ expect(source).toContain("botEnvironment.groups.delete");
+ expect(source).toContain("members.length <= 2");
+ expect(source).not.toContain("GroupPeopleSettings");
+ expect(source).not.toContain("Invite people");
+ });
+
+ it("mounts beside the group conversation", () => {
+ const source = NodeFS.readFileSync(
+ new URL("../../routes/_chat.groups.$groupId.tsx", import.meta.url),
+ "utf8",
+ );
+ expect(source).toContain("<GroupThreadLanding");
+ expect(source).toContain("<GroupDetailsPanel");
+ expect(source).toContain("onDeleted=");
+ expect(source).not.toContain("environmentPeopleAtom");
+ });
+});
diff --git a/apps/web/src/components/roster/GroupDetailsPanel.tsx b/apps/web/src/components/roster/GroupDetailsPanel.tsx
new file mode 100644
index 000000000..4fe184e36
--- /dev/null
+++ b/apps/web/src/components/roster/GroupDetailsPanel.tsx
@@ -0,0 +1,388 @@
+import { useAtomValue } from "@effect/atom-react";
+import { BotId, GroupId, isGroupBotMember, type EnvironmentId } from "@t3tools/contracts";
+import { Cancel01Icon, PanelRightCloseIcon, PanelRightIcon } from "@hugeicons/core-free-icons";
+import { BotIcon, Trash2Icon } from "lucide-react";
+import { useEffect, useReducer, useState, type ReactNode } from "react";
+
+import { resolveShortcutCommand, shortcutLabelForCommand } from "../../keybindings";
+import { RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY } from "../../rightPanelLayout";
+import { botEnvironment } from "../../state/bots";
+import { useAtomCommand } from "../../state/use-atom-command";
+import { primaryServerKeybindingsAtom } from "../../state/server";
+import { SettingsRow } from "../settings/settingsLayout";
+import { AppIcon } from "../ui/app-icon";
+import { Button } from "../ui/button";
+import { Input } from "../ui/input";
+import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
+import { Sheet, SheetClose, SheetPopup, SheetTitle } from "../ui/sheet";
+import { toastManager } from "../ui/toast";
+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
+import { GroupMemberStack } from "./GroupMemberStack";
+import { groupBotMembers, groupContainsBot } from "./roster.logic";
+import type { Bot, Group } from "./types";
+
+type PanelState = {
+ readonly desktopOpen: boolean;
+ readonly mobileOpen: boolean;
+};
+type PanelAction =
+ | { readonly type: "toggle-desktop" }
+ | { readonly type: "toggle-mobile" }
+ | { readonly type: "set-mobile"; readonly open: boolean };
+
+function reducePanelState(state: PanelState, action: PanelAction): PanelState {
+ if (action.type === "toggle-desktop") return { ...state, desktopOpen: !state.desktopOpen };
+ if (action.type === "toggle-mobile") return { ...state, mobileOpen: !state.mobileOpen };
+ return { ...state, mobileOpen: action.open };
+}
+
+function GroupEditor({
+ environmentId,
+ group,
+ bots,
+ onDeleted,
+}: {
+ readonly environmentId: EnvironmentId;
+ readonly group: Group;
+ readonly bots: readonly Bot[];
+ readonly onDeleted: () => void;
+}) {
+ const renameGroup = useAtomCommand(botEnvironment.groups.rename, {
+ reportFailure: false,
+ });
+ const deleteGroup = useAtomCommand(botEnvironment.groups.delete, {
+ reportFailure: false,
+ });
+ const assignMember = useAtomCommand(botEnvironment.groups.assignMember, {
+ reportFailure: false,
+ });
+ const unassignMember = useAtomCommand(botEnvironment.groups.unassignMember, {
+ reportFailure: false,
+ });
+ const setBoss = useAtomCommand(botEnvironment.groups.setBoss, {
+ reportFailure: false,
+ });
+ const [name, setName] = useState(group.name);
+ const [newMemberId, setNewMemberId] = useState("");
+ const [busy, setBusy] = useState(false);
+ const activeBots = bots.filter((bot) => bot.archivedAt === null);
+ const members = groupBotMembers(group, activeBots);
+ const availableBots = activeBots.filter((bot) => !groupContainsBot(group, bot.id));
+
+ useEffect(() => setName(group.name), [group.name]);
+ useEffect(() => {
+ if (!availableBots.some((bot) => bot.id === newMemberId)) setNewMemberId("");
+ }, [availableBots, newMemberId]);
+
+ 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;
+ };
+
+ return (
+ <div className="min-h-0 flex-1 overflow-y-auto px-5 pb-6">
+ <div className="flex flex-col items-center gap-3 pb-7 pt-6">
+ <GroupMemberStack group={group} bots={bots} sizeClassName="size-16" />
+ <span className="text-sm text-muted-foreground">{members.length} bots</span>
+ </div>
+ <div className="space-y-5">
+ <label className="block space-y-2 text-sm font-medium">
+ Name
+ <div className="flex gap-2">
+ <Input
+ aria-label="Group name"
+ className="w-0 min-w-0 flex-1"
+ value={name}
+ onChange={(event) => setName(event.currentTarget.value)}
+ />
+ <Button
+ size="sm"
+ disabled={busy || !name.trim() || name.trim() === group.name}
+ onClick={() =>
+ void run(
+ () =>
+ renameGroup({
+ environmentId,
+ input: {
+ groupId: GroupId.make(group.id),
+ name: name.trim(),
+ },
+ }),
+ "Could not rename group",
+ )
+ }
+ >
+ Save
+ </Button>
+ </div>
+ </label>
+ <label className="block space-y-2 text-sm font-medium">
+ Boss
+ <Select
+ value={group.bossBotId ?? ""}
+ onValueChange={(botId) => {
+ if (!botId || botId === group.bossBotId) return;
+ void run(
+ () =>
+ setBoss({
+ environmentId,
+ input: {
+ groupId: GroupId.make(group.id),
+ bossBotId: BotId.make(botId),
+ unassignPreviousBoss: false,
+ },
+ }),
+ "Could not change group boss",
+ );
+ }}
+ >
+ <SelectTrigger aria-label="Group boss" className="w-full">
+ <SelectValue>
+ {members.find((bot) => bot.id === group.bossBotId)?.name ?? "Choose boss"}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectPopup>
+ {members.map((bot) => (
+ <SelectItem key={bot.id} value={bot.id}>
+ {bot.name}
+ </SelectItem>
+ ))}
+ </SelectPopup>
+ </Select>
+ </label>
+ <section className="space-y-2" aria-labelledby="group-bots-heading">
+ <h3 id="group-bots-heading" className="text-sm font-medium">
+ Bots
+ </h3>
+ <div className="space-y-1 rounded-lg border p-2">
+ {members.map((bot) => {
+ const role = group.members.find(
+ (member) => isGroupBotMember(member) && member.botId === bot.id,
+ );
+ return (
+ <div key={bot.id} className="flex min-h-9 items-center gap-2 rounded-md px-1">
+ <span className="min-w-0 flex-1 truncate text-sm">{bot.name}</span>
+ <span className="text-xs capitalize text-muted-foreground">
+ {role?.kind === "bot" ? role.role : "specialist"}
+ </span>
+ <Button
+ aria-label={`Remove ${bot.name} from ${group.name}`}
+ disabled={
+ busy || role?.kind !== "bot" || role.role === "boss" || members.length <= 2
+ }
+ size="icon-sm"
+ variant="ghost"
+ onClick={() =>
+ void run(
+ () =>
+ unassignMember({
+ environmentId,
+ input: {
+ groupId: GroupId.make(group.id),
+ botId: BotId.make(bot.id),
+ },
+ }),
+ `Could not remove ${bot.name}`,
+ )
+ }
+ >
+ <Trash2Icon />
+ </Button>
+ </div>
+ );
+ })}
+ </div>
+ <div className="flex gap-2">
+ <Select value={newMemberId} onValueChange={(value) => value && setNewMemberId(value)}>
+ <SelectTrigger aria-label="Add bot" className="min-w-0 flex-1">
+ <SelectValue placeholder="Choose bot" />
+ </SelectTrigger>
+ <SelectPopup>
+ {availableBots.map((bot) => (
+ <SelectItem key={bot.id} value={bot.id}>
+ {bot.name}
+ </SelectItem>
+ ))}
+ </SelectPopup>
+ </Select>
+ <Button
+ aria-label="Add bot to group"
+ disabled={busy || !newMemberId}
+ size="icon"
+ variant="outline"
+ onClick={() =>
+ void run(
+ () =>
+ assignMember({
+ environmentId,
+ input: {
+ groupId: GroupId.make(group.id),
+ botId: BotId.make(newMemberId),
+ role: "specialist",
+ },
+ }),
+ "Could not add bot",
+ ).then((success) => success && setNewMemberId(""))
+ }
+ >
+ <BotIcon />
+ </Button>
+ </div>
+ </section>
+ </div>
+ <div className="mt-6 -mx-2">
+ <SettingsRow
+ title="Delete group"
+ control={
+ <Button
+ disabled={busy}
+ variant="destructive"
+ onClick={() =>
+ void run(
+ () =>
+ deleteGroup({
+ environmentId,
+ input: { groupId: GroupId.make(group.id) },
+ }),
+ "Could not delete group",
+ ).then((success) => success && onDeleted())
+ }
+ >
+ Delete
+ </Button>
+ }
+ />
+ </div>
+ </div>
+ );
+}
+
+export function GroupDetailsPanel(props: {
+ readonly environmentId: EnvironmentId;
+ readonly group: Group;
+ readonly bots: readonly Bot[];
+ readonly onDeleted: () => void;
+}) {
+ const keybindings = useAtomValue(primaryServerKeybindingsAtom);
+ const [panelState, dispatchPanel] = useReducer(reducePanelState, {
+ desktopOpen: true,
+ mobileOpen: false,
+ });
+ const shortcutLabel = shortcutLabelForCommand(keybindings, "rightPanel.toggle");
+
+ useEffect(() => {
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.defaultPrevented || event.repeat) return;
+ if (
+ event.target instanceof HTMLElement &&
+ event.target.closest("[data-keybinding-capture]")
+ ) {
+ return;
+ }
+ if (resolveShortcutCommand(event, keybindings) !== "rightPanel.toggle") return;
+ event.preventDefault();
+ event.stopPropagation();
+ dispatchPanel({
+ type: window.matchMedia(RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY).matches
+ ? "toggle-mobile"
+ : "toggle-desktop",
+ });
+ };
+ window.addEventListener("keydown", onKeyDown, true);
+ return () => window.removeEventListener("keydown", onKeyDown, true);
+ }, [keybindings]);
+
+ const content = (closeButton?: ReactNode) => (
+ <>
+ <header className="relative flex h-[var(--workspace-topbar-height)] shrink-0 items-center justify-center px-4">
+ <h2 className="text-sm font-medium">Group</h2>
+ <div className="absolute right-3 flex items-center">{closeButton}</div>
+ </header>
+ <GroupEditor {...props} />
+ </>
+ );
+
+ return (
+ <>
+ <aside
+ aria-hidden={!panelState.desktopOpen}
+ aria-label={`${props.group.name} group sidebar`}
+ data-testid="group-details-panel"
+ className={
+ panelState.desktopOpen
+ ? "hidden h-full w-88 shrink-0 flex-col border-l border-border bg-background min-[981px]:flex"
+ : "hidden"
+ }
+ >
+ {content(
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ aria-expanded="true"
+ aria-label={`Collapse ${props.group.name} group sidebar`}
+ size="icon-sm"
+ variant="ghost"
+ onClick={() => dispatchPanel({ type: "toggle-desktop" })}
+ >
+ <AppIcon icon={PanelRightCloseIcon} />
+ </Button>
+ }
+ />
+ <TooltipPopup side="left">
+ Collapse{shortcutLabel ? ` (${shortcutLabel})` : ""}
+ </TooltipPopup>
+ </Tooltip>,
+ )}
+ </aside>
+ {!panelState.desktopOpen ? (
+ <div className="fixed right-[var(--workspace-controls-right)] top-[var(--workspace-controls-top)] z-40 hidden h-[var(--workspace-topbar-height)] items-center min-[981px]:flex">
+ <Button
+ aria-label={`Open ${props.group.name} group sidebar`}
+ size="icon-sm"
+ variant="ghost"
+ onClick={() => dispatchPanel({ type: "toggle-desktop" })}
+ >
+ <AppIcon icon={PanelRightIcon} />
+ </Button>
+ </div>
+ ) : null}
+ <div className="fixed right-[var(--workspace-controls-right)] top-[var(--workspace-controls-top)] z-40 flex h-[var(--workspace-topbar-height)] items-center min-[981px]:hidden">
+ <Button
+ aria-label={`Open ${props.group.name} group sidebar`}
+ size="icon-sm"
+ variant="ghost"
+ onClick={() => dispatchPanel({ type: "set-mobile", open: true })}
+ >
+ <AppIcon icon={PanelRightIcon} />
+ </Button>
+ </div>
+ <Sheet
+ open={panelState.mobileOpen}
+ onOpenChange={(open) => dispatchPanel({ type: "set-mobile", open })}
+ >
+ <SheetPopup
+ className="w-[min(92vw,24rem)] pb-safe pt-safe p-0"
+ showCloseButton={false}
+ side="right"
+ >
+ <SheetTitle className="sr-only">Edit {props.group.name}</SheetTitle>
+ {content(
+ <SheetClose
+ aria-label="Close group sidebar"
+ render={<Button size="icon-sm" variant="ghost" />}
+ >
+ <AppIcon icon={Cancel01Icon} />
+ </SheetClose>,
+ )}
+ </SheetPopup>
+ </Sheet>
+ </>
+ );
+}
diff --git a/apps/web/src/components/roster/GroupMemberStack.tsx b/apps/web/src/components/roster/GroupMemberStack.tsx
new file mode 100644
index 000000000..80359b2e3
--- /dev/null
+++ b/apps/web/src/components/roster/GroupMemberStack.tsx
@@ -0,0 +1,39 @@
+import { cn } from "../../lib/utils";
+import { BotAvatarView } from "./BotAvatarView";
+import { groupBotMembers } from "./roster.logic";
+import type { Bot, Group } from "./types";
+
+export function GroupMemberStack({
+ group,
+ bots,
+ sizeClassName = "size-6",
+ className,
+}: {
+ readonly group: Group;
+ readonly bots: ReadonlyArray<Bot>;
+ readonly sizeClassName?: string;
+ readonly className?: string;
+}) {
+ const groupBots = groupBotMembers(group, bots)
+ .filter((bot) => bot.archivedAt === null)
+ .sort((a, b) => {
+ if (a.id === group.bossBotId) return -1;
+ if (b.id === group.bossBotId) return 1;
+ return 0;
+ });
+ return (
+ <div className={cn("relative inline-flex shrink-0", sizeClassName, className)}>
+ {groupBots.slice(0, 2).map((bot, index) => (
+ <BotAvatarView
+ key={bot.id}
+ avatar={bot.avatar}
+ name={bot.name}
+ className={cn(
+ "absolute size-[68%]",
+ index === 0 ? "left-0 top-0" : "bottom-0 right-0 z-10",
+ )}
+ />
+ ))}
+ </div>
+ );
+}
diff --git a/apps/web/src/components/roster/GroupThreadLanding.test.ts b/apps/web/src/components/roster/GroupThreadLanding.test.ts
new file mode 100644
index 000000000..108f4bbef
--- /dev/null
+++ b/apps/web/src/components/roster/GroupThreadLanding.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import { isCurrentGroupPerson } from "./roster.logic";
+import { resolveAvailableGroupBoss } from "./GroupThreadLanding";
+
+describe("group thread person placement", () => {
+ it("keeps legacy host messages on the right for the host", () => {
+ expect(isCurrentGroupPerson(null, "person-host", "person-host")).toBe(true);
+ });
+
+ it("puts legacy host messages on the left for a guest", () => {
+ expect(isCurrentGroupPerson(null, "person-guest", "person-host")).toBe(false);
+ });
+
+ it("puts another paired person's message on the left", () => {
+ expect(isCurrentGroupPerson("person-guest", "person-host", "person-host")).toBe(false);
+ });
+});
+
+describe("group boss availability", () => {
+ it("keeps the landing available when the configured boss is unavailable", () => {
+ expect(resolveAvailableGroupBoss([{ id: "specialist" }], "boss")).toBeNull();
+ });
+});
diff --git a/apps/web/src/components/roster/GroupThreadLanding.tsx b/apps/web/src/components/roster/GroupThreadLanding.tsx
index 1ce1c7876..b0902729a 100644
--- a/apps/web/src/components/roster/GroupThreadLanding.tsx
+++ b/apps/web/src/components/roster/GroupThreadLanding.tsx
@@ -6,6 +6,7 @@ import { useEffect, useMemo } from "react";
import { selectOpenBotInboxItems } from "../../botInbox";
import { openSettings } from "../../settingsDialogStore";
import { usePrimaryEnvironmentId } from "../../state/environments";
+import { environmentPeopleAtom } from "../../state/bots";
import { useEnvironmentQuery } from "../../state/query";
import { useThreadActivities } from "../../state/entities";
import { serverEnvironment } from "../../state/server";
@@ -26,15 +27,25 @@ import { BotMessageAttachments } from "./BotMessageAttachments";
import { BotStepMeter } from "./BotStepMeter";
import { buildBotStepMeters } from "./botStepMeter.logic";
import { useGroupPresence } from "./botPresence";
+import { groupBotMembers, isCurrentGroupPerson } from "./roster.logic";
import { useRosterStore } from "./rosterStore";
import { useGroupThreadRuntime } from "./useGroupThreadRuntime";
import { useRosterPendingApproval } from "./useRosterPendingApproval";
const NO_ENVIRONMENT = "" as EnvironmentId;
+export function resolveAvailableGroupBoss<T extends { readonly id: string }>(
+ members: ReadonlyArray<T>,
+ bossBotId: string | null,
+): T | null {
+ return members.find((bot) => bot.id === bossBotId) ?? null;
+}
+
export function GroupThreadLanding({ groupId }: { readonly groupId: string }) {
- const navigate = useNavigate();
const environmentId = usePrimaryEnvironmentId();
+ const peopleIdentity = useAtomValue(
+ environmentPeopleAtom((environmentId ?? "") as EnvironmentId),
+ );
const group = useRosterStore((state) =>
state.groups.find((candidate) => candidate.id === groupId),
);
@@ -51,14 +62,9 @@ export function GroupThreadLanding({ groupId }: { readonly groupId: string }) {
);
const snapshot = useAtomValue(environmentSnapshotAtom(environmentId ?? NO_ENVIRONMENT));
- useEffect(() => {
- if (!group) void navigate({ to: "/", replace: true });
- }, [group, navigate]);
-
if (!group) return null;
- const members = bots.filter((bot) => bot.groupId === group.id && bot.archivedAt === null);
- const boss = members.find((bot) => bot.id === group.bossBotId) ?? members[0];
- if (!boss) return null;
+ const members = groupBotMembers(group, bots).filter((bot) => bot.archivedAt === null);
+ const boss = resolveAvailableGroupBoss(members, group.bossBotId);
const working = runtime.sending || presence === "working";
const messages = visibleBotChatMessages(runtime.messages);
const pendingApproval = approvalState.pendingApproval;
@@ -82,16 +88,7 @@ export function GroupThreadLanding({ groupId }: { readonly groupId: string }) {
<div className="flex min-h-0 min-w-0 flex-1 flex-col">
<WorkspacePageHeader className="border-b border-border">
<div className="flex min-w-0 items-center gap-2">
- <div className="flex -space-x-1.5">
- {members.slice(0, 3).map((bot) => (
- <BotAvatarView
- key={bot.id}
- avatar={bot.avatar}
- name={bot.name}
- className="size-6 ring-2 ring-background"
- />
- ))}
- </div>
+ <GroupMemberStack group={group} bots={bots} />
<span className="truncate text-sm font-medium">{group.name}</span>
</div>
</WorkspacePageHeader>
@@ -108,13 +105,32 @@ export function GroupThreadLanding({ groupId }: { readonly groupId: string }) {
/>
))}
</div>
- <h1 className="text-lg font-medium">Message {group.name}</h1>
+ <h1 className="text-lg font-medium">
+ {boss ? `Message ${group.name}` : "Group boss unavailable"}
+ </h1>
</div>
) : (
messages.map((message) => {
if (message.role === "assistant") {
const respondingBot =
members.find((bot) => bot.id === message.respondingBotId) ?? boss;
+ if (!respondingBot) {
+ return (
+ <div
+ key={message.id}
+ className="max-w-[85%]"
+ data-testid="group-provider-message"
+ >
+ <div className="text-sm font-medium">Unavailable bot</div>
+ <ChatMarkdown
+ className="mt-1"
+ cwd={runtime.defaultProject?.workspaceRoot}
+ text={message.text}
+ threadRef={runtime.linkedThreadRef ?? undefined}
+ />
+ </div>
+ );
+ }
return (
<div
key={message.id}
@@ -141,6 +157,11 @@ export function GroupThreadLanding({ groupId }: { readonly groupId: string }) {
</div>
);
}
+ const current = isCurrentGroupPerson(
+ message.authorPersonId,
+ peopleIdentity.current?.id,
+ peopleIdentity.host?.id,
+ );
return (
<div key={message.id} className="flex justify-end" data-testid="group-user-message">
<div className="max-w-[78%] rounded-2xl bg-foreground/10 px-3.5 py-2 text-sm leading-6">
@@ -190,6 +211,11 @@ export function GroupThreadLanding({ groupId }: { readonly groupId: string }) {
inboxItems.some((item) => item.lastFailure === runtime.error) ? null : runtime.error
}
/>
+ {boss === null ? (
+ <div className="px-4 py-2 text-sm text-muted-foreground" role="status">
+ Choose an active group boss in the group sidebar.
+ </div>
+ ) : null}
<BotPromptComposer
botName={group.name}
draftKey={`group:${group.id}`}
@@ -198,7 +224,8 @@ export function GroupThreadLanding({ groupId }: { readonly groupId: string }) {
pendingApproval !== null ||
!runtime.groupReady ||
!runtime.bootstrapped ||
- runtime.defaultProject === null
+ runtime.defaultProject === null ||
+ boss === null
}
mentionBots={members.map((bot) => ({ id: bot.id, name: bot.name }))}
modelPicker={null}
diff --git a/apps/web/src/components/roster/NewGroupDialog.test.tsx b/apps/web/src/components/roster/NewGroupDialog.test.tsx
new file mode 100644
index 000000000..38024aa65
--- /dev/null
+++ b/apps/web/src/components/roster/NewGroupDialog.test.tsx
@@ -0,0 +1,13 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import { canCreateGroup } from "./NewGroupDialog";
+
+describe("new group", () => {
+ it("requires a name, two distinct bots, and a selected boss", () => {
+ expect(canCreateGroup("Launch crew", ["one", "two"], "one")).toBe(true);
+ expect(canCreateGroup("Launch crew", ["one"], "one")).toBe(false);
+ expect(canCreateGroup("Launch crew", ["one", "one"], "one")).toBe(false);
+ expect(canCreateGroup(" ", ["one", "two"], "one")).toBe(false);
+ expect(canCreateGroup("Launch crew", ["one", "two"], "three")).toBe(false);
+ });
+});
diff --git a/apps/web/src/components/roster/NewGroupDialog.tsx b/apps/web/src/components/roster/NewGroupDialog.tsx
new file mode 100644
index 000000000..bb9e7c188
--- /dev/null
+++ b/apps/web/src/components/roster/NewGroupDialog.tsx
@@ -0,0 +1,137 @@
+import { useEffect, useMemo, useState } from "react";
+
+import { Button } from "../ui/button";
+import { Checkbox } from "../ui/checkbox";
+import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog";
+import { Input } from "../ui/input";
+import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
+import { BotAvatarView } from "./BotAvatarView";
+import type { Bot } from "./types";
+
+export interface NewGroupInput {
+ readonly name: string;
+ readonly bossBotId: string;
+ readonly specialistBotIds: readonly string[];
+}
+
+export function canCreateGroup(
+ name: string,
+ selectedIds: readonly string[],
+ bossBotId: string,
+): boolean {
+ return (
+ name.trim().length > 0 && new Set(selectedIds).size >= 2 && selectedIds.includes(bossBotId)
+ );
+}
+
+export function NewGroupDialog({
+ open,
+ bots,
+ onOpenChange,
+ onCreate,
+}: {
+ readonly open: boolean;
+ readonly bots: readonly Bot[];
+ readonly onOpenChange: (open: boolean) => void;
+ readonly onCreate: (input: NewGroupInput) => void;
+}) {
+ const activeBots = useMemo(() => bots.filter((bot) => bot.archivedAt === null), [bots]);
+ const [name, setName] = useState("");
+ const [selectedIds, setSelectedIds] = useState<readonly string[]>(() =>
+ activeBots.slice(0, 2).map((bot) => bot.id),
+ );
+ const [bossBotId, setBossBotId] = useState(selectedIds[0] ?? "");
+ const selectedBots = activeBots.filter((bot) => selectedIds.includes(bot.id));
+
+ useEffect(() => {
+ if (!selectedIds.includes(bossBotId)) setBossBotId(selectedIds[0] ?? "");
+ }, [bossBotId, selectedIds]);
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogPopup className="max-w-lg overflow-hidden p-0" bottomStickOnMobile={false}>
+ <form
+ onSubmit={(event) => {
+ event.preventDefault();
+ if (!canCreateGroup(name, selectedIds, bossBotId)) return;
+ onCreate({
+ name: name.trim(),
+ bossBotId,
+ specialistBotIds: selectedIds.filter((id) => id !== bossBotId),
+ });
+ }}
+ >
+ <header className="border-b px-6 py-5">
+ <DialogTitle>New group</DialogTitle>
+ </header>
+ <div className="space-y-5 px-6 py-6">
+ <label className="block space-y-2 text-sm font-medium">
+ Name
+ <Input
+ autoFocus
+ aria-label="Group name"
+ maxLength={80}
+ placeholder="Group name"
+ value={name}
+ onChange={(event) => setName(event.currentTarget.value)}
+ />
+ </label>
+ <fieldset className="space-y-2">
+ <legend className="mb-2 text-sm font-medium">Bots</legend>
+ <div className="max-h-56 space-y-1 overflow-y-auto rounded-lg border p-2">
+ {activeBots.map((bot) => {
+ const checked = selectedIds.includes(bot.id);
+ return (
+ <label
+ key={bot.id}
+ className="flex min-h-10 cursor-pointer items-center gap-3 rounded-md px-2 hover:bg-muted/50"
+ >
+ <Checkbox
+ checked={checked}
+ onCheckedChange={(next) =>
+ setSelectedIds((current) =>
+ next
+ ? [...current, bot.id]
+ : current.filter((candidate) => candidate !== bot.id),
+ )
+ }
+ />
+ <BotAvatarView avatar={bot.avatar} name={bot.name} className="size-7" />
+ <span className="min-w-0 flex-1 truncate text-sm">{bot.name}</span>
+ </label>
+ );
+ })}
+ </div>
+ <p className="text-xs text-muted-foreground">Select at least two bots.</p>
+ </fieldset>
+ <label className="block space-y-2 text-sm font-medium">
+ Boss
+ <Select value={bossBotId} onValueChange={(value) => value && setBossBotId(value)}>
+ <SelectTrigger aria-label="Group boss" className="w-full">
+ <SelectValue>
+ {selectedBots.find((bot) => bot.id === bossBotId)?.name ?? "Choose boss"}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectPopup>
+ {selectedBots.map((bot) => (
+ <SelectItem key={bot.id} value={bot.id}>
+ {bot.name}
+ </SelectItem>
+ ))}
+ </SelectPopup>
+ </Select>
+ </label>
+ </div>
+ <footer className="flex justify-end gap-2 border-t bg-muted px-6 py-4">
+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button type="submit" disabled={!canCreateGroup(name, selectedIds, bossBotId)}>
+ Create group
+ </Button>
+ </footer>
+ </form>
+ </DialogPopup>
+ </Dialog>
+ );
+}
diff --git a/apps/web/src/components/roster/botConversationPresentation.test.ts b/apps/web/src/components/roster/botConversationPresentation.test.ts
index 6c8ebe60a..f9b2c7886 100644
--- a/apps/web/src/components/roster/botConversationPresentation.test.ts
+++ b/apps/web/src/components/roster/botConversationPresentation.test.ts
@@ -1,7 +1,12 @@
import { MessageId, TurnId, type OrchestrationMessage } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
-import { visibleBotChatMessages } from "./botConversationPresentation";
+import {
+ channelOriginLabel,
+ channelOriginForAssistantMessage,
+ channelProviderLabel,
+ visibleBotChatMessages,
+} from "./botConversationPresentation";
const message = (
id: string,
@@ -20,6 +25,35 @@ const message = (
}) as const;
describe("bot conversation presentation", () => {
+ it("shows the iMessage sender and maps every channel provider", () => {
+ expect(
+ channelOriginLabel({
+ provider: "imessage",
+ externalThreadId: "group-1",
+ externalSenderId: "+15551234567",
+ }),
+ ).toBe("iMessage · +15551234567");
+ expect(channelProviderLabel("telegram")).toBe("Telegram");
+ expect(channelProviderLabel("whatsapp")).toBe("WhatsApp");
+ });
+
+ it("pairs an assistant message with the nearest inbound channel message", () => {
+ const messages = [
+ message("web-user", "user", false),
+ {
+ ...message("telegram-user", "user", false),
+ channelOrigin: { provider: "telegram" as const, externalThreadId: "chat-1" },
+ },
+ message("answer", "assistant", false),
+ ];
+
+ expect(channelOriginForAssistantMessage(messages, 2)).toEqual({
+ provider: "telegram",
+ externalThreadId: "chat-1",
+ });
+ expect(channelOriginForAssistantMessage(messages, 0)).toBeNull();
+ });
+
it("keeps user messages and settled answers only", () => {
const messages = [
message("user", "user", false),
diff --git a/apps/web/src/components/roster/botConversationPresentation.ts b/apps/web/src/components/roster/botConversationPresentation.ts
index 47fd60e95..2dbd23d70 100644
--- a/apps/web/src/components/roster/botConversationPresentation.ts
+++ b/apps/web/src/components/roster/botConversationPresentation.ts
@@ -1,4 +1,31 @@
-import type { OrchestrationMessage } from "@t3tools/contracts";
+import type { ChannelMessageOrigin, OrchestrationMessage } from "@t3tools/contracts";
+
+export function channelProviderLabel(
+ provider: ChannelMessageOrigin["provider"] | "whatsapp",
+): string {
+ if (provider === "imessage") return "iMessage";
+ if (provider === "whatsapp") return "WhatsApp";
+ return "Telegram";
+}
+
+export function channelOriginLabel(origin: ChannelMessageOrigin): string {
+ const provider = channelProviderLabel(origin.provider);
+ return origin.provider === "imessage" && origin.externalSenderId
+ ? `${provider} · ${origin.externalSenderId}`
+ : provider;
+}
+
+export function channelOriginForAssistantMessage(
+ messages: ReadonlyArray<OrchestrationMessage>,
+ assistantIndex: number,
+): ChannelMessageOrigin | null {
+ if (messages[assistantIndex]?.role !== "assistant") return null;
+ for (let index = assistantIndex - 1; index >= 0; index -= 1) {
+ const message = messages[index];
+ if (message?.role === "user") return message.channelOrigin ?? null;
+ }
+ return null;
+}
/**
* Bot chat shows user messages and every completed assistant note. A turn can
diff --git a/apps/web/src/components/roster/roster.logic.test.ts b/apps/web/src/components/roster/roster.logic.test.ts
index 26b141703..306030b75 100644
--- a/apps/web/src/components/roster/roster.logic.test.ts
+++ b/apps/web/src/components/roster/roster.logic.test.ts
@@ -1,16 +1,14 @@
+import { BotId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import {
blinkDelayMs,
- buildGroupedRosterSections,
- buildRosterSections,
- buildRosterStrip,
- buildRosterTiles,
- compareRosterBots,
filterRosterBots,
+ filterRosterGroups,
DEFAULT_BLOB_COLOR,
DEFAULT_BLOB_SHAPE,
formatRosterTimestamp,
+ groupContainsBot,
isRecordableChatPath,
parseChatPath,
randomBotAvatar,
@@ -19,9 +17,12 @@ import {
resolveLatestRosterMessage,
resolveRosterBotId,
resolveRosterIndicator,
+ parseRosterBotDragId,
+ parseRosterGroupDropId,
+ rosterBotDragId,
+ rosterGroupDropId,
BLOB_COLORS,
BLOB_SHAPES,
- type RosterLastMessage,
} from "./roster.logic";
import type { Bot, BotAvatar, Group } from "./types";
@@ -243,6 +244,40 @@ describe("filterRosterBots", () => {
});
});
+describe("filterRosterGroups", () => {
+ const bots = [bot({ id: "boss", name: "Akeru" }), bot({ id: "specialist", name: "Mori" })];
+ const groups: Group[] = [
+ {
+ id: "launch",
+ name: "Launch crew",
+ bossBotId: "boss",
+ members: [
+ { kind: "bot", botId: BotId.make("boss"), role: "boss" },
+ { kind: "bot", botId: BotId.make("specialist"), role: "specialist" },
+ ],
+ createdAt: "2026-08-01T00:00:00.000Z",
+ updatedAt: "2026-08-01T00:00:00.000Z",
+ },
+ ];
+
+ it("matches a group by its name or a member bot name", () => {
+ expect(filterRosterGroups(groups, bots, "launch")).toHaveLength(1);
+ expect(filterRosterGroups(groups, bots, "MORI")).toHaveLength(1);
+ expect(filterRosterGroups(groups, bots, "nobody")).toEqual([]);
+ });
+});
+
+describe("roster drag ids", () => {
+ it("keeps bot and group targets distinct", () => {
+ expect(parseRosterBotDragId(rosterBotDragId("same"))).toBe("same");
+ expect(parseRosterGroupDropId(rosterGroupDropId("same"))).toBe("same");
+ expect(parseRosterBotDragId(rosterGroupDropId("same"))).toBeNull();
+ expect(parseRosterGroupDropId(rosterBotDragId("same"))).toBeNull();
+ expect(parseRosterBotDragId("bot:")).toBeNull();
+ expect(parseRosterGroupDropId("group:")).toBeNull();
+ });
+});
+
describe("randomBotAvatar", () => {
it("returns a valid blob and never picks white", () => {
for (let i = 0; i < 20; i++) {
@@ -352,42 +387,6 @@ describe("resolveLatestRosterMessage", () => {
});
});
-describe("compareRosterBots", () => {
- const lastMessageByBotId: Record<string, RosterLastMessage> = {
- older: { text: "old", at: "2026-08-25T10:00:00.000Z" },
- newer: { text: "new", at: "2026-08-27T10:00:00.000Z" },
- };
-
- it("sorts the latest conversation first", () => {
- const sorted = [bot({ id: "older", name: "Older" }), bot({ id: "newer", name: "Newer" })].sort(
- (a, b) => compareRosterBots(a, b, lastMessageByBotId),
- );
- expect(sorted.map((entry) => entry.id)).toEqual(["newer", "older"]);
- });
-
- it("puts bots without messages after those with, alphabetized", () => {
- const sorted = [
- bot({ id: "quiet-b", name: "Zed" }),
- bot({ id: "older", name: "Older" }),
- bot({ id: "quiet-a", name: "Ada" }),
- ].sort((a, b) => compareRosterBots(a, b, lastMessageByBotId));
- expect(sorted.map((entry) => entry.id)).toEqual(["older", "quiet-a", "quiet-b"]);
- });
-
- it("treats an unparseable timestamp as no message", () => {
- const sorted = [
- bot({ id: "broken", name: "Broken" }),
- bot({ id: "older", name: "Older" }),
- ].sort((a, b) =>
- compareRosterBots(a, b, {
- ...lastMessageByBotId,
- broken: { text: "?", at: "not-a-date" },
- }),
- );
- expect(sorted.map((entry) => entry.id)).toEqual(["older", "broken"]);
- });
-});
-
describe("resolveBlobRendering", () => {
it("passes a valid blob avatar through", () => {
expect(resolveBlobRendering({ kind: "blob", shape: "hex", color: "#5BA97B" })).toEqual({
diff --git a/apps/web/src/components/roster/roster.logic.ts b/apps/web/src/components/roster/roster.logic.ts
index 231382422..44765bfac 100644
--- a/apps/web/src/components/roster/roster.logic.ts
+++ b/apps/web/src/components/roster/roster.logic.ts
@@ -1,4 +1,9 @@
import type { OrchestrationThreadShell } from "@t3tools/contracts";
+import {
+ isGroupBotMember,
+ isGroupPersonMember,
+ type GroupPersonMembership,
+} from "@t3tools/contracts";
import type { TimestampFormat } from "@t3tools/contracts/settings";
import { formatShortTimestamp, parseTimestampDate } from "../../timestampFormat";
import type { Bot, BotAvatar, BotBlobShape, Group } from "./types";
@@ -149,77 +154,6 @@ export function resolveLatestRosterMessage(
return latest.at >= fallback.at ? latest : fallback;
}
-export interface RosterSection {
- id: "pinned" | "unpinned";
- name: "Pinned" | "Bots";
- bots: Bot[];
-}
-
-function lastMessageSortValue(
- bot: Bot,
- lastMessageByBotId: Readonly<Record<string, RosterLastMessage>>,
-): number | null {
- const at = lastMessageByBotId[bot.id]?.at;
- if (at === undefined) return null;
- return parseTimestampDate(at)?.getTime() ?? null;
-}
-
-/** Latest conversation first; bots without messages trail, alphabetized. */
-export function compareRosterBots(
- a: Bot,
- b: Bot,
- lastMessageByBotId: Readonly<Record<string, RosterLastMessage>>,
-): number {
- const aAt = lastMessageSortValue(a, lastMessageByBotId);
- const bAt = lastMessageSortValue(b, lastMessageByBotId);
- if (aAt !== null && bAt !== null && aAt !== bAt) return bAt - aAt;
- if (aAt !== null && bAt === null) return -1;
- if (aAt === null && bAt !== null) return 1;
- return a.name.localeCompare(b.name, undefined, { sensitivity: "base" });
-}
-
-type RosterSectionsInput = readonly Bot[] | { bots: readonly Bot[] };
-
-function isPreviousRosterSectionsInput(
- input: RosterSectionsInput,
-): input is { bots: readonly Bot[] } {
- return !Array.isArray(input);
-}
-
-/**
- * Pinned and unpinned bots keep their persisted order within each section.
- * The object form covers a previous caller that can remain mounted during HMR.
- */
-export function buildRosterSections(input: RosterSectionsInput): RosterSection[] {
- const bots = isPreviousRosterSectionsInput(input) ? input.bots : input;
- const visibleBots = bots.filter((bot) => bot.archivedAt === null);
- const pinned = visibleBots.filter((bot) => bot.pinned);
- const unpinned = visibleBots.filter((bot) => !bot.pinned);
- return [
- ...(pinned.length > 0 ? [{ id: "pinned", name: "Pinned", bots: pinned } as const] : []),
- ...(unpinned.length > 0 ? [{ id: "unpinned", name: "Bots", bots: unpinned } as const] : []),
- ];
-}
-
-export const ROSTER_TILE_LIMIT = 5;
-
-/** Visible bots, pinned first, with persisted order preserved in each partition. */
-export function buildRosterStrip(
- bots: readonly Bot[],
- _lastMessageByBotId: Readonly<Record<string, RosterLastMessage>>,
-): Bot[] {
- const visible = bots.filter((bot) => bot.archivedAt === null);
- return [...visible.filter((bot) => bot.pinned), ...visible.filter((bot) => !bot.pinned)];
-}
-
-/** The expanded roster shows pinned bots in a fixed grid, never a carousel. */
-export function buildRosterTiles(
- bots: readonly Bot[],
- _lastMessageByBotId: Readonly<Record<string, RosterLastMessage>>,
-): Bot[] {
- return bots.filter((bot) => bot.archivedAt === null && bot.pinned).slice(0, ROSTER_TILE_LIMIT);
-}
-
export function filterRosterBots(bots: readonly Bot[], query: string): Bot[] {
const needle = query.trim().toLowerCase();
if (needle.length === 0) return [...bots];
@@ -231,10 +165,18 @@ export function filterRosterBots(bots: readonly Bot[], query: string): Bot[] {
);
}
-export interface RosterGroupSection {
- readonly id: string;
- readonly name: string;
- readonly bots: ReadonlyArray<Bot>;
+export function filterRosterGroups(
+ groups: readonly Group[],
+ bots: readonly Bot[],
+ query: string,
+): Group[] {
+ const needle = query.trim().toLowerCase();
+ if (needle.length === 0) return [...groups];
+ return groups.filter(
+ (group) =>
+ group.name.toLowerCase().includes(needle) ||
+ groupBotMembers(group, bots).some((bot) => bot.name.toLowerCase().includes(needle)),
+ );
}
/**
diff --git a/apps/web/src/components/roster/rosterStore.test.ts b/apps/web/src/components/roster/rosterStore.test.ts
index bb5b5de36..6690622c0 100644
--- a/apps/web/src/components/roster/rosterStore.test.ts
+++ b/apps/web/src/components/roster/rosterStore.test.ts
@@ -1,7 +1,7 @@
import { afterEach, beforeEach, describe, expect, it } from "vite-plus/test";
-import { useRosterStore } from "./rosterStore";
-import type { Bot } from "./types";
+import { reorderVisibleRosterBots, useRosterStore } from "./rosterStore";
+import type { Bot, Group } from "./types";
function bot(id: string, archivedAt: string | null = null): Bot {
return {
@@ -25,6 +25,17 @@ function bot(id: string, archivedAt: string | null = null): Bot {
};
}
+function group(id: string): Group {
+ return {
+ id,
+ name: id,
+ bossBotId: null,
+ members: [],
+ createdAt: "2026-08-01T00:00:00.000Z",
+ updatedAt: "2026-08-01T00:00:00.000Z",
+ };
+}
+
const initialState = useRosterStore.getState();
beforeEach(() => {
@@ -34,6 +45,9 @@ beforeEach(() => {
lastMessageByBotId: {},
selectedBotId: null,
chatPathByBotId: {},
+ sections: [],
+ pinnedItems: [],
+ environmentId: null,
});
});
@@ -44,9 +58,14 @@ afterEach(() => {
lastMessageByBotId: initialState.lastMessageByBotId,
selectedBotId: initialState.selectedBotId,
chatPathByBotId: initialState.chatPathByBotId,
+ sections: initialState.sections,
+ pinnedItems: initialState.pinnedItems,
+ environmentId: initialState.environmentId,
});
if (typeof window !== "undefined") {
- window.localStorage.removeItem("akeru:roster:v1");
+ for (const key of Object.keys(window.localStorage)) {
+ if (key.startsWith("akeru:roster:v1")) window.localStorage.removeItem(key);
+ }
}
});
@@ -54,6 +73,7 @@ describe("bot selection", () => {
it("selects the first available bot when a roster arrives without the active bot", () => {
useRosterStore.setState({ selectedBotId: "missing" });
useRosterStore.getState().replaceRoster({
+ environmentId: "env-one",
bots: [bot("archived", "2026-08-20T00:00:00.000Z"), bot("akeru")],
groups: [],
});
@@ -85,50 +105,166 @@ describe("bot selection", () => {
});
});
-describe("pin and order", () => {
- it("pins and unpins only on a completed partition move", () => {
- useRosterStore.setState({ bots: [bot("one"), bot("two"), bot("three")] });
+describe("bot order", () => {
+ it("moves a bot downward instead of leaving it in place", () => {
+ const bots = [bot("one"), bot("two"), bot("three")];
+
+ const reordered = reorderVisibleRosterBots(bots, ["one", "two", "three"], 0, 2);
+
+ expect(reordered?.map((entry) => entry.id)).toEqual(["two", "three", "one"]);
+ });
+
+ it("moves a bot upward", () => {
+ const bots = [bot("one"), bot("two"), bot("three")];
+
+ const reordered = reorderVisibleRosterBots(bots, ["one", "two", "three"], 2, 0);
+
+ expect(reordered?.map((entry) => entry.id)).toEqual(["three", "one", "two"]);
+ });
- useRosterStore.getState().moveBot("two", null, true);
- expect(useRosterStore.getState().bots.map(({ id, pinned }) => [id, pinned])).toEqual([
- ["two", true],
- ["one", false],
- ["three", false],
+ it("keeps filtered bots in place", () => {
+ const bots = [bot("one"), bot("hidden"), bot("two"), bot("three")];
+
+ const reordered = reorderVisibleRosterBots(bots, ["one", "two", "three"], 2, 0);
+
+ expect(reordered?.map((entry) => entry.id)).toEqual(["three", "hidden", "one", "two"]);
+ });
+});
+
+describe("roster sections and pins", () => {
+ it("moves a bot into a section without changing group or bot identity", () => {
+ const bots = [bot("one"), bot("two")];
+ useRosterStore.setState({
+ bots,
+ sections: [{ id: "news", name: "News", botIds: [], collapsed: false }],
+ });
+
+ useRosterStore.getState().moveBotToSection("one", "news");
+
+ expect(useRosterStore.getState().sections[0]?.botIds).toEqual(["one"]);
+ expect(useRosterStore.getState().bots).toEqual(bots);
+ });
+
+ it("moves a bot between sections and back to unassigned", () => {
+ useRosterStore.setState({
+ bots: [bot("one")],
+ sections: [
+ { id: "first", name: "First", botIds: ["one"], collapsed: false },
+ { id: "second", name: "Second", botIds: [], collapsed: false },
+ ],
+ });
+
+ useRosterStore.getState().moveBotToSection("one", "second");
+ expect(useRosterStore.getState().sections.map((section) => section.botIds)).toEqual([
+ [],
+ ["one"],
]);
- useRosterStore.getState().moveBot("two", null, false);
- expect(useRosterStore.getState().bots.map(({ id, pinned }) => [id, pinned])).toEqual([
- ["one", false],
- ["three", false],
- ["two", false],
+ useRosterStore.getState().moveBotToSection("one", null);
+ expect(useRosterStore.getState().sections.map((section) => section.botIds)).toEqual([[], []]);
+ });
+
+ it("reorders bots inside Unassigned", () => {
+ useRosterStore.setState({ bots: [bot("one"), bot("two"), bot("three")] });
+
+ useRosterStore.getState().moveBotToSection("three", null, 0);
+
+ expect(useRosterStore.getState().bots.map((entry) => entry.id)).toEqual([
+ "three",
+ "one",
+ "two",
]);
});
- it("reorders both partitions and supports valid cross-partition drops", () => {
+ it("pins bots and groups as separate quick-launch items", () => {
+ useRosterStore.getState().setItemPinned({ kind: "bot", id: "one" }, true);
+ useRosterStore.getState().setItemPinned({ kind: "group", id: "crew" }, true);
+ useRosterStore.getState().setItemPinned({ kind: "bot", id: "one" }, false);
+
+ expect(useRosterStore.getState().pinnedItems).toEqual([{ kind: "group", id: "crew" }]);
+ });
+
+ it("moves a group between a section and Unassigned", () => {
+ useRosterStore.setState({
+ groups: [group("crew")],
+ sections: [
+ {
+ id: "launch",
+ name: "Launch",
+ botIds: [],
+ groupIds: [],
+ collapsed: false,
+ },
+ ],
+ });
+
+ useRosterStore.getState().moveGroupToSection("crew", "launch");
+ expect(useRosterStore.getState().sections[0]?.groupIds).toEqual(["crew"]);
+
+ useRosterStore.getState().moveGroupToSection("crew", null);
+ expect(useRosterStore.getState().sections[0]?.groupIds).toEqual([]);
+ });
+
+ it("reorders sections and persists collapsed state", () => {
useRosterStore.setState({
- bots: [
- { ...bot("pin-a"), pinned: true },
- { ...bot("pin-b"), pinned: true },
- bot("plain-a"),
- bot("plain-b"),
+ sections: [
+ { id: "first", name: "First", botIds: [], collapsed: false },
+ { id: "second", name: "Second", botIds: [], collapsed: false },
],
});
- useRosterStore.getState().moveBot("pin-b", "pin-a", true);
- useRosterStore.getState().moveBot("plain-b", "plain-a", false);
- useRosterStore.getState().moveBot("plain-a", "pin-a", true);
- expect(useRosterStore.getState().bots.map(({ id, pinned }) => [id, pinned])).toEqual([
- ["pin-b", true],
- ["plain-a", true],
- ["pin-a", true],
- ["plain-b", false],
+ useRosterStore.getState().toggleSection("first");
+ useRosterStore.getState().reorderSections(0, 1);
+
+ expect(
+ useRosterStore.getState().sections.map(({ id, collapsed }) => ({ id, collapsed })),
+ ).toEqual([
+ { id: "second", collapsed: false },
+ { id: "first", collapsed: true },
]);
});
- it("ignores an invalid cross-partition target", () => {
- useRosterStore.setState({ bots: [{ ...bot("pinned"), pinned: true }, bot("plain")] });
+ it("deletes a section without deleting its bots", () => {
+ const bots = [bot("one"), bot("two")];
+ useRosterStore.setState({
+ bots,
+ sections: [{ id: "old", name: "Old", botIds: ["one"], collapsed: false }],
+ });
+
+ useRosterStore.getState().deleteSection("old");
+
+ expect(useRosterStore.getState().sections).toEqual([]);
+ expect(useRosterStore.getState().bots).toEqual(bots);
+ });
- useRosterStore.getState().moveBot("pinned", "plain", true);
- expect(useRosterStore.getState().bots.map((entry) => entry.id)).toEqual(["pinned", "plain"]);
+ it("does not erase another environment's layout", () => {
+ useRosterStore.setState({
+ environmentId: "env-one",
+ bots: [bot("one")],
+ sections: [{ id: "work", name: "Work", botIds: ["one"], collapsed: false }],
+ });
+ useRosterStore.getState().toggleSection("work");
+
+ useRosterStore.getState().replaceRoster({
+ environmentId: "env-two",
+ bots: [bot("two")],
+ groups: [],
+ });
+ expect(useRosterStore.getState().sections).toEqual([]);
+ useRosterStore.getState().replaceRoster({
+ environmentId: "env-one",
+ bots: [bot("one")],
+ groups: [],
+ });
+
+ expect(useRosterStore.getState().sections).toEqual([
+ {
+ id: "work",
+ name: "Work",
+ botIds: ["one"],
+ groupIds: [],
+ collapsed: true,
+ },
+ ]);
});
});
diff --git a/apps/web/src/components/roster/rosterStore.ts b/apps/web/src/components/roster/rosterStore.ts
index d6644c505..24ef0666c 100644
--- a/apps/web/src/components/roster/rosterStore.ts
+++ b/apps/web/src/components/roster/rosterStore.ts
@@ -1,31 +1,54 @@
import { create } from "zustand";
+import { randomUUID } from "../../lib/utils";
import type { RosterLastMessage } from "./roster.logic";
import type { Bot, BotAvatar, Group } from "./types";
const PERSISTED_ROSTER_KEY = "akeru:roster:v1";
+const persistedRosterMemory = new Map<string, PersistedRoster>();
+
+function persistedRosterKey(environmentId: string | null): string {
+ return environmentId ? `${PERSISTED_ROSTER_KEY}:${environmentId}` : PERSISTED_ROSTER_KEY;
+}
interface PersistedRoster {
selectedBotId?: string;
chatPathByBotId?: Record<string, string>;
botLayout?: Array<{ id: string; pinned: boolean }>;
+ sections?: RosterSection[];
+ pinnedItems?: RosterItemRef[];
+}
+
+export interface RosterSection {
+ id: string;
+ name: string;
+ botIds: string[];
+ groupIds?: string[];
+ collapsed: boolean;
}
+export type RosterItemRef = { kind: "bot"; id: string } | { kind: "group"; id: string };
+
function firstAvailableBotId(bots: readonly Bot[]): string | null {
return bots.find((bot) => bot.archivedAt === null)?.id ?? null;
}
-function readPersistedRoster(): PersistedRoster | null {
+function readPersistedRoster(environmentId: string | null = null): PersistedRoster | null {
+ const key = persistedRosterKey(environmentId);
+ const inMemory = persistedRosterMemory.get(key);
+ if (inMemory) return inMemory;
if (typeof window === "undefined") return null;
try {
- const raw = window.localStorage.getItem(PERSISTED_ROSTER_KEY);
+ const raw = window.localStorage.getItem(key);
if (raw === null) return null;
const parsed: unknown = JSON.parse(raw);
if (typeof parsed !== "object" || parsed === null) return null;
- const { selectedBotId, chatPathByBotId, botLayout } = parsed as {
+ const { selectedBotId, chatPathByBotId, botLayout, sections, pinnedItems } = parsed as {
selectedBotId?: unknown;
chatPathByBotId?: unknown;
botLayout?: unknown;
+ sections?: unknown;
+ pinnedItems?: unknown;
};
return {
...(typeof selectedBotId === "string" ? { selectedBotId } : {}),
@@ -42,16 +65,54 @@ function readPersistedRoster(): PersistedRoster | null {
)
? { botLayout: botLayout as Array<{ id: string; pinned: boolean }> }
: {}),
+ ...(Array.isArray(sections) &&
+ sections.every(
+ (section) =>
+ typeof section === "object" &&
+ section !== null &&
+ typeof (section as { id?: unknown }).id === "string" &&
+ typeof (section as { name?: unknown }).name === "string" &&
+ Array.isArray((section as { botIds?: unknown }).botIds) &&
+ (section as { botIds: unknown[] }).botIds.every((id) => typeof id === "string") &&
+ ((section as { groupIds?: unknown }).groupIds === undefined ||
+ (Array.isArray((section as { groupIds?: unknown }).groupIds) &&
+ (section as { groupIds: unknown[] }).groupIds.every(
+ (id) => typeof id === "string",
+ ))) &&
+ typeof (section as { collapsed?: unknown }).collapsed === "boolean",
+ )
+ ? {
+ sections: (
+ sections as Array<Omit<RosterSection, "groupIds"> & { groupIds?: string[] }>
+ ).map((section) => ({
+ ...section,
+ groupIds: section.groupIds ?? [],
+ })),
+ }
+ : {}),
+ ...(Array.isArray(pinnedItems) &&
+ pinnedItems.every(
+ (item) =>
+ typeof item === "object" &&
+ item !== null &&
+ ((item as { kind?: unknown }).kind === "bot" ||
+ (item as { kind?: unknown }).kind === "group") &&
+ typeof (item as { id?: unknown }).id === "string",
+ )
+ ? { pinnedItems: pinnedItems as RosterItemRef[] }
+ : {}),
};
} catch {
return null;
}
}
-function persistRoster(roster: PersistedRoster): void {
+function persistRoster(roster: PersistedRoster, environmentId: string | null): void {
+ const key = persistedRosterKey(environmentId);
+ persistedRosterMemory.set(key, roster);
if (typeof window === "undefined") return;
try {
- window.localStorage.setItem(PERSISTED_ROSTER_KEY, JSON.stringify(roster));
+ window.localStorage.setItem(key, JSON.stringify(roster));
} catch (error) {
console.error("Could not persist bot roster.", error);
}
@@ -63,50 +124,74 @@ interface RosterStore {
lastMessageByBotId: Record<string, RosterLastMessage>;
selectedBotId: string | null;
chatPathByBotId: Record<string, string>;
+ sections: RosterSection[];
+ pinnedItems: RosterItemRef[];
+ environmentId: string | null;
selectBot: (botId: string) => void;
setBotAvatar: (botId: string, avatar: BotAvatar) => boolean;
- moveBot: (activeBotId: string, overBotId: string | null, pinned: boolean) => void;
commitBotLayout: (bots: Bot[]) => void;
+ createSection: (name: string) => void;
+ toggleSection: (sectionId: string) => void;
+ deleteSection: (sectionId: string) => void;
+ moveGroupToSection: (groupId: string, sectionId: string | null, index?: number) => void;
+ moveBotToSection: (botId: string, sectionId: string | null, index?: number) => void;
+ reorderSections: (sourceIndex: number, destinationIndex: number) => void;
+ setItemPinned: (item: RosterItemRef, pinned: boolean) => void;
recordLastMessage: (botId: string, message: RosterLastMessage) => void;
recordChatPath: (botId: string, path: string) => void;
forgetChatPath: (botId: string) => void;
replaceRoster: (input: {
+ environmentId: string;
bots: Bot[];
groups: Group[];
lastMessageByBotId?: Record<string, RosterLastMessage>;
}) => void;
}
-export function moveRosterBot(
+export function reorderVisibleRosterBots(
bots: readonly Bot[],
- activeBotId: string,
- overBotId: string | null,
- pinned: boolean,
+ visibleBotIds: readonly string[],
+ sourceIndex: number,
+ destinationIndex: number,
): Bot[] | null {
- const active = bots.find((bot) => bot.id === activeBotId);
- const over = overBotId ? bots.find((bot) => bot.id === overBotId) : null;
- if (!active || active.archivedAt !== null) return null;
- if (over && (over.archivedAt !== null || over.pinned !== pinned)) return null;
- if (active.id === over?.id && active.pinned === pinned) return null;
-
- const moved = { ...active, pinned };
- const next = bots.filter((bot) => bot.id !== activeBotId);
- if (over) {
- const overIndex = next.findIndex((bot) => bot.id === over.id);
- next.splice(overIndex, 0, moved);
- } else {
- const partitionEnd = next.findLastIndex((bot) => bot.pinned === pinned);
- next.splice(partitionEnd + 1, 0, moved);
+ if (
+ sourceIndex === destinationIndex ||
+ sourceIndex < 0 ||
+ destinationIndex < 0 ||
+ sourceIndex >= visibleBotIds.length ||
+ destinationIndex >= visibleBotIds.length ||
+ new Set(visibleBotIds).size !== visibleBotIds.length
+ ) {
+ return null;
}
- return next;
+ const byId = new Map(bots.map((bot) => [bot.id, bot] as const));
+ const visible = visibleBotIds.map((id) => byId.get(id));
+ if (visible.some((bot) => !bot || bot.archivedAt !== null)) return null;
+ const ordered = visible as Bot[];
+ const [moved] = ordered.splice(sourceIndex, 1);
+ if (!moved) return null;
+ ordered.splice(destinationIndex, 0, moved);
+ const visibleIds = new Set(visibleBotIds);
+ let index = 0;
+ return bots.map((bot) => (visibleIds.has(bot.id) ? ordered[index++]! : bot));
}
-function saveState(state: Pick<RosterStore, "bots" | "selectedBotId" | "chatPathByBotId">) {
- persistRoster({
- ...(state.selectedBotId === null ? {} : { selectedBotId: state.selectedBotId }),
- chatPathByBotId: state.chatPathByBotId,
- botLayout: state.bots.map((bot) => ({ id: bot.id, pinned: bot.pinned })),
- });
+function saveState(
+ state: Pick<
+ RosterStore,
+ "bots" | "selectedBotId" | "chatPathByBotId" | "sections" | "pinnedItems" | "environmentId"
+ >,
+) {
+ persistRoster(
+ {
+ ...(state.selectedBotId === null ? {} : { selectedBotId: state.selectedBotId }),
+ chatPathByBotId: state.chatPathByBotId,
+ botLayout: state.bots.map((bot) => ({ id: bot.id, pinned: bot.pinned })),
+ sections: state.sections,
+ pinnedItems: state.pinnedItems,
+ },
+ state.environmentId,
+ );
}
const persisted = readPersistedRoster();
@@ -117,6 +202,9 @@ export const useRosterStore = create<RosterStore>((set, get) => ({
lastMessageByBotId: {},
selectedBotId: persisted?.selectedBotId ?? null,
chatPathByBotId: persisted?.chatPathByBotId ?? {},
+ sections: persisted?.sections ?? [],
+ pinnedItems: persisted?.pinnedItems ?? [],
+ environmentId: null,
selectBot: (botId) => {
if (!get().bots.some((bot) => bot.id === botId && bot.archivedAt === null)) return;
@@ -135,20 +223,6 @@ export const useRosterStore = create<RosterStore>((set, get) => ({
return true;
},
- moveBot: (activeBotId, overBotId, pinned) => {
- const current = get().bots;
- const bots = moveRosterBot(current, activeBotId, overBotId, pinned);
- if (!bots) return;
- const active = current.find((bot) => bot.id === activeBotId);
- const nextBots = bots.map((bot) =>
- bot.id === activeBotId && active?.pinned !== pinned
- ? { ...bot, updatedAt: new Date().toISOString() }
- : bot,
- );
- set({ bots: nextBots });
- saveState(get());
- },
-
commitBotLayout: (bots) => {
const current = get().bots;
if (
@@ -163,19 +237,141 @@ export const useRosterStore = create<RosterStore>((set, get) => ({
const previous = currentById.get(bot.id)!;
return previous.pinned === bot.pinned
? previous
- : { ...previous, pinned: bot.pinned, updatedAt: new Date().toISOString() };
+ : {
+ ...previous,
+ pinned: bot.pinned,
+ updatedAt: new Date().toISOString(),
+ };
});
set({ bots: committed });
saveState(get());
},
+ createSection: (name) => {
+ const trimmed = name.trim();
+ if (!trimmed) return;
+ set((state) => ({
+ sections: [
+ ...state.sections,
+ {
+ id: randomUUID(),
+ name: trimmed,
+ botIds: [],
+ groupIds: [],
+ collapsed: false,
+ },
+ ],
+ }));
+ saveState(get());
+ },
+
+ toggleSection: (sectionId) => {
+ set((state) => ({
+ sections: state.sections.map((section) =>
+ section.id === sectionId ? { ...section, collapsed: !section.collapsed } : section,
+ ),
+ }));
+ saveState(get());
+ },
+
+ deleteSection: (sectionId) => {
+ if (!get().sections.some((section) => section.id === sectionId)) return;
+ set((state) => ({
+ sections: state.sections.filter((section) => section.id !== sectionId),
+ }));
+ saveState(get());
+ },
+
+ moveBotToSection: (botId, sectionId, index) => {
+ if (!get().bots.some((bot) => bot.id === botId && bot.archivedAt === null)) return;
+ if (sectionId !== null && !get().sections.some((section) => section.id === sectionId)) return;
+ set((state) => {
+ const sections = state.sections.map((section) => {
+ const botIds = section.botIds.filter((id) => id !== botId);
+ if (section.id !== sectionId) return { ...section, botIds };
+ botIds.splice(Math.min(Math.max(index ?? botIds.length, 0), botIds.length), 0, botId);
+ return { ...section, botIds };
+ });
+ if (sectionId !== null) return { sections };
+ const assigned = new Set(sections.flatMap((section) => section.botIds));
+ const unassignedIds = state.bots
+ .filter((bot) => bot.archivedAt === null && !assigned.has(bot.id) && bot.id !== botId)
+ .map((bot) => bot.id);
+ unassignedIds.splice(
+ Math.min(Math.max(index ?? unassignedIds.length, 0), unassignedIds.length),
+ 0,
+ botId,
+ );
+ const unassigned = new Set(unassignedIds);
+ const botsById = new Map(state.bots.map((bot) => [bot.id, bot] as const));
+ let botIndex = 0;
+ return {
+ sections,
+ bots: state.bots.map((bot) =>
+ unassigned.has(bot.id) ? (botsById.get(unassignedIds[botIndex++]!) ?? bot) : bot,
+ ),
+ };
+ });
+ saveState(get());
+ },
+
+ moveGroupToSection: (groupId, sectionId, index) => {
+ if (!get().groups.some((group) => group.id === groupId)) return;
+ if (sectionId !== null && !get().sections.some((section) => section.id === sectionId)) return;
+ set((state) => ({
+ sections: state.sections.map((section) => {
+ const groupIds = (section.groupIds ?? []).filter((id) => id !== groupId);
+ if (section.id !== sectionId) return { ...section, groupIds };
+ groupIds.splice(
+ Math.min(Math.max(index ?? groupIds.length, 0), groupIds.length),
+ 0,
+ groupId,
+ );
+ return { ...section, groupIds };
+ }),
+ }));
+ saveState(get());
+ },
+
+ reorderSections: (sourceIndex, destinationIndex) => {
+ if (
+ sourceIndex === destinationIndex ||
+ sourceIndex < 0 ||
+ destinationIndex < 0 ||
+ sourceIndex >= get().sections.length ||
+ destinationIndex >= get().sections.length
+ ) {
+ return;
+ }
+ const sections = [...get().sections];
+ const [moved] = sections.splice(sourceIndex, 1);
+ if (!moved) return;
+ sections.splice(destinationIndex, 0, moved);
+ set({ sections });
+ saveState(get());
+ },
+
+ setItemPinned: (item, pinned) => {
+ set((state) => {
+ const withoutItem = state.pinnedItems.filter(
+ (candidate) => candidate.kind !== item.kind || candidate.id !== item.id,
+ );
+ return { pinnedItems: pinned ? [...withoutItem, item] : withoutItem };
+ });
+ saveState(get());
+ },
+
recordLastMessage: (botId, message) => {
- set((state) => ({ lastMessageByBotId: { ...state.lastMessageByBotId, [botId]: message } }));
+ set((state) => ({
+ lastMessageByBotId: { ...state.lastMessageByBotId, [botId]: message },
+ }));
},
recordChatPath: (botId, path) => {
if (get().chatPathByBotId[botId] === path) return;
- set((state) => ({ chatPathByBotId: { ...state.chatPathByBotId, [botId]: path } }));
+ set((state) => ({
+ chatPathByBotId: { ...state.chatPathByBotId, [botId]: path },
+ }));
saveState(get());
},
@@ -188,10 +384,15 @@ export const useRosterStore = create<RosterStore>((set, get) => ({
},
replaceRoster: (input) => {
+ const switchingEnvironment = get().environmentId !== input.environmentId;
+ const scopedPersisted = switchingEnvironment ? readPersistedRoster(input.environmentId) : null;
+ const targetPersisted = switchingEnvironment
+ ? (scopedPersisted ?? (get().environmentId === null ? persisted : null))
+ : null;
const currentLayout =
- get().bots.length > 0
+ !switchingEnvironment && get().bots.length > 0
? get().bots.map((bot) => ({ id: bot.id, pinned: bot.pinned }))
- : (persisted?.botLayout ?? []);
+ : (targetPersisted?.botLayout ?? []);
const orderById = new Map(currentLayout.map((entry, index) => [entry.id, index] as const));
const pinnedById = new Map(currentLayout.map((entry) => [entry.id, entry.pinned] as const));
const bots = input.bots
@@ -201,14 +402,39 @@ export const useRosterStore = create<RosterStore>((set, get) => ({
(orderById.get(left.id) ?? Number.MAX_SAFE_INTEGER) -
(orderById.get(right.id) ?? Number.MAX_SAFE_INTEGER),
);
+ const targetSelectedBotId = switchingEnvironment
+ ? (targetPersisted?.selectedBotId ?? null)
+ : get().selectedBotId;
const selectedBotId = bots.some(
- (bot) => bot.id === get().selectedBotId && bot.archivedAt === null,
+ (bot) => bot.id === targetSelectedBotId && bot.archivedAt === null,
)
- ? get().selectedBotId
+ ? targetSelectedBotId
: firstAvailableBotId(bots);
+ const targetSections = switchingEnvironment
+ ? (targetPersisted?.sections ?? [])
+ : get().sections;
+ const targetPinnedItems = switchingEnvironment
+ ? (targetPersisted?.pinnedItems ?? [])
+ : get().pinnedItems;
set({
+ environmentId: input.environmentId,
bots,
groups: input.groups,
+ chatPathByBotId: switchingEnvironment
+ ? (targetPersisted?.chatPathByBotId ?? {})
+ : get().chatPathByBotId,
+ sections: targetSections.map((section) => ({
+ ...section,
+ botIds: section.botIds.filter((id) => bots.some((bot) => bot.id === id)),
+ groupIds: (section.groupIds ?? []).filter((id) =>
+ input.groups.some((group) => group.id === id),
+ ),
+ })),
+ pinnedItems: targetPinnedItems.filter((item) =>
+ item.kind === "bot"
+ ? bots.some((bot) => bot.id === item.id && bot.archivedAt === null)
+ : input.groups.some((group) => group.id === item.id),
+ ),
selectedBotId,
...(input.lastMessageByBotId ? { lastMessageByBotId: input.lastMessageByBotId } : {}),
});
diff --git a/apps/web/src/components/roster/types.ts b/apps/web/src/components/roster/types.ts
index 9d6bfb587..5980718db 100644
--- a/apps/web/src/components/roster/types.ts
+++ b/apps/web/src/components/roster/types.ts
@@ -1,4 +1,4 @@
-import type { McpServerId } from "@t3tools/contracts";
+import type { ChannelBinding, GroupMembership, McpServerId } from "@t3tools/contracts";
/**
* Local mirror of the bot roster wire shape the server-side persistence work
@@ -35,6 +35,7 @@ export interface Bot {
runtimeMode: "approval-required" | "auto-accept-edits" | "auto" | "full-access";
usageCap: { unit: "tokens"; limit: number } | null;
voiceEnabled: boolean;
+ channelBindings?: ReadonlyArray<ChannelBinding>;
groupId: string | null;
pinned: boolean;
archivedAt: string | null;
@@ -46,7 +47,7 @@ export interface Group {
id: string;
name: string;
bossBotId: string | null;
- members: ReadonlyArray<{ botId: string; role: "boss" | "specialist" }>;
+ members: ReadonlyArray<GroupMembership>;
createdAt: string;
updatedAt: string;
}
diff --git a/apps/web/src/components/roster/useGroupThreadRuntime.ts b/apps/web/src/components/roster/useGroupThreadRuntime.ts
index 26b7325f3..738ab6c26 100644
--- a/apps/web/src/components/roster/useGroupThreadRuntime.ts
+++ b/apps/web/src/components/roster/useGroupThreadRuntime.ts
@@ -31,6 +31,7 @@ import { DEFAULT_INTERACTION_MODE } from "../../types";
import { sortScopedProjectsForSidebar } from "../Sidebar.logic";
import { resolveBotRuntimeMode } from "./botSandbox";
import { buildGroupTurnStartInput, findLatestGroupThreadTarget } from "./botThreadRuntime.logic";
+import { groupContainsBot } from "./roster.logic";
import { useRosterStore } from "./rosterStore";
const NO_ENVIRONMENT = "" as EnvironmentId;
@@ -157,7 +158,7 @@ export function useGroupThreadRuntime(groupId: string) {
const respondingBotId = requestedBotId ?? group.bossBotId;
const respondingBot = bots.find(
- (bot) => bot.id === respondingBotId && bot.groupId === groupId,
+ (bot) => bot.id === respondingBotId && groupContainsBot(group, bot.id),
);
if (!respondingBot) {
setError("Choose a current group member.");
diff --git a/apps/web/src/components/roster/useServerRoster.ts b/apps/web/src/components/roster/useServerRoster.ts
index fc7bde62c..bf0ee032a 100644
--- a/apps/web/src/components/roster/useServerRoster.ts
+++ b/apps/web/src/components/roster/useServerRoster.ts
@@ -26,9 +26,11 @@ export function useServerRosterSync(): void {
useEffect(() => {
if (environmentId === null || !loaded) return;
useRosterStore.getState().replaceRoster({
+ environmentId,
bots: bots.map((bot) => ({
...bot,
avatar: { ...bot.avatar },
+ channelBindings: bot.channelBindings ?? [],
pinned: false,
})),
groups: groups.map((group) => ({ ...group })),
@@ -39,7 +41,9 @@ export function useServerRosterSync(): void {
export function useSaveBotAvatar(): (botId: string, avatar: BotAvatar) => Promise<boolean> {
const environmentId = usePrimaryEnvironmentId();
const bots = useAtomValue(environmentBotsAtom(environmentId ?? NO_ENVIRONMENT));
- const updateBot = useAtomCommand(botEnvironment.update, { reportFailure: false });
+ const updateBot = useAtomCommand(botEnvironment.update, {
+ reportFailure: false,
+ });
return useCallback(
async (botId: string, avatar: BotAvatar) => {
diff --git a/apps/web/src/components/settings/BotChannelRows.tsx b/apps/web/src/components/settings/BotChannelRows.tsx
new file mode 100644
index 000000000..b18bd99fe
--- /dev/null
+++ b/apps/web/src/components/settings/BotChannelRows.tsx
@@ -0,0 +1,402 @@
+import {
+ type BotId,
+ type ChannelBinding,
+ type ChannelProvider,
+ type EnvironmentId,
+} 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;
+ readonly channelBindings?: readonly ChannelBinding[];
+}
+
+export function bindingFor(bot: ChannelBot, provider: ChannelProvider): ChannelBinding {
+ return (
+ bot.channelBindings?.find((binding) => binding.provider === provider) ?? {
+ botId: bot.id,
+ provider,
+ status: "disconnected",
+ externalIdentity: null,
+ connectedAt: null,
+ sentMessageIds: [],
+ }
+ );
+}
+
+export function selfHostedIMessageConnectInput(
+ botId: BotId,
+ serverUrl: string,
+ apiKey: string,
+ phone: string,
+) {
+ const trimmedPhone = phone.trim();
+ return {
+ botId,
+ provider: "imessage" as const,
+ mode: "self-hosted" as const,
+ serverUrl: serverUrl.trim(),
+ apiKey: apiKey.trim(),
+ ...(trimmedPhone ? { phone: trimmedPhone } : {}),
+ };
+}
+
+export function whatsAppConnectInput(
+ botId: BotId,
+ accessToken: string,
+ appSecret: string,
+ phoneNumberId: string,
+ verifyToken: string,
+) {
+ return {
+ botId,
+ provider: "whatsapp" as const,
+ accessToken: accessToken.trim(),
+ appSecret: appSecret.trim(),
+ phoneNumberId: phoneNumberId.trim(),
+ 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.test.ts b/apps/web/src/components/settings/BotChannelsSettings.test.ts
new file mode 100644
index 000000000..56289a59a
--- /dev/null
+++ b/apps/web/src/components/settings/BotChannelsSettings.test.ts
@@ -0,0 +1,169 @@
+import { AuthAccessWriteScope, BotId, ChannelConnectionId } from "@t3tools/contracts";
+import { describe, expect, it } from "vite-plus/test";
+
+import {
+ canManageChannels,
+ connectedChannelBinding,
+ resolveChannelSettingsAccess,
+} from "../../channelAccess";
+import { bindingFor, selfHostedIMessageConnectInput, whatsAppConnectInput } from "./BotChannelRows";
+import {
+ assignedBotForConnection,
+ channelTestInstructions,
+ parsePhotonHostedCredentials,
+ providerLabel,
+} from "./BotChannelsSettings";
+
+describe("bot channel settings", () => {
+ const botId = BotId.make("bot-1");
+
+ it("shows disconnected live adapters", () => {
+ const bot = { id: botId, channelBindings: [] };
+
+ expect(bindingFor(bot, "telegram")).toEqual({
+ botId,
+ provider: "telegram",
+ status: "disconnected",
+ externalIdentity: null,
+ connectedAt: null,
+ sentMessageIds: [],
+ });
+ expect(bindingFor(bot, "whatsapp").status).toBe("disconnected");
+ });
+
+ it("uses a persisted binding", () => {
+ const connectedAt = "2026-08-27T20:00:00.000Z";
+ expect(
+ bindingFor(
+ {
+ id: botId,
+ channelBindings: [
+ {
+ botId,
+ provider: "imessage",
+ status: "connected",
+ externalIdentity: "+15551234567",
+ connectedAt,
+ sentMessageIds: [],
+ },
+ ],
+ },
+ "imessage",
+ ),
+ ).toMatchObject({ status: "connected", externalIdentity: "+15551234567", connectedAt });
+ });
+
+ it("sends a trimmed Photon phone when self-hosted", () => {
+ expect(
+ selfHostedIMessageConnectInput(botId, " photon.test:443 ", " secret ", " +15551234567 "),
+ ).toEqual({
+ botId,
+ provider: "imessage",
+ mode: "self-hosted",
+ serverUrl: "photon.test:443",
+ apiKey: "secret",
+ phone: "+15551234567",
+ });
+ expect(selfHostedIMessageConnectInput(botId, "server", "key", " ")).not.toHaveProperty(
+ "phone",
+ );
+ });
+
+ it("sends trimmed WhatsApp credentials", () => {
+ expect(
+ whatsAppConnectInput(
+ botId,
+ " access-token ",
+ " app-secret ",
+ " phone-number-id ",
+ " verify-token ",
+ ),
+ ).toEqual({
+ botId,
+ provider: "whatsapp",
+ accessToken: "access-token",
+ appSecret: "app-secret",
+ phoneNumberId: "phone-number-id",
+ verifyToken: "verify-token",
+ });
+ });
+
+ it("requires access write scope for channel controls", () => {
+ const session = { authenticated: true, auth: { mode: "required" as const } };
+
+ expect(canManageChannels({ ...session, scopes: [AuthAccessWriteScope] })).toBe(true);
+ expect(canManageChannels({ ...session, scopes: ["orchestration:operate"] })).toBe(false);
+ expect(canManageChannels(null)).toBe(false);
+ });
+
+ it("allows Send only for a connected binding", () => {
+ const disconnected = bindingFor({ id: botId, channelBindings: [] }, "telegram");
+ const connected = { ...disconnected, status: "connected" as const };
+
+ expect(connectedChannelBinding([disconnected], "telegram")).toBeUndefined();
+ expect(connectedChannelBinding([connected], "telegram")).toEqual(connected);
+ });
+
+ it("keeps pending access neutral until the session loads", () => {
+ expect(resolveChannelSettingsAccess({ isPending: true, session: null })).toBe("pending");
+ expect(resolveChannelSettingsAccess({ isPending: false, session: null })).toBe("denied");
+ });
+
+ it("finds saved connections assigned to archived bots", () => {
+ const connectionId = ChannelConnectionId.make("photon-work");
+ const bots = [
+ {
+ id: botId,
+ name: "Scout",
+ archivedAt: "2026-08-28T20:00:00.000Z",
+ channelBindings: [
+ {
+ botId,
+ connectionId,
+ provider: "imessage" as const,
+ status: "connected" as const,
+ externalIdentity: "+15551234567",
+ connectedAt: "2026-08-27T20:00:00.000Z",
+ sentMessageIds: [],
+ },
+ ],
+ },
+ ];
+
+ expect(assignedBotForConnection(connectionId, bots)?.name).toBe("Scout");
+ expect(assignedBotForConnection(ChannelConnectionId.make("unassigned"), bots)).toBeUndefined();
+ });
+
+ it("uses installed adapter names", () => {
+ expect(providerLabel("imessage")).toBe("Photon");
+ expect(providerLabel("whatsapp")).toBe("Meta Cloud API");
+ expect(providerLabel("telegram")).toBe("Telegram Bot API");
+ });
+
+ 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");
+ });
+
+ it("parses copied Photon environment variables", () => {
+ expect(
+ parsePhotonHostedCredentials(
+ "SPECTRUM_PROJECT_ID=project-1\r\nSPECTRUM_PROJECT_SECRET=secret=with=equals",
+ ),
+ ).toEqual({ projectId: "project-1", projectSecret: "secret=with=equals" });
+ });
+
+ it("rejects incomplete or ambiguous Photon environment variables", () => {
+ expect(parsePhotonHostedCredentials("SPECTRUM_PROJECT_ID=project-1")).toBeNull();
+ expect(
+ parsePhotonHostedCredentials(
+ "SPECTRUM_PROJECT_ID=first\nSPECTRUM_PROJECT_ID=second\nSPECTRUM_PROJECT_SECRET=secret",
+ ),
+ ).toBeNull();
+ expect(
+ parsePhotonHostedCredentials("OTHER_PROJECT_ID=project-1\nSPECTRUM_PROJECT_SECRET=secret"),
+ ).toBeNull();
+ });
+});
diff --git a/apps/web/src/components/settings/BotChannelsSettings.tsx b/apps/web/src/components/settings/BotChannelsSettings.tsx
new file mode 100644
index 000000000..96b09999d
--- /dev/null
+++ b/apps/web/src/components/settings/BotChannelsSettings.tsx
@@ -0,0 +1,519 @@
+import { useAtomValue } from "@effect/atom-react";
+import {
+ BotId,
+ ChannelConnectionId,
+ type ChannelConnectionProfile,
+ type ChannelProvider,
+ type EnvironmentId,
+ type OrchestrationBot,
+} from "@t3tools/contracts";
+import { useEffect, useMemo, useRef, useState } from "react";
+
+import { resolveChannelSettingsAccess } from "../../channelAccess";
+import { useEnvironmentSettings } from "../../hooks/useSettings";
+import { cn } from "../../lib/utils";
+import { botEnvironment, environmentBotsAtom } from "../../state/bots";
+import { useEnvironmentSessionState } from "../../state/session";
+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 { 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",
+ ),
+ );
+}
+
+export function providerLabel(provider: ChannelProvider): string {
+ return provider === "imessage"
+ ? "Photon"
+ : provider === "whatsapp"
+ ? "Meta Cloud API"
+ : "Telegram Bot API";
+}
+
+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.";
+}
+
+export function parsePhotonHostedCredentials(input: string): {
+ readonly projectId: string;
+ readonly projectSecret: string;
+} | null {
+ const entries = new Map<string, string>();
+ for (const line of input.split(/\r?\n/u)) {
+ if (!line.trim()) continue;
+ const separator = line.indexOf("=");
+ if (separator <= 0) return null;
+ const key = line.slice(0, separator).trim();
+ const value = line.slice(separator + 1).trim();
+ if (
+ (key !== "SPECTRUM_PROJECT_ID" && key !== "SPECTRUM_PROJECT_SECRET") ||
+ !value ||
+ entries.has(key)
+ ) {
+ return null;
+ }
+ entries.set(key, value);
+ }
+ const projectId = entries.get("SPECTRUM_PROJECT_ID");
+ const projectSecret = entries.get("SPECTRUM_PROJECT_SECRET");
+ return projectId && projectSecret ? { projectId, projectSecret } : null;
+}
+
+export function BotChannelsSettingsPanel() {
+ const environmentId = useSettingsEnvironmentId();
+ const targetEnvironmentId = environmentId ?? NO_ENVIRONMENT;
+ const session = useEnvironmentSessionState(targetEnvironmentId);
+ const bots = useAtomValue(environmentBotsAtom(targetEnvironmentId));
+ const activeBots = useMemo(() => bots.filter((bot) => bot.archivedAt === null), [bots]);
+ const connections = useEnvironmentSettings(
+ targetEnvironmentId,
+ (settings) => settings.channelConnections,
+ );
+ const saveConnection = useAtomCommand(botEnvironment.channels.saveConnection, {
+ reportFailure: false,
+ });
+ const deleteConnection = useAtomCommand(botEnvironment.channels.deleteConnection, {
+ reportFailure: false,
+ });
+ const attach = useAtomCommand(botEnvironment.channels.attach, { reportFailure: false });
+ const disconnect = useAtomCommand(botEnvironment.channels.disconnect, {
+ 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 [busy, setBusy] = useState(false);
+ const [busyConnectionId, setBusyConnectionId] = useState<string | null>(null);
+ const [pendingProfile, setPendingProfile] = useState<{
+ readonly id: string;
+ readonly present: boolean;
+ } | null>(null);
+ const mutationRef = useRef(false);
+ const access = resolveChannelSettingsAccess({
+ 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;
+ const present = connections.some((connection) => connection.id === pendingProfile.id);
+ if (present !== pendingProfile.present) return;
+ mutationRef.current = false;
+ setBusy(false);
+ 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;
+ setBusy(true);
+ const result = await deleteConnection({
+ environmentId,
+ input: { connectionId: connection.id },
+ });
+ if (result._tag === "Failure") {
+ mutationRef.current = false;
+ setBusy(false);
+ toastManager.add({ type: "error", title: "Unassign this channel before deleting it" });
+ return;
+ }
+ setPendingProfile({ id: connection.id, present: false });
+ };
+
+ const updateAssignment = async (connection: ChannelConnectionProfile, nextBotId: string) => {
+ if (!environmentId || busyConnectionId) return;
+ const assignedBot = assignedBotForConnection(connection.id, bots);
+ if (assignedBot?.id === nextBotId) return;
+ setBusyConnectionId(connection.id);
+
+ if (assignedBot) {
+ const result = await disconnect({
+ environmentId,
+ input: { botId: assignedBot.id, provider: connection.provider },
+ });
+ if (result._tag === "Failure") {
+ setBusyConnectionId(null);
+ toastManager.add({ type: "error", title: "Could not unassign channel" });
+ return;
+ }
+ }
+
+ if (nextBotId !== UNASSIGNED) {
+ const result = await attach({
+ environmentId,
+ input: {
+ botId: BotId.make(nextBotId),
+ connectionId: connection.id,
+ provider: connection.provider,
+ },
+ });
+ if (result._tag === "Failure") {
+ const restored = assignedBot
+ ? await attach({
+ environmentId,
+ input: {
+ botId: assignedBot.id,
+ connectionId: connection.id,
+ provider: connection.provider,
+ },
+ })
+ : null;
+ toastManager.add({
+ type: "error",
+ title:
+ restored?._tag === "Failure"
+ ? "Could not assign or restore channel"
+ : "Could not assign channel",
+ });
+ }
+ }
+ setBusyConnectionId(null);
+ };
+
+ if (environmentId === null) {
+ return (
+ <SettingsPageContainer>
+ <div className="px-4 py-8 text-sm text-muted-foreground">Connect an environment first.</div>
+ </SettingsPageContainer>
+ );
+ }
+ if (access === "pending") {
+ return (
+ <SettingsPageContainer>
+ <div className="flex justify-center px-4 py-8">
+ <Spinner aria-label="Loading channel access" />
+ </div>
+ </SettingsPageContainer>
+ );
+ }
+ if (access === "denied") {
+ return (
+ <SettingsPageContainer>
+ <div className="px-4 py-8 text-sm text-muted-foreground">
+ Open this environment on its host to manage channels.
+ </div>
+ </SettingsPageContainer>
+ );
+ }
+
+ 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"
+ role="tablist"
+ aria-label="Channel type"
+ >
+ {CHANNELS.map((channel) => (
+ <button
+ key={channel.provider}
+ type="button"
+ role="tab"
+ aria-selected={provider === channel.provider}
+ onClick={() => setProvider(channel.provider)}
+ className={cn(
+ "h-8 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.label}
+ </button>
+ ))}
+ </div>
+ </SettingsSection>
+
+ <SettingsSection
+ title={CHANNELS.find((channel) => channel.provider === provider)?.label ?? "Channels"}
+ >
+ {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>
+ ) : (
+ providerConnections.map((connection) => {
+ const assignedBot = assignedBotForConnection(connection.id, bots);
+ const connectionBusy = busyConnectionId === connection.id;
+ return (
+ <SettingsRow
+ 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"}
+ </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}
+ <Select
+ value={assignedBot?.id ?? UNASSIGNED}
+ onValueChange={(next) => next && void updateAssignment(connection, next)}
+ >
+ <SelectTrigger
+ aria-label={`Assign ${connection.name}`}
+ className="w-40"
+ disabled={connectionBusy}
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectPopup>
+ <SelectItem value={UNASSIGNED}>Unassigned</SelectItem>
+ {assignedBot?.archivedAt ? (
+ <SelectItem value={assignedBot.id}>
+ {assignedBot.name} (archived)
+ </SelectItem>
+ ) : null}
+ {activeBots.map((bot) => (
+ <SelectItem key={bot.id} value={bot.id}>
+ {bot.name}
+ </SelectItem>
+ ))}
+ </SelectPopup>
+ </Select>
+ <Button
+ variant="outline"
+ disabled={busy || connectionBusy || assignedBot !== undefined}
+ onClick={() => void removeConnection(connection)}
+ >
+ Delete
+ </Button>
+ </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>
+ </SettingsPageContainer>
+ );
+}
diff --git a/apps/web/src/components/settings/GroupPeopleSettings.tsx b/apps/web/src/components/settings/GroupPeopleSettings.tsx
new file mode 100644
index 000000000..dd443d83a
--- /dev/null
+++ b/apps/web/src/components/settings/GroupPeopleSettings.tsx
@@ -0,0 +1,183 @@
+import {
+ type AuthClientSession,
+ type AuthSessionId,
+ type EnvironmentId,
+ type OrchestrationGroup,
+} from "@t3tools/contracts";
+import { LogOutIcon, Trash2Icon, UserPlusIcon } from "lucide-react";
+import { useEffect, useMemo, useState } from "react";
+
+import { botEnvironment } from "../../state/bots";
+import { useAtomCommand } from "../../state/use-atom-command";
+import { openSettings } from "../../settingsDialogStore";
+import { groupPersonMembers } from "../roster/roster.logic";
+import { Button } from "../ui/button";
+import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
+import { toastManager } from "../ui/toast";
+import { SettingsRow } from "./settingsLayout";
+
+export function GroupPeopleSettings({
+ environmentId,
+ group,
+ people,
+ currentPersonId,
+}: {
+ readonly environmentId: EnvironmentId;
+ readonly group: OrchestrationGroup;
+ readonly people: ReadonlyArray<AuthClientSession>;
+ readonly currentPersonId: AuthSessionId | null;
+}) {
+ const assignPerson = useAtomCommand(botEnvironment.groups.assignPerson, {
+ reportFailure: false,
+ });
+ const unassignPerson = useAtomCommand(botEnvironment.groups.unassignPerson, {
+ reportFailure: false,
+ });
+ const leaveGroup = useAtomCommand(botEnvironment.groups.leave, { reportFailure: false });
+ const [personId, setPersonId] = useState("");
+ const [busy, setBusy] = useState(false);
+ const members = useMemo(() => groupPersonMembers(group), [group]);
+ const availablePeople = useMemo(
+ () =>
+ people.filter((person) => !members.some((member) => member.personId === person.sessionId)),
+ [members, people],
+ );
+
+ useEffect(() => {
+ if (!availablePeople.some((person) => person.sessionId === personId)) setPersonId("");
+ }, [availablePeople, personId]);
+
+ 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;
+ };
+
+ return (
+ <>
+ <div className="space-y-1 px-3 pb-3 sm:px-4">
+ {members.map((person) => (
+ <div key={person.personId} className="flex min-h-10 items-center gap-3 rounded-lg px-2">
+ <span className="flex size-7 items-center justify-center rounded-full bg-muted text-xs font-semibold">
+ {person.displayName.slice(0, 1).toUpperCase()}
+ </span>
+ <span className="min-w-0 flex-1 truncate text-sm">
+ {person.personId === currentPersonId ? "You" : person.displayName}
+ </span>
+ {person.personId !== currentPersonId ? (
+ <Button
+ aria-label={`Remove ${person.displayName} from ${group.name}`}
+ disabled={busy}
+ size="icon-sm"
+ variant="ghost"
+ onClick={() =>
+ void run(
+ () =>
+ unassignPerson({
+ environmentId,
+ input: { groupId: group.id, personId: person.personId },
+ }),
+ `Could not remove ${person.displayName}`,
+ )
+ }
+ >
+ <Trash2Icon />
+ </Button>
+ ) : null}
+ </div>
+ ))}
+ </div>
+ <SettingsRow
+ title="Add person"
+ description={
+ availablePeople.length === 0
+ ? "Pair another client in Connections before adding a person."
+ : undefined
+ }
+ control={
+ <div className="flex items-center gap-2">
+ <Select value={personId} onValueChange={(value) => value && setPersonId(value)}>
+ <SelectTrigger aria-label="Person" className="w-44">
+ <SelectValue placeholder="Choose person" />
+ </SelectTrigger>
+ <SelectPopup>
+ {availablePeople.map((person) => (
+ <SelectItem key={person.sessionId} value={person.sessionId}>
+ {person.client.label ?? "Paired person"}
+ </SelectItem>
+ ))}
+ </SelectPopup>
+ </Select>
+ <Button
+ aria-label="Add person"
+ disabled={busy || !personId}
+ size="icon-sm"
+ variant="outline"
+ onClick={() => {
+ const person = availablePeople.find(
+ (candidate) => candidate.sessionId === personId,
+ );
+ if (!person) return;
+ void run(
+ () =>
+ assignPerson({
+ environmentId,
+ input: {
+ groupId: group.id,
+ person: {
+ kind: "person",
+ personId: person.sessionId,
+ displayName: person.client.label ?? "Paired person",
+ },
+ },
+ }),
+ "Could not add person",
+ ).then((success) => success && setPersonId(""));
+ }}
+ >
+ <UserPlusIcon />
+ </Button>
+ </div>
+ }
+ />
+ <SettingsRow
+ title="Invite people"
+ description="Pair another client in Connections."
+ control={
+ <Button variant="outline" onClick={() => openSettings("connections")}>
+ Open Connections
+ </Button>
+ }
+ />
+ {currentPersonId && members.some((person) => person.personId === currentPersonId) ? (
+ <SettingsRow
+ title="Leave group"
+ control={
+ <Button
+ disabled={busy}
+ variant="outline"
+ onClick={() =>
+ void run(
+ () =>
+ leaveGroup({
+ environmentId,
+ input: { groupId: group.id, personId: currentPersonId },
+ }),
+ "Could not leave group",
+ )
+ }
+ >
+ <LogOutIcon />
+ Leave
+ </Button>
+ }
+ />
+ ) : null}
+ </>
+ );
+}
diff --git a/apps/web/src/components/settings/GroupSettingsSection.test.ts b/apps/web/src/components/settings/GroupSettingsSection.test.ts
deleted file mode 100644
index 551d4a389..000000000
--- a/apps/web/src/components/settings/GroupSettingsSection.test.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { BotId, GroupId } from "@t3tools/contracts";
-import { describe, expect, it } from "vite-plus/test";
-
-import { availableSpecialists } from "./GroupSettingsSection";
-
-const bot = (id: string, groupId: string | null, archivedAt: string | null = null) => ({
- id: BotId.make(id),
- name: id,
- groupId: groupId === null ? null : GroupId.make(groupId),
- archivedAt,
-});
-
-describe("group settings", () => {
- it("offers active unassigned bots as specialists", () => {
- expect(
- availableSpecialists([
- bot("free", null),
- bot("assigned", "group-one"),
- bot("archived", null, "2026-08-27T00:00:00.000Z"),
- ]).map((entry) => entry.id),
- ).toEqual(["free"]);
- });
-});
diff --git a/apps/web/src/components/settings/GroupSettingsSection.tsx b/apps/web/src/components/settings/GroupSettingsSection.tsx
deleted file mode 100644
index c4cd9834c..000000000
--- a/apps/web/src/components/settings/GroupSettingsSection.tsx
+++ /dev/null
@@ -1,293 +0,0 @@
-import {
- BotId,
- GROUP_SHARED_WORKSPACE_WARNING,
- GroupId,
- type EnvironmentId,
- type OrchestrationBot,
- type OrchestrationGroup,
-} from "@t3tools/contracts";
-import { Trash2Icon, UserPlusIcon } from "lucide-react";
-import { useEffect, useMemo, useState } from "react";
-
-import { randomUUID } from "../../lib/utils";
-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, SettingsSection } from "./settingsLayout";
-
-export function availableSpecialists(
- bots: ReadonlyArray<Pick<OrchestrationBot, "id" | "name" | "archivedAt" | "groupId">>,
-): ReadonlyArray<Pick<OrchestrationBot, "id" | "name" | "archivedAt" | "groupId">> {
- return bots.filter((bot) => bot.archivedAt === null && bot.groupId === null);
-}
-
-export function GroupSettingsSection({
- environmentId,
- bots,
- groups,
-}: {
- readonly environmentId: EnvironmentId;
- readonly bots: ReadonlyArray<OrchestrationBot>;
- readonly groups: ReadonlyArray<OrchestrationGroup>;
-}) {
- const createGroup = useAtomCommand(botEnvironment.groups.create, { reportFailure: false });
- const deleteGroup = useAtomCommand(botEnvironment.groups.delete, { reportFailure: false });
- const assignMember = useAtomCommand(botEnvironment.groups.assignMember, {
- reportFailure: false,
- });
- const unassignMember = useAtomCommand(botEnvironment.groups.unassignMember, {
- reportFailure: false,
- });
- const setBoss = useAtomCommand(botEnvironment.groups.setBoss, { reportFailure: false });
- const [selectedGroupId, setSelectedGroupId] = useState<string | null>(groups[0]?.id ?? null);
- const [newGroupName, setNewGroupName] = useState("");
- const [newBossId, setNewBossId] = useState<string>(
- bots.find((bot) => bot.groupId === null && bot.archivedAt === null)?.id ?? "",
- );
- const [specialistId, setSpecialistId] = useState("");
- const [busy, setBusy] = useState(false);
- const selectedGroup = groups.find((group) => group.id === selectedGroupId) ?? groups[0] ?? null;
- const unassignedBots = useMemo(() => availableSpecialists(bots), [bots]);
- const members = selectedGroup
- ? selectedGroup.members.flatMap((membership) => {
- const bot = bots.find((candidate) => candidate.id === membership.botId);
- return bot ? [{ bot, role: membership.role }] : [];
- })
- : [];
-
- useEffect(() => {
- if (selectedGroup && selectedGroup.id !== selectedGroupId) {
- setSelectedGroupId(selectedGroup.id);
- }
- }, [selectedGroup, selectedGroupId]);
-
- useEffect(() => {
- if (!unassignedBots.some((bot) => bot.id === newBossId)) {
- setNewBossId(unassignedBots[0]?.id ?? "");
- }
- if (!unassignedBots.some((bot) => bot.id === specialistId)) {
- setSpecialistId("");
- }
- }, [newBossId, specialistId, unassignedBots]);
-
- 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 create = async () => {
- const name = newGroupName.trim();
- if (!name || !newBossId) return;
- const groupId = GroupId.make(`group-${randomUUID()}`);
- if (
- await run(
- () =>
- createGroup({
- environmentId,
- input: { groupId, name, bossBotId: BotId.make(newBossId) },
- }),
- "Could not create group",
- )
- ) {
- setSelectedGroupId(groupId);
- setNewGroupName("");
- }
- };
-
- return (
- <SettingsSection title="Groups">
- <div className="mx-3 mb-3 rounded-lg border border-warning/30 bg-warning/8 px-3 py-2 text-xs leading-5 text-muted-foreground sm:mx-4">
- {GROUP_SHARED_WORKSPACE_WARNING}
- </div>
- <SettingsRow
- title="New group"
- description="Choose one boss. Specialists can be added after creation."
- control={
- <div className="flex w-72 flex-col gap-2">
- <Input
- aria-label="New group name"
- placeholder="Group name"
- value={newGroupName}
- onChange={(event) => setNewGroupName(event.currentTarget.value)}
- />
- <Select value={newBossId} onValueChange={(value) => value && setNewBossId(value)}>
- <SelectTrigger aria-label="New group boss" className="w-full">
- <SelectValue placeholder="Choose boss" />
- </SelectTrigger>
- <SelectPopup>
- {unassignedBots.map((bot) => (
- <SelectItem key={bot.id} value={bot.id}>
- {bot.name}
- </SelectItem>
- ))}
- </SelectPopup>
- </Select>
- <Button
- disabled={busy || !newGroupName.trim() || !newBossId}
- onClick={() => void create()}
- >
- Create group
- </Button>
- </div>
- }
- />
- {selectedGroup ? (
- <>
- <SettingsRow
- title="Manage group"
- control={
- <Select
- value={selectedGroup.id}
- onValueChange={(value) => value && setSelectedGroupId(value)}
- >
- <SelectTrigger aria-label="Group" className="w-52">
- <SelectValue />
- </SelectTrigger>
- <SelectPopup>
- {groups.map((group) => (
- <SelectItem key={group.id} value={group.id}>
- {group.name}
- </SelectItem>
- ))}
- </SelectPopup>
- </Select>
- }
- />
- <SettingsRow
- title="Boss"
- description="Changing the boss keeps the previous boss as a specialist."
- control={
- <Select
- value={selectedGroup.bossBotId ?? ""}
- onValueChange={(botId) => {
- if (!botId || botId === selectedGroup.bossBotId) return;
- void run(
- () =>
- setBoss({
- environmentId,
- input: {
- groupId: selectedGroup.id,
- bossBotId: BotId.make(botId),
- unassignPreviousBoss: false,
- },
- }),
- "Could not change group boss",
- );
- }}
- >
- <SelectTrigger aria-label="Group boss" className="w-52">
- <SelectValue />
- </SelectTrigger>
- <SelectPopup>
- {members.map(({ bot }) => (
- <SelectItem key={bot.id} value={bot.id}>
- {bot.name}
- </SelectItem>
- ))}
- </SelectPopup>
- </Select>
- }
- />
- <div className="space-y-1 px-3 pb-3 sm:px-4">
- {members.map(({ bot, role }) => (
- <div key={bot.id} className="flex min-h-10 items-center gap-3 rounded-lg px-2">
- <span className="min-w-0 flex-1 truncate text-sm">{bot.name}</span>
- <span className="text-xs capitalize text-muted-foreground">{role}</span>
- <Button
- aria-label={`Remove ${bot.name} from ${selectedGroup.name}`}
- disabled={busy || role === "boss"}
- size="icon-sm"
- variant="ghost"
- onClick={() =>
- void run(
- () =>
- unassignMember({
- environmentId,
- input: { groupId: selectedGroup.id, botId: BotId.make(bot.id) },
- }),
- `Could not remove ${bot.name}`,
- )
- }
- >
- <Trash2Icon />
- </Button>
- </div>
- ))}
- </div>
- <SettingsRow
- title="Add specialist"
- control={
- <div className="flex items-center gap-2">
- <Select
- value={specialistId}
- onValueChange={(value) => value && setSpecialistId(value)}
- >
- <SelectTrigger aria-label="Specialist" className="w-44">
- <SelectValue placeholder="Choose bot" />
- </SelectTrigger>
- <SelectPopup>
- {unassignedBots.map((bot) => (
- <SelectItem key={bot.id} value={bot.id}>
- {bot.name}
- </SelectItem>
- ))}
- </SelectPopup>
- </Select>
- <Button
- aria-label="Add specialist"
- disabled={busy || !specialistId}
- size="icon-sm"
- variant="outline"
- onClick={() => {
- if (!specialistId) return;
- void run(
- () =>
- assignMember({
- environmentId,
- input: {
- groupId: selectedGroup.id,
- botId: BotId.make(specialistId),
- role: "specialist",
- },
- }),
- "Could not add specialist",
- ).then((success) => success && setSpecialistId(""));
- }}
- >
- <UserPlusIcon />
- </Button>
- </div>
- }
- />
- <SettingsRow
- title="Delete group"
- description="Bots return to Unassigned. Threads keep their group owner."
- control={
- <Button
- disabled={busy}
- variant="destructive"
- onClick={() =>
- void run(
- () => deleteGroup({ environmentId, input: { groupId: selectedGroup.id } }),
- "Could not delete group",
- )
- }
- >
- Delete group
- </Button>
- }
- />
- </>
- ) : null}
- </SettingsSection>
- );
-}
diff --git a/apps/web/src/components/settings/SettingsDialog.tsx b/apps/web/src/components/settings/SettingsDialog.tsx
index 4d2cf92a3..15a24d3ef 100644
--- a/apps/web/src/components/settings/SettingsDialog.tsx
+++ b/apps/web/src/components/settings/SettingsDialog.tsx
@@ -31,8 +31,8 @@ const InboxPanel = lazy(async () => ({
const ProvidersPanel = lazy(async () => ({
default: (await import("./ProvidersPanel")).ProvidersPanel,
}));
-const BrowserSettingsPanel = lazy(async () => ({
- default: (await import("./BrowserSettings")).BrowserSettingsPanel,
+const BotChannelsSettingsPanel = lazy(async () => ({
+ default: (await import("./BotChannelsSettings")).BotChannelsSettingsPanel,
}));
const VoiceSettingsPanel = lazy(async () => ({
default: (await import("./VoiceSettings")).VoiceSettingsPanel,
diff --git a/apps/web/src/components/settings/settingsSearch.test.ts b/apps/web/src/components/settings/settingsSearch.test.ts
index 6fb7c1c5b..4eead110e 100644
--- a/apps/web/src/components/settings/settingsSearch.test.ts
+++ b/apps/web/src/components/settings/settingsSearch.test.ts
@@ -53,6 +53,12 @@ describe("searchSettings", () => {
expect(searchSettings("xyzzy")).toEqual([]);
});
+ it("finds bot channels by provider name", () => {
+ for (const query of ["telegram", "imessage", "photon", "whatsapp"]) {
+ expect(searchSettings(query).map((item) => item.id)).toContain("bot-channels");
+ }
+ });
+
it("keeps catalog order for multiple title matches", () => {
expect(searchSettings("update", ITEMS).map((item) => item.id)).toEqual([
"provider-updates",
diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts
index bac2d43e6..9a9735c57 100644
--- a/apps/web/src/components/settings/settingsSearch.ts
+++ b/apps/web/src/components/settings/settingsSearch.ts
@@ -18,6 +18,7 @@ export interface SettingsSearchItem {
readonly title: string;
readonly to: SettingsPath;
readonly targetId?: string;
+ readonly keywords?: ReadonlyArray<string>;
// Its row only renders in the desktop app, so a browser result would land on
// an anchor that isn't there.
readonly desktopOnly?: boolean;
@@ -374,6 +375,8 @@ export function searchSettings(
return items.filter(
(item) =>
(isElectron || item.desktopOnly !== true) &&
- normalizeSearchText(item.title).includes(normalizedQuery),
+ [item.title, ...(item.keywords ?? [])].some((value) =>
+ normalizeSearchText(value).includes(normalizedQuery),
+ ),
);
}
diff --git a/apps/web/src/components/sidebar/SidebarChrome.test.ts b/apps/web/src/components/sidebar/SidebarChrome.test.ts
index 71dd7d9c2..99a1457cc 100644
--- a/apps/web/src/components/sidebar/SidebarChrome.test.ts
+++ b/apps/web/src/components/sidebar/SidebarChrome.test.ts
@@ -201,6 +201,17 @@ describe("sidebar footer", () => {
expect(source).not.toContain("touch-none");
});
+ it("keeps group membership out of roster drag and centers pinned items", () => {
+ const source = NodeFS.readFileSync(
+ new URL("../roster/BotRosterSidebar.tsx", import.meta.url),
+ "utf8",
+ );
+
+ expect(source).not.toContain("botEnvironment.groups.assignMember");
+ expect(source).toContain('className="flex justify-center gap-2 overflow-x-auto px-2 py-1"');
+ expect(source).toContain("onContextMenu={(event) => {");
+ });
+
it("keeps short plugin dialogs and the footer independently scrollable", () => {
const sidebarSource = NodeFS.readFileSync(
new URL("./SidebarChrome.tsx", import.meta.url),
diff --git a/apps/web/src/environments/primary/auth.ts b/apps/web/src/environments/primary/auth.ts
index f9381bcad..bdd2327ae 100644
--- a/apps/web/src/environments/primary/auth.ts
+++ b/apps/web/src/environments/primary/auth.ts
@@ -318,12 +318,13 @@ function isTransientBootstrapError(error: unknown): boolean {
}
async function bootstrapServerAuth(): Promise<ServerAuthGateState> {
- const bootstrapCredential = getDesktopBootstrapCredential();
+ const pairingCredential = takePairingTokenFromUrl();
const currentSession = await fetchSessionState();
- if (currentSession.authenticated) {
+ if (currentSession.authenticated && !pairingCredential) {
return { status: "authenticated" };
}
+ const bootstrapCredential = pairingCredential ?? getDesktopBootstrapCredential();
if (!bootstrapCredential) {
return {
status: "requires-auth",
@@ -508,7 +509,7 @@ export async function revokeOtherServerClientSessions(): Promise<number> {
}
export async function resolveInitialServerAuthGateState(): Promise<ServerAuthGateState> {
- if (resolvedAuthenticatedGateState?.status === "authenticated") {
+ if (resolvedAuthenticatedGateState?.status === "authenticated" && !peekPairingTokenFromUrl()) {
return resolvedAuthenticatedGateState;
}
diff --git a/apps/web/src/routes/_chat.groups.$groupId.tsx b/apps/web/src/routes/_chat.groups.$groupId.tsx
index 9a65a2ebc..e69a0a530 100644
--- a/apps/web/src/routes/_chat.groups.$groupId.tsx
+++ b/apps/web/src/routes/_chat.groups.$groupId.tsx
@@ -1,10 +1,35 @@
import { createFileRoute } from "@tanstack/react-router";
+import { useShallow } from "zustand/react/shallow";
+import { GroupDetailsPanel } from "../components/roster/GroupDetailsPanel";
import { GroupThreadLanding } from "../components/roster/GroupThreadLanding";
+import { useRosterStore } from "../components/roster/rosterStore";
+import { usePrimaryEnvironmentId } from "../state/environments";
function GroupThreadRouteView() {
const { groupId } = Route.useParams();
- return <GroupThreadLanding groupId={groupId} />;
+ const navigate = Route.useNavigate();
+ const environmentId = usePrimaryEnvironmentId();
+ const { group, bots } = useRosterStore(
+ useShallow((state) => ({
+ group: state.groups.find((candidate) => candidate.id === groupId) ?? null,
+ bots: state.bots,
+ })),
+ );
+ return (
+ <>
+ <GroupThreadLanding groupId={groupId} />
+ {environmentId && group ? (
+ <GroupDetailsPanel
+ key={group.id}
+ environmentId={environmentId}
+ group={group}
+ bots={bots}
+ onDeleted={() => void navigate({ to: "/" })}
+ />
+ ) : null}
+ </>
+ );
}
export const Route = createFileRoute("/_chat/groups/$groupId")({
diff --git a/apps/web/src/settingsDialogStore.test.ts b/apps/web/src/settingsDialogStore.test.ts
index c341c5a15..c0ef20510 100644
--- a/apps/web/src/settingsDialogStore.test.ts
+++ b/apps/web/src/settingsDialogStore.test.ts
@@ -84,5 +84,6 @@ describe("legacy settings deep links", () => {
expect(settingsSectionFromPathname("/settings")).toBe("general");
expect(settingsSectionFromPathname("/settings/")).toBe("general");
expect(settingsSectionFromPathname("/settings/archived")).toBe("general");
+ expect(settingsSectionFromPathname("/settings/groups")).toBe("general");
});
});
diff --git a/apps/web/src/settingsDialogStore.ts b/apps/web/src/settingsDialogStore.ts
index d9f33d5f0..96de3f5b7 100644
--- a/apps/web/src/settingsDialogStore.ts
+++ b/apps/web/src/settingsDialogStore.ts
@@ -83,6 +83,7 @@ export function closeSettings(): void {
/** Map a legacy `/settings/...` pathname onto a dialog section. */
export function settingsSectionFromPathname(pathname: string): SettingsSection {
const slug = pathname.replace(/^\/settings\/?/, "").split("/")[0] ?? "";
+ if (slug === "bots") return "channels";
return (SETTINGS_SECTIONS as readonly string[]).includes(slug)
? (slug as SettingsSection)
: "general";
diff --git a/apps/web/src/state/bots.ts b/apps/web/src/state/bots.ts
index d4550e6c4..1f3ae03d3 100644
--- a/apps/web/src/state/bots.ts
+++ b/apps/web/src/state/bots.ts
@@ -24,6 +24,26 @@ export const environmentGroupsAtom = Atom.family((environmentId: EnvironmentId)
).pipe(Atom.withLabel(`web-groups:${environmentId}`)),
);
+export const environmentPeopleAtom = Atom.family((environmentId: EnvironmentId) =>
+ Atom.make((get) => {
+ const snapshot = get(environmentSnapshotAtom(environmentId));
+ return {
+ current: snapshot?.currentPersonId
+ ? {
+ id: snapshot.currentPersonId,
+ displayName: snapshot.currentPersonDisplayName ?? "Paired person",
+ }
+ : null,
+ host: snapshot?.environmentHostPersonId
+ ? {
+ id: snapshot.environmentHostPersonId,
+ displayName: snapshot.environmentHostDisplayName ?? "Host",
+ }
+ : null,
+ };
+ }).pipe(Atom.withLabel(`web-people:${environmentId}`)),
+);
+
/** Snapshot presence gates the server-backed roster swap and bootstrap. */
export const environmentRosterLoadedAtom = Atom.family((environmentId: EnvironmentId) =>
Atom.make((get): boolean => get(environmentSnapshotAtom(environmentId)) !== null).pipe(
diff --git a/packages/client-runtime/src/operations/commands.test.ts b/packages/client-runtime/src/operations/commands.test.ts
index e69e65f66..a65167460 100644
--- a/packages/client-runtime/src/operations/commands.test.ts
+++ b/packages/client-runtime/src/operations/commands.test.ts
@@ -5,6 +5,7 @@ import {
EnvironmentId,
GroupId,
McpServerId,
+ MessageId,
ORCHESTRATION_WS_METHODS,
ProjectId,
ThreadId,
@@ -31,6 +32,9 @@ import {
cancelDelegation,
createMcpServer,
createProject,
+ disconnectChannel,
+ reconnectChannel,
+ sendChannelMessage,
settleThread,
setGroupBoss,
stopThreadSession,
@@ -188,6 +192,36 @@ describe("environment commands", () => {
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
);
+ it.effect("dispatches channel lifecycle and send commands", () =>
+ Effect.gen(function* () {
+ const dispatched: ClientOrchestrationCommand[] = [];
+ 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* reconnectChannel({ botId, provider: "telegram" }).pipe(
+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
+ );
+ yield* sendChannelMessage({
+ botId,
+ threadId: ThreadId.make("thread-1"),
+ messageId: MessageId.make("message-1"),
+ }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
+ yield* disconnectChannel({ botId, provider: "telegram" }).pipe(
+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
+ );
+
+ expect(dispatched.map((command) => command.type)).toEqual([
+ "channel.connect",
+ "channel.reconnect",
+ "channel.send",
+ "channel.disconnect",
+ ]);
+ }).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
+ );
+
it.effect("preserves caller metadata for idempotent queued commands", () =>
Effect.gen(function* () {
const dispatched: ClientOrchestrationCommand[] = [];
diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts
index e3999f934..419be0d1f 100644
--- a/packages/client-runtime/src/operations/commands.ts
+++ b/packages/client-runtime/src/operations/commands.ts
@@ -35,11 +35,21 @@ export type CreateBotInput = CommandInput<"bot.create">;
export type UpdateBotInput = CommandInput<"bot.update">;
export type ArchiveBotInput = CommandInput<"bot.archive">;
export type RestoreBotInput = CommandInput<"bot.restore">;
+export type ConnectChannelInput = CommandInput<"channel.connect">;
+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 ReconnectChannelInput = CommandInput<"channel.reconnect">;
+export type SendChannelMessageInput = CommandInput<"channel.send">;
export type CreateGroupInput = CommandInput<"group.create">;
export type RenameGroupInput = CommandInput<"group.rename">;
export type DeleteGroupInput = CommandInput<"group.delete">;
export type AssignGroupMemberInput = CommandInput<"group.member.assign">;
export type UnassignGroupMemberInput = CommandInput<"group.member.unassign">;
+export type AssignGroupPersonInput = CommandInput<"group.person.assign">;
+export type UnassignGroupPersonInput = CommandInput<"group.person.unassign">;
+export type LeaveGroupInput = CommandInput<"group.leave">;
export type SetGroupBossInput = CommandInput<"group.boss.set">;
export type CreateMcpServerInput = CommandInput<"mcp-server.create">;
export type UpdateMcpServerInput = CommandInput<"mcp-server.update">;
@@ -287,6 +297,36 @@ export const unassignGroupMember: (input: UnassignGroupMemberInput) => CommandEf
});
});
+export const assignGroupPerson: (input: AssignGroupPersonInput) => CommandEffect = Effect.fn(
+ "EnvironmentCommands.assignGroupPerson",
+)(function* (input) {
+ return yield* dispatch({
+ ...input,
+ type: "group.person.assign",
+ commandId: yield* commandId(input),
+ });
+});
+
+export const unassignGroupPerson: (input: UnassignGroupPersonInput) => CommandEffect = Effect.fn(
+ "EnvironmentCommands.unassignGroupPerson",
+)(function* (input) {
+ return yield* dispatch({
+ ...input,
+ type: "group.person.unassign",
+ commandId: yield* commandId(input),
+ });
+});
+
+export const leaveGroup: (input: LeaveGroupInput) => CommandEffect = Effect.fn(
+ "EnvironmentCommands.leaveGroup",
+)(function* (input) {
+ return yield* dispatch({
+ ...input,
+ type: "group.leave",
+ commandId: yield* commandId(input),
+ });
+});
+
export const setGroupBoss: (input: SetGroupBossInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.setGroupBoss",
)(function* (input) {
@@ -297,6 +337,70 @@ export const setGroupBoss: (input: SetGroupBossInput) => CommandEffect = Effect.
});
});
+export const connectChannel: (input: ConnectChannelInput) => CommandEffect = Effect.fn(
+ "EnvironmentCommands.connectChannel",
+)(function* (input) {
+ return yield* dispatch({
+ ...input,
+ type: "channel.connect",
+ commandId: yield* commandId(input),
+ });
+});
+
+export const saveChannelConnection: (input: SaveChannelConnectionInput) => CommandEffect =
+ Effect.fn("EnvironmentCommands.saveChannelConnection")(function* (input) {
+ return yield* dispatch({
+ ...input,
+ type: "channel.connection.save",
+ commandId: yield* commandId(input),
+ });
+ });
+
+export const deleteChannelConnection: (input: DeleteChannelConnectionInput) => CommandEffect =
+ Effect.fn("EnvironmentCommands.deleteChannelConnection")(function* (input) {
+ return yield* dispatch({
+ ...input,
+ type: "channel.connection.delete",
+ commandId: yield* commandId(input),
+ });
+ });
+
+export const attachChannel: (input: AttachChannelInput) => CommandEffect = Effect.fn(
+ "EnvironmentCommands.attachChannel",
+)(function* (input) {
+ return yield* dispatch({ ...input, type: "channel.attach", commandId: yield* commandId(input) });
+});
+
+export const disconnectChannel: (input: DisconnectChannelInput) => CommandEffect = Effect.fn(
+ "EnvironmentCommands.disconnectChannel",
+)(function* (input) {
+ return yield* dispatch({
+ ...input,
+ type: "channel.disconnect",
+ commandId: yield* commandId(input),
+ });
+});
+
+export const reconnectChannel: (input: ReconnectChannelInput) => CommandEffect = Effect.fn(
+ "EnvironmentCommands.reconnectChannel",
+)(function* (input) {
+ return yield* dispatch({
+ ...input,
+ type: "channel.reconnect",
+ commandId: yield* commandId(input),
+ });
+});
+
+export const sendChannelMessage: (input: SendChannelMessageInput) => CommandEffect = Effect.fn(
+ "EnvironmentCommands.sendChannelMessage",
+)(function* (input) {
+ return yield* dispatch({
+ ...input,
+ type: "channel.send",
+ commandId: yield* commandId(input),
+ });
+});
+
export const disableMcpServer: (input: DisableMcpServerInput) => CommandEffect = Effect.fn(
"EnvironmentCommands.disableMcpServer",
)(function* (input) {
diff --git a/packages/client-runtime/src/state/bots.ts b/packages/client-runtime/src/state/bots.ts
index f4c93017f..bd7d139f3 100644
--- a/packages/client-runtime/src/state/bots.ts
+++ b/packages/client-runtime/src/state/bots.ts
@@ -5,23 +5,43 @@ import type { EnvironmentRegistry } from "../connection/registry.ts";
import {
type ArchiveBotInput,
type AssignGroupMemberInput,
+ type AssignGroupPersonInput,
type CreateBotInput,
+ type ConnectChannelInput,
+ type SaveChannelConnectionInput,
+ type DeleteChannelConnectionInput,
+ type AttachChannelInput,
+ type DisconnectChannelInput,
+ type ReconnectChannelInput,
+ type SendChannelMessageInput,
type CreateGroupInput,
type DeleteGroupInput,
type RenameGroupInput,
type RestoreBotInput,
type SetGroupBossInput,
type UnassignGroupMemberInput,
+ type UnassignGroupPersonInput,
+ type LeaveGroupInput,
type UpdateBotInput,
archiveBot,
assignGroupMember,
+ assignGroupPerson,
createBot,
+ connectChannel,
+ saveChannelConnection,
+ deleteChannelConnection,
+ attachChannel,
+ disconnectChannel,
+ reconnectChannel,
+ sendChannelMessage,
createGroup,
deleteGroup,
renameGroup,
restoreBot,
setGroupBoss,
unassignGroupMember,
+ unassignGroupPerson,
+ leaveGroup,
updateBot,
} from "../operations/commands.ts";
import { createAtomCommandScheduler, createEnvironmentCommand } from "./runtime.ts";
@@ -29,13 +49,23 @@ import { createAtomCommandScheduler, createEnvironmentCommand } from "./runtime.
export type {
ArchiveBotInput,
AssignGroupMemberInput,
+ AssignGroupPersonInput,
CreateBotInput,
+ ConnectChannelInput,
+ SaveChannelConnectionInput,
+ DeleteChannelConnectionInput,
+ AttachChannelInput,
+ DisconnectChannelInput,
+ ReconnectChannelInput,
+ SendChannelMessageInput,
CreateGroupInput,
DeleteGroupInput,
RenameGroupInput,
RestoreBotInput,
SetGroupBossInput,
UnassignGroupMemberInput,
+ UnassignGroupPersonInput,
+ LeaveGroupInput,
UpdateBotInput,
} from "../operations/commands.ts";
@@ -79,6 +109,48 @@ export function createBotEnvironmentAtoms<R, E>(
scheduler,
concurrency: botConcurrency,
}),
+ channels: {
+ saveConnection: createEnvironmentCommand(runtime, {
+ label: "environment-data:commands:channel:connection:save",
+ execute: (input: SaveChannelConnectionInput) => saveChannelConnection(input),
+ scheduler,
+ }),
+ deleteConnection: createEnvironmentCommand(runtime, {
+ label: "environment-data:commands:channel:connection:delete",
+ execute: (input: DeleteChannelConnectionInput) => deleteChannelConnection(input),
+ scheduler,
+ }),
+ attach: createEnvironmentCommand(runtime, {
+ label: "environment-data:commands:channel:attach",
+ execute: (input: AttachChannelInput) => attachChannel(input),
+ scheduler,
+ concurrency: botConcurrency,
+ }),
+ connect: createEnvironmentCommand(runtime, {
+ label: "environment-data:commands:channel:connect",
+ execute: (input: ConnectChannelInput) => connectChannel(input),
+ scheduler,
+ concurrency: botConcurrency,
+ }),
+ disconnect: createEnvironmentCommand(runtime, {
+ label: "environment-data:commands:channel:disconnect",
+ execute: (input: DisconnectChannelInput) => disconnectChannel(input),
+ scheduler,
+ concurrency: botConcurrency,
+ }),
+ reconnect: createEnvironmentCommand(runtime, {
+ label: "environment-data:commands:channel:reconnect",
+ execute: (input: ReconnectChannelInput) => reconnectChannel(input),
+ scheduler,
+ concurrency: botConcurrency,
+ }),
+ send: createEnvironmentCommand(runtime, {
+ label: "environment-data:commands:channel:send",
+ execute: (input: SendChannelMessageInput) => sendChannelMessage(input),
+ scheduler,
+ concurrency: botConcurrency,
+ }),
+ },
groups: {
create: createEnvironmentCommand(runtime, {
label: "environment-data:commands:group:create",
@@ -110,6 +182,24 @@ export function createBotEnvironmentAtoms<R, E>(
scheduler,
concurrency: groupConcurrency,
}),
+ assignPerson: createEnvironmentCommand(runtime, {
+ label: "environment-data:commands:group:person:assign",
+ execute: (input: AssignGroupPersonInput) => assignGroupPerson(input),
+ scheduler,
+ concurrency: groupConcurrency,
+ }),
+ unassignPerson: createEnvironmentCommand(runtime, {
+ label: "environment-data:commands:group:person:unassign",
+ execute: (input: UnassignGroupPersonInput) => unassignGroupPerson(input),
+ scheduler,
+ concurrency: groupConcurrency,
+ }),
+ leave: createEnvironmentCommand(runtime, {
+ label: "environment-data:commands:group:leave",
+ execute: (input: LeaveGroupInput) => leaveGroup(input),
+ scheduler,
+ concurrency: groupConcurrency,
+ }),
setBoss: createEnvironmentCommand(runtime, {
label: "environment-data:commands:group:boss:set",
execute: (input: SetGroupBossInput) => setGroupBoss(input),
diff --git a/packages/client-runtime/src/state/shellReducer.test.ts b/packages/client-runtime/src/state/shellReducer.test.ts
index 51b429aab..80c9068ba 100644
--- a/packages/client-runtime/src/state/shellReducer.test.ts
+++ b/packages/client-runtime/src/state/shellReducer.test.ts
@@ -94,6 +94,7 @@ const stubBot = {
runtimeMode: "full-access" as const,
usageCap: null,
voiceEnabled: false,
+ channelBindings: [],
groupId: null,
archivedAt: null,
createdAt: "2026-04-01T00:00:00.000Z",
@@ -104,7 +105,7 @@ const stubGroup = {
id: GroupId.make("group-1"),
name: "Engineering",
bossBotId: stubBot.id,
- members: [{ botId: stubBot.id, role: "boss" as const }],
+ members: [{ kind: "bot" as const, botId: stubBot.id, role: "boss" as const }],
createdAt: "2026-04-01T00:00:00.000Z",
updatedAt: "2026-04-01T00:00:00.000Z",
};
diff --git a/packages/client-runtime/src/state/threadReducer.test.ts b/packages/client-runtime/src/state/threadReducer.test.ts
index 2042b2168..95ac9cb53 100644
--- a/packages/client-runtime/src/state/threadReducer.test.ts
+++ b/packages/client-runtime/src/state/threadReducer.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vite-plus/test";
import {
+ AuthSessionId,
CheckpointRef,
CommandId,
EventId,
@@ -367,6 +368,8 @@ describe("applyThreadDetailEvent", () => {
role: "user",
text: "Hello, world!",
turnId: null,
+ authorPersonId: AuthSessionId.make("person-1"),
+ authorDisplayName: "Leo",
streaming: false,
createdAt: "2026-04-01T06:00:00.000Z",
updatedAt: "2026-04-01T06:00:00.000Z",
@@ -377,6 +380,8 @@ describe("applyThreadDetailEvent", () => {
if (result.kind === "updated") {
expect(result.thread.messages).toHaveLength(1);
expect(result.thread.messages[0]?.text).toBe("Hello, world!");
+ expect(result.thread.messages[0]?.authorPersonId).toBe("person-1");
+ expect(result.thread.messages[0]?.authorDisplayName).toBe("Leo");
}
});
diff --git a/packages/client-runtime/src/state/threadReducer.ts b/packages/client-runtime/src/state/threadReducer.ts
index 11604f27d..f5e1bbfc8 100644
--- a/packages/client-runtime/src/state/threadReducer.ts
+++ b/packages/client-runtime/src/state/threadReducer.ts
@@ -303,6 +303,8 @@ export function applyThreadDetailEvent(
? { attachments: event.payload.attachments }
: {}),
turnId: event.payload.turnId,
+ authorPersonId: event.payload.authorPersonId ?? null,
+ authorDisplayName: event.payload.authorDisplayName ?? null,
streaming: event.payload.streaming,
createdAt: event.payload.createdAt,
updatedAt: event.payload.updatedAt,
diff --git a/packages/contracts/src/baseSchemas.ts b/packages/contracts/src/baseSchemas.ts
index ef25b13fc..f4f99a340 100644
--- a/packages/contracts/src/baseSchemas.ts
+++ b/packages/contracts/src/baseSchemas.ts
@@ -60,6 +60,8 @@ export const BotId = makeEntityId("BotId");
export type BotId = typeof BotId.Type;
export const GroupId = makeEntityId("GroupId");
export type GroupId = typeof GroupId.Type;
+export const ChannelConnectionId = makeEntityId("ChannelConnectionId");
+export type ChannelConnectionId = typeof ChannelConnectionId.Type;
export const EnvironmentId = makeEntityId("EnvironmentId");
export type EnvironmentId = typeof EnvironmentId.Type;
export const CommandId = makeEntityId("CommandId");
diff --git a/packages/contracts/src/orchestration.test.ts b/packages/contracts/src/orchestration.test.ts
index 449fb2e42..f2206b414 100644
--- a/packages/contracts/src/orchestration.test.ts
+++ b/packages/contracts/src/orchestration.test.ts
@@ -2,7 +2,7 @@ import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
-import { MessageId } from "./baseSchemas.ts";
+import { ChannelConnectionId, MessageId } from "./baseSchemas.ts";
import {
BotAvatar,
DEFAULT_LOCAL_EXECUTION_MODE,
@@ -10,6 +10,7 @@ import {
DEFAULT_RUNTIME_MODE,
ClientOrchestrationCommand,
ModelSelection,
+ OrchestrationBot,
OrchestrationCommand,
OrchestrationDispatchCommandError,
OrchestrationEvent,
@@ -35,6 +36,7 @@ import {
import { ProviderInstanceId } from "./providerInstance.ts";
const decodeBotAvatar = Schema.decodeUnknownEffect(BotAvatar);
+const decodeOrchestrationBot = Schema.decodeUnknownEffect(OrchestrationBot);
const decodeTurnDiffInput = Schema.decodeUnknownEffect(OrchestrationGetTurnDiffInput);
const decodeFullThreadDiffInput = Schema.decodeUnknownEffect(OrchestrationGetFullThreadDiffInput);
const decodeThreadTurnDiff = Schema.decodeUnknownEffect(ThreadTurnDiff);
@@ -88,6 +90,188 @@ it.effect("decodes every bot avatar variant", () =>
}),
);
+it.effect("decodes live channel commands", () =>
+ Effect.gen(function* () {
+ const telegram = yield* decodeClientOrchestrationCommand({
+ type: "channel.connect",
+ commandId: "connect-telegram",
+ botId: "bot-1",
+ provider: "telegram",
+ token: " token ",
+ });
+ const imessage = yield* decodeClientOrchestrationCommand({
+ type: "channel.connect",
+ commandId: "connect-imessage",
+ botId: "bot-1",
+ provider: "imessage",
+ mode: "hosted",
+ projectId: " photon-project ",
+ projectSecret: " photon-secret ",
+ });
+ const whatsapp = yield* decodeClientOrchestrationCommand({
+ type: "channel.connect",
+ commandId: "connect-whatsapp",
+ botId: "bot-1",
+ provider: "whatsapp",
+ accessToken: " access-token ",
+ appSecret: " app-secret ",
+ phoneNumberId: " phone-number-id ",
+ verifyToken: " verify-token ",
+ });
+ const saveConnection = yield* decodeClientOrchestrationCommand({
+ type: "channel.connection.save",
+ commandId: "save-photon",
+ connectionId: " photon-work ",
+ name: " Work iPhone ",
+ provider: "imessage",
+ mode: "self-hosted",
+ serverUrl: " photon.example:443 ",
+ apiKey: " photon-key ",
+ phone: " +15551234567 ",
+ });
+
+ assert.deepInclude(telegram, { provider: "telegram", token: "token" });
+ assert.deepInclude(imessage, {
+ provider: "imessage",
+ projectId: "photon-project",
+ projectSecret: "photon-secret",
+ });
+ assert.deepInclude(whatsapp, {
+ provider: "whatsapp",
+ accessToken: "access-token",
+ appSecret: "app-secret",
+ phoneNumberId: "phone-number-id",
+ verifyToken: "verify-token",
+ });
+ assert.deepInclude(saveConnection, {
+ connectionId: ChannelConnectionId.make("photon-work"),
+ name: "Work iPhone",
+ provider: "imessage",
+ serverUrl: "photon.example:443",
+ apiKey: "photon-key",
+ phone: "+15551234567",
+ });
+ }),
+);
+
+it.effect("decodes WhatsApp message origins", () =>
+ Effect.gen(function* () {
+ const command = yield* decodeOrchestrationCommand({
+ type: "thread.turn.start",
+ commandId: "turn-whatsapp",
+ threadId: "thread-whatsapp",
+ message: {
+ messageId: "message-whatsapp",
+ role: "user",
+ text: "Hello",
+ attachments: [],
+ channelOrigin: {
+ provider: "whatsapp",
+ externalThreadId: "whatsapp:phone:user",
+ externalSenderId: "user",
+ },
+ },
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ createdAt: "2026-08-27T20:00:00.000Z",
+ });
+
+ assert.equal(command.type, "thread.turn.start");
+ if (command.type !== "thread.turn.start") return;
+ assert.deepEqual(command.message.channelOrigin, {
+ provider: "whatsapp",
+ externalThreadId: "whatsapp:phone:user",
+ externalSenderId: "user",
+ });
+ }),
+);
+
+it.effect("requires credentials for the selected iMessage mode", () =>
+ Effect.gen(function* () {
+ const missingHosted = yield* Effect.exit(
+ decodeClientOrchestrationCommand({
+ type: "channel.connect",
+ commandId: "connect-imessage-hosted",
+ botId: "bot-1",
+ provider: "imessage",
+ mode: "hosted",
+ }),
+ );
+ const missingSelfHosted = yield* Effect.exit(
+ decodeClientOrchestrationCommand({
+ type: "channel.connect",
+ commandId: "connect-imessage-self-hosted",
+ botId: "bot-1",
+ provider: "imessage",
+ mode: "self-hosted",
+ }),
+ );
+
+ assert.strictEqual(missingHosted._tag, "Failure");
+ assert.strictEqual(missingSelfHosted._tag, "Failure");
+ }),
+);
+
+it.effect("strips runtime-owned channel fields from client commands", () =>
+ Effect.gen(function* () {
+ const botUpdate = yield* decodeClientOrchestrationCommand({
+ type: "bot.update",
+ commandId: "update-bot",
+ botId: "bot-1",
+ channelBindings: [
+ {
+ botId: "bot-1",
+ provider: "telegram",
+ status: "connected",
+ externalIdentity: "@forged",
+ connectedAt: "2026-08-27T20:00:00.000Z",
+ sentMessageIds: [],
+ },
+ ],
+ });
+ const turnStart = yield* decodeClientOrchestrationCommand({
+ type: "thread.turn.start",
+ commandId: "start-turn",
+ threadId: "thread-1",
+ message: {
+ messageId: "message-1",
+ role: "user",
+ text: "Hello",
+ attachments: [],
+ channelOrigin: { provider: "telegram", externalThreadId: "forged-chat" },
+ },
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ createdAt: "2026-08-27T20:00:00.000Z",
+ });
+
+ assert.isFalse("channelBindings" in botUpdate);
+ assert.strictEqual(turnStart.type, "thread.turn.start");
+ if (turnStart.type === "thread.turn.start") {
+ assert.isFalse("channelOrigin" in turnStart.message);
+ }
+ }),
+);
+
+it.effect("defaults omitted bot channel bindings", () =>
+ Effect.gen(function* () {
+ const bot = yield* decodeOrchestrationBot({
+ id: "bot-1",
+ name: "Akeru",
+ title: "Agent",
+ avatar: { kind: "dither", seed: "akeru" },
+ engine: null,
+ sandbox: "local",
+ groupId: null,
+ archivedAt: null,
+ createdAt: "2026-08-27T20:00:00.000Z",
+ updatedAt: "2026-08-27T20:00:00.000Z",
+ });
+
+ assert.deepEqual(bot.channelBindings, []);
+ }),
+);
+
it.effect("decodes a dispatch error after its bootstrap thread was deleted", () =>
Effect.gen(function* () {
const error = yield* decodeDispatchCommandError({
diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts
index d87c0e401..af62b7fe9 100644
--- a/packages/contracts/src/orchestration.ts
+++ b/packages/contracts/src/orchestration.ts
@@ -7,7 +7,9 @@ import { ProviderOptionSelections } from "./model.ts";
import { RepositoryIdentity, ThreadEnvMode } from "./environment.ts";
import {
ApprovalRequestId,
+ AuthSessionId,
BotId,
+ ChannelConnectionId,
CheckpointRef,
ClientSurface,
CommandId,
@@ -328,6 +330,26 @@ export const BotUsageCap = Schema.Struct({
});
export type BotUsageCap = typeof BotUsageCap.Type;
+export const ChannelProvider = Schema.Literals(["telegram", "imessage", "whatsapp"]);
+export type ChannelProvider = typeof ChannelProvider.Type;
+export const ChannelBindingStatus = Schema.Literals([
+ "disconnected",
+ "connected",
+ "needs-reconnect",
+ "not-live",
+]);
+export type ChannelBindingStatus = typeof ChannelBindingStatus.Type;
+export const ChannelBinding = Schema.Struct({
+ botId: BotId,
+ connectionId: Schema.optional(ChannelConnectionId),
+ provider: ChannelProvider,
+ status: ChannelBindingStatus,
+ externalIdentity: Schema.NullOr(TrimmedNonEmptyString),
+ connectedAt: Schema.NullOr(IsoDateTime),
+ sentMessageIds: Schema.Array(MessageId).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
+});
+export type ChannelBinding = typeof ChannelBinding.Type;
+
export const OrchestrationBot = Schema.Struct({
id: BotId,
name: TrimmedNonEmptyString,
@@ -345,6 +367,9 @@ export const OrchestrationBot = Schema.Struct({
runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_RUNTIME_MODE))),
usageCap: Schema.NullOr(BotUsageCap).pipe(Schema.withDecodingDefault(Effect.succeed(null))),
voiceEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
+ channelBindings: Schema.Array(ChannelBinding).pipe(
+ Schema.withDecodingDefault(Effect.succeed([])),
+ ),
groupId: Schema.NullOr(GroupId),
archivedAt: Schema.NullOr(IsoDateTime),
createdAt: IsoDateTime,
@@ -355,12 +380,31 @@ export type OrchestrationBot = typeof OrchestrationBot.Type;
export const GroupMembershipRole = Schema.Literals(["boss", "specialist"]);
export type GroupMembershipRole = typeof GroupMembershipRole.Type;
-export const GroupMembership = Schema.Struct({
+export const GroupBotMembership = Schema.Struct({
+ kind: Schema.Literal("bot").pipe(Schema.withDecodingDefault(Effect.succeed("bot" as const))),
botId: BotId,
role: GroupMembershipRole,
});
+export type GroupBotMembership = typeof GroupBotMembership.Type;
+
+export const GroupPersonMembership = Schema.Struct({
+ kind: Schema.Literal("person"),
+ personId: AuthSessionId,
+ displayName: TrimmedNonEmptyString,
+});
+export type GroupPersonMembership = typeof GroupPersonMembership.Type;
+
+export const GroupMembership = Schema.Union([GroupBotMembership, GroupPersonMembership]);
export type GroupMembership = typeof GroupMembership.Type;
+export function isGroupBotMember(member: GroupMembership): member is GroupBotMembership {
+ return member.kind === "bot";
+}
+
+export function isGroupPersonMember(member: GroupMembership): member is GroupPersonMembership {
+ return member.kind === "person";
+}
+
export const GROUP_SHARED_WORKSPACE_WARNING =
"Bots share this workspace. Anyone who can talk to a bot can reach anything the workspace can.";
@@ -374,6 +418,13 @@ export const OrchestrationGroup = Schema.Struct({
});
export type OrchestrationGroup = typeof OrchestrationGroup.Type;
+export const ChannelMessageOrigin = Schema.Struct({
+ provider: ChannelProvider,
+ externalThreadId: TrimmedNonEmptyString,
+ externalSenderId: Schema.optional(TrimmedNonEmptyString),
+});
+export type ChannelMessageOrigin = typeof ChannelMessageOrigin.Type;
+
export const OrchestrationMessageRole = Schema.Literals(["user", "assistant", "system"]);
export type OrchestrationMessageRole = typeof OrchestrationMessageRole.Type;
@@ -664,6 +715,10 @@ export type OrchestrationThreadShell = typeof OrchestrationThreadShell.Type;
export const OrchestrationShellSnapshot = Schema.Struct({
snapshotSequence: NonNegativeInt,
+ currentPersonId: Schema.optional(AuthSessionId),
+ currentPersonDisplayName: Schema.optional(TrimmedNonEmptyString),
+ environmentHostPersonId: Schema.optional(AuthSessionId),
+ environmentHostDisplayName: Schema.optional(TrimmedNonEmptyString),
projects: Schema.Array(OrchestrationProjectShell),
bots: Schema.Array(OrchestrationBot).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
groups: Schema.Array(OrchestrationGroup).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
@@ -885,6 +940,25 @@ const BotCreateCommand = Schema.Struct({
});
const BotUpdateCommand = Schema.Struct({
+ type: Schema.Literal("bot.update"),
+ commandId: CommandId,
+ botId: BotId,
+ name: Schema.optional(TrimmedNonEmptyString),
+ title: Schema.optional(TrimmedNonEmptyString),
+ label: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
+ description: Schema.optional(Schema.NullOr(Schema.String)),
+ disabledMcpServerIds: Schema.optional(Schema.Array(McpServerId)),
+ avatar: Schema.optional(BotAvatar),
+ engine: Schema.optional(Schema.NullOr(BotEngine)),
+ sandbox: Schema.optional(Schema.NullOr(BotSandbox)),
+ runtimeMode: Schema.optional(RuntimeMode),
+ usageCap: Schema.optional(Schema.NullOr(BotUsageCap)),
+ voiceEnabled: Schema.optional(Schema.Boolean),
+ channelBindings: Schema.optional(Schema.Array(ChannelBinding)),
+ groupId: Schema.optional(Schema.NullOr(GroupId)),
+});
+
+const ClientBotUpdateCommand = Schema.Struct({
type: Schema.Literal("bot.update"),
commandId: CommandId,
botId: BotId,
@@ -914,6 +988,124 @@ const BotRestoreCommand = Schema.Struct({
botId: BotId,
});
+const ChannelConnectCommand = Schema.Union([
+ Schema.Struct({
+ type: Schema.Literal("channel.connect"),
+ commandId: CommandId,
+ botId: BotId,
+ provider: Schema.Literal("telegram"),
+ token: TrimmedNonEmptyString,
+ }),
+ Schema.Struct({
+ type: Schema.Literal("channel.connect"),
+ commandId: CommandId,
+ botId: BotId,
+ provider: Schema.Literal("imessage"),
+ mode: Schema.Literal("hosted"),
+ projectId: TrimmedNonEmptyString,
+ projectSecret: TrimmedNonEmptyString,
+ }),
+ Schema.Struct({
+ type: Schema.Literal("channel.connect"),
+ commandId: CommandId,
+ botId: BotId,
+ provider: Schema.Literal("imessage"),
+ mode: Schema.Literal("self-hosted"),
+ serverUrl: TrimmedNonEmptyString,
+ apiKey: TrimmedNonEmptyString,
+ phone: Schema.optional(TrimmedNonEmptyString),
+ }),
+ Schema.Struct({
+ type: Schema.Literal("channel.connect"),
+ commandId: CommandId,
+ botId: BotId,
+ provider: Schema.Literal("whatsapp"),
+ accessToken: TrimmedNonEmptyString,
+ appSecret: TrimmedNonEmptyString,
+ phoneNumberId: TrimmedNonEmptyString,
+ verifyToken: TrimmedNonEmptyString,
+ }),
+]);
+
+const ChannelConnectionSaveCommand = Schema.Union([
+ Schema.Struct({
+ type: Schema.Literal("channel.connection.save"),
+ commandId: CommandId,
+ connectionId: ChannelConnectionId,
+ name: TrimmedNonEmptyString,
+ provider: Schema.Literal("telegram"),
+ token: TrimmedNonEmptyString,
+ }),
+ Schema.Struct({
+ type: Schema.Literal("channel.connection.save"),
+ commandId: CommandId,
+ connectionId: ChannelConnectionId,
+ name: TrimmedNonEmptyString,
+ provider: Schema.Literal("imessage"),
+ mode: Schema.Literal("hosted"),
+ projectId: TrimmedNonEmptyString,
+ projectSecret: TrimmedNonEmptyString,
+ }),
+ Schema.Struct({
+ type: Schema.Literal("channel.connection.save"),
+ commandId: CommandId,
+ connectionId: ChannelConnectionId,
+ name: TrimmedNonEmptyString,
+ provider: Schema.Literal("imessage"),
+ mode: Schema.Literal("self-hosted"),
+ serverUrl: TrimmedNonEmptyString,
+ apiKey: TrimmedNonEmptyString,
+ phone: Schema.optional(TrimmedNonEmptyString),
+ }),
+ Schema.Struct({
+ type: Schema.Literal("channel.connection.save"),
+ commandId: CommandId,
+ connectionId: ChannelConnectionId,
+ name: TrimmedNonEmptyString,
+ provider: Schema.Literal("whatsapp"),
+ accessToken: TrimmedNonEmptyString,
+ appSecret: TrimmedNonEmptyString,
+ phoneNumberId: TrimmedNonEmptyString,
+ verifyToken: TrimmedNonEmptyString,
+ }),
+]);
+
+const ChannelConnectionDeleteCommand = Schema.Struct({
+ type: Schema.Literal("channel.connection.delete"),
+ commandId: CommandId,
+ connectionId: ChannelConnectionId,
+});
+
+const ChannelAttachCommand = Schema.Struct({
+ type: Schema.Literal("channel.attach"),
+ commandId: CommandId,
+ botId: BotId,
+ connectionId: ChannelConnectionId,
+ provider: ChannelProvider,
+});
+
+const ChannelDisconnectCommand = Schema.Struct({
+ type: Schema.Literal("channel.disconnect"),
+ commandId: CommandId,
+ botId: BotId,
+ provider: ChannelProvider,
+});
+
+const ChannelReconnectCommand = Schema.Struct({
+ type: Schema.Literal("channel.reconnect"),
+ commandId: CommandId,
+ botId: BotId,
+ provider: ChannelProvider,
+});
+
+const ChannelSendCommand = Schema.Struct({
+ type: Schema.Literal("channel.send"),
+ commandId: CommandId,
+ botId: BotId,
+ threadId: ThreadId,
+ messageId: MessageId,
+});
+
const GroupCreateCommand = Schema.Struct({
type: Schema.Literal("group.create"),
commandId: CommandId,
@@ -923,6 +1115,7 @@ const GroupCreateCommand = Schema.Struct({
// missing-boss rejection instead of a generic schema failure.
bossBotId: Schema.optional(BotId),
specialistBotIds: Schema.optional(Schema.Array(BotId)),
+ creator: Schema.optional(GroupPersonMembership),
createdAt: IsoDateTime,
});
@@ -954,6 +1147,27 @@ const GroupMemberUnassignCommand = Schema.Struct({
botId: BotId,
});
+const GroupPersonAssignCommand = Schema.Struct({
+ type: Schema.Literal("group.person.assign"),
+ commandId: CommandId,
+ groupId: GroupId,
+ person: GroupPersonMembership,
+});
+
+const GroupPersonUnassignCommand = Schema.Struct({
+ type: Schema.Literal("group.person.unassign"),
+ commandId: CommandId,
+ groupId: GroupId,
+ personId: AuthSessionId,
+});
+
+const GroupLeaveCommand = Schema.Struct({
+ type: Schema.Literal("group.leave"),
+ commandId: CommandId,
+ groupId: GroupId,
+ personId: AuthSessionId,
+});
+
const GroupBossSetCommand = Schema.Struct({
type: Schema.Literal("group.boss.set"),
commandId: CommandId,
@@ -1208,6 +1422,7 @@ export const ThreadTurnStartCommand = Schema.Struct({
role: Schema.Literal("user"),
text: Schema.String,
attachments: Schema.Array(ChatAttachment),
+ channelOrigin: Schema.optional(ChannelMessageOrigin),
}),
modelSelection: Schema.optional(ModelSelection),
titleSeed: Schema.optional(TrimmedNonEmptyString),
@@ -1220,6 +1435,9 @@ export const ThreadTurnStartCommand = Schema.Struct({
bootstrap: Schema.optional(ThreadTurnStartBootstrap),
sourceProposedPlan: Schema.optional(SourceProposedPlanReference),
respondingBotId: Schema.optional(BotId),
+ senderPersonId: Schema.optional(AuthSessionId),
+ senderDisplayName: Schema.optional(TrimmedNonEmptyString),
+ senderCanManageGroups: Schema.optional(Schema.Boolean),
createdAt: IsoDateTime,
});
@@ -1322,6 +1540,9 @@ const DispatchableClientOrchestrationCommand = Schema.Union([
GroupDeleteCommand,
GroupMemberAssignCommand,
GroupMemberUnassignCommand,
+ GroupPersonAssignCommand,
+ GroupPersonUnassignCommand,
+ GroupLeaveCommand,
GroupBossSetCommand,
McpServerCreateCommand,
McpServerUpdateCommand,
@@ -1359,14 +1580,24 @@ export const ClientOrchestrationCommand = Schema.Union([
ProjectMetaUpdateCommand,
ProjectDeleteCommand,
BotCreateCommand,
- BotUpdateCommand,
+ ClientBotUpdateCommand,
BotArchiveCommand,
BotRestoreCommand,
+ ChannelConnectCommand,
+ ChannelConnectionSaveCommand,
+ ChannelConnectionDeleteCommand,
+ ChannelAttachCommand,
+ ChannelDisconnectCommand,
+ ChannelReconnectCommand,
+ ChannelSendCommand,
GroupCreateCommand,
GroupRenameCommand,
GroupDeleteCommand,
GroupMemberAssignCommand,
GroupMemberUnassignCommand,
+ GroupPersonAssignCommand,
+ GroupPersonUnassignCommand,
+ GroupLeaveCommand,
GroupBossSetCommand,
McpServerCreateCommand,
McpServerUpdateCommand,
@@ -1547,6 +1778,8 @@ export const OrchestrationEventType = Schema.Literals([
"group.deleted",
"group.member-assigned",
"group.member-unassigned",
+ "group.person-assigned",
+ "group.person-unassigned",
"group.boss-set",
"mcp-server.created",
"mcp-server.updated",
@@ -1554,6 +1787,7 @@ export const OrchestrationEventType = Schema.Literals([
"mcp-server.enabled",
"mcp-server.disabled",
"thread.created",
+ "thread.ownership-updated",
"thread.deleted",
"thread.archived",
"thread.unarchived",
@@ -1643,6 +1877,9 @@ export const BotCreatedPayload = Schema.Struct({
runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_RUNTIME_MODE))),
usageCap: Schema.NullOr(BotUsageCap).pipe(Schema.withDecodingDefault(Effect.succeed(null))),
voiceEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
+ channelBindings: Schema.Array(ChannelBinding).pipe(
+ Schema.withDecodingDefault(Effect.succeed([])),
+ ),
groupId: Schema.NullOr(GroupId),
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
@@ -1661,6 +1898,7 @@ export const BotUpdatedPayload = Schema.Struct({
runtimeMode: Schema.optional(RuntimeMode),
usageCap: Schema.optional(Schema.NullOr(BotUsageCap)),
voiceEnabled: Schema.optional(Schema.Boolean),
+ channelBindings: Schema.optional(Schema.Array(ChannelBinding)),
groupId: Schema.optional(Schema.NullOr(GroupId)),
updatedAt: IsoDateTime,
});
@@ -1699,7 +1937,7 @@ export const GroupDeletedPayload = Schema.Struct({
export const GroupMemberAssignedPayload = Schema.Struct({
groupId: GroupId,
- member: GroupMembership,
+ member: GroupBotMembership,
updatedAt: IsoDateTime,
});
@@ -1709,6 +1947,18 @@ export const GroupMemberUnassignedPayload = Schema.Struct({
updatedAt: IsoDateTime,
});
+export const GroupPersonAssignedPayload = Schema.Struct({
+ groupId: GroupId,
+ person: GroupPersonMembership,
+ updatedAt: IsoDateTime,
+});
+
+export const GroupPersonUnassignedPayload = Schema.Struct({
+ groupId: GroupId,
+ personId: AuthSessionId,
+ updatedAt: IsoDateTime,
+});
+
export const GroupBossSetPayload = Schema.Struct({
groupId: GroupId,
bossBotId: BotId,
@@ -1755,6 +2005,13 @@ export const ThreadCreatedPayload = Schema.Struct({
updatedAt: IsoDateTime,
});
+export const ThreadOwnershipUpdatedPayload = Schema.Struct({
+ threadId: ThreadId,
+ botId: Schema.NullOr(BotId),
+ groupId: Schema.NullOr(GroupId),
+ updatedAt: IsoDateTime,
+});
+
export const ThreadDeletedPayload = Schema.Struct({
threadId: ThreadId,
deletedAt: IsoDateTime,
@@ -1859,6 +2116,9 @@ export const ThreadMessageSentPayload = Schema.Struct({
attachments: Schema.optional(Schema.Array(ChatAttachment)),
turnId: Schema.NullOr(TurnId),
respondingBotId: Schema.optional(Schema.NullOr(BotId)),
+ authorPersonId: Schema.optional(Schema.NullOr(AuthSessionId)),
+ authorDisplayName: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
+ channelOrigin: Schema.optional(Schema.NullOr(ChannelMessageOrigin)),
streaming: Schema.Boolean,
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
@@ -2057,6 +2317,16 @@ export const OrchestrationEvent = Schema.Union([
type: Schema.Literal("group.member-unassigned"),
payload: GroupMemberUnassignedPayload,
}),
+ Schema.Struct({
+ ...EventBaseFields,
+ type: Schema.Literal("group.person-assigned"),
+ payload: GroupPersonAssignedPayload,
+ }),
+ Schema.Struct({
+ ...EventBaseFields,
+ type: Schema.Literal("group.person-unassigned"),
+ payload: GroupPersonUnassignedPayload,
+ }),
Schema.Struct({
...EventBaseFields,
type: Schema.Literal("group.boss-set"),
@@ -2092,6 +2362,11 @@ export const OrchestrationEvent = Schema.Union([
type: Schema.Literal("thread.created"),
payload: ThreadCreatedPayload,
}),
+ Schema.Struct({
+ ...EventBaseFields,
+ type: Schema.Literal("thread.ownership-updated"),
+ payload: ThreadOwnershipUpdatedPayload,
+ }),
Schema.Struct({
...EventBaseFields,
type: Schema.Literal("thread.deleted"),
diff --git a/packages/contracts/src/portability.test.ts b/packages/contracts/src/portability.test.ts
new file mode 100644
index 000000000..b4eb34b97
--- /dev/null
+++ b/packages/contracts/src/portability.test.ts
@@ -0,0 +1,21 @@
+import { assert, it } from "@effect/vitest";
+import * as Effect from "effect/Effect";
+import * as Schema from "effect/Schema";
+
+import { PortabilityGroupData } from "./portability.ts";
+
+const decodePortabilityGroupData = Schema.decodeUnknownEffect(PortabilityGroupData);
+
+it.effect("rejects person memberships in portable group records", () =>
+ Effect.gen(function* () {
+ const result = yield* Effect.exit(
+ decodePortabilityGroupData({
+ name: "Product",
+ bossBotId: "bot-1",
+ members: [{ kind: "person", personId: "person-1", role: "specialist" }],
+ }),
+ );
+
+ assert.strictEqual(result._tag, "Failure");
+ }),
+);
diff --git a/packages/contracts/src/portability.ts b/packages/contracts/src/portability.ts
index 27d6a9476..8a4cb5b70 100644
--- a/packages/contracts/src/portability.ts
+++ b/packages/contracts/src/portability.ts
@@ -20,7 +20,7 @@ import {
BotSandboxBrowserSharing,
PersistedBotSandbox,
BotUsageCap,
- GroupMembership,
+ GroupBotMembership,
ModelSelection,
OrchestrationMessageRole,
OrchestrationProposedPlanId,
@@ -100,7 +100,7 @@ export type PortabilityBotData = typeof PortabilityBotData.Type;
export const PortabilityGroupData = Schema.Struct({
name: TrimmedNonEmptyString,
bossBotId: Schema.NullOr(BotId),
- members: Schema.Array(GroupMembership),
+ members: Schema.Array(GroupBotMembership),
});
export type PortabilityGroupData = typeof PortabilityGroupData.Type;
diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts
index 72eeac6f3..9d25d7eef 100644
--- a/packages/contracts/src/rpc.ts
+++ b/packages/contracts/src/rpc.ts
@@ -177,7 +177,7 @@ import {
ResourceTelemetrySnapshot,
} from "./resourceTelemetry.ts";
import { UsageReadError, UsageSummary, UsageSummaryInput } from "./usage.ts";
-import { ServerSettings, ServerSettingsError, ServerSettingsPatch } from "./settings.ts";
+import { ServerSettings, ServerSettingsError, ServerSettingsRpcPatch } from "./settings.ts";
import {
BotInboxItem,
BotInboxResolveInput,
@@ -410,7 +410,7 @@ export const WsServerGetSettingsRpc = Rpc.make(WS_METHODS.serverGetSettings, {
});
export const WsServerUpdateSettingsRpc = Rpc.make(WS_METHODS.serverUpdateSettings, {
- payload: Schema.Struct({ patch: ServerSettingsPatch }),
+ payload: Schema.Struct({ patch: ServerSettingsRpcPatch }),
success: ServerSettings,
error: Schema.Union([ServerSettingsError, EnvironmentAuthorizationError]),
});
diff --git a/packages/contracts/src/settings.test.ts b/packages/contracts/src/settings.test.ts
index fa5f62c74..ab2aed2da 100644
--- a/packages/contracts/src/settings.test.ts
+++ b/packages/contracts/src/settings.test.ts
@@ -11,12 +11,14 @@ import {
resolveProviderInstanceEnabled,
ServerSettings,
ServerSettingsPatch,
+ ServerSettingsRpcPatch,
} from "./settings.ts";
const decodeClientSettings = Schema.decodeUnknownSync(ClientSettingsSchema);
const decodeClientSettingsPatch = Schema.decodeUnknownSync(ClientSettingsPatch);
const decodeServerSettings = Schema.decodeUnknownSync(ServerSettings);
const decodeServerSettingsPatch = Schema.decodeUnknownSync(ServerSettingsPatch);
+const decodeServerSettingsRpcPatch = Schema.decodeUnknownSync(ServerSettingsRpcPatch);
const encodeServerSettings = Schema.encodeSync(ServerSettings);
const decodeClaudeSettings = Schema.decodeUnknownSync(ClaudeSettings);
diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts
index 925026582..09d38ebd8 100644
--- a/packages/contracts/src/settings.ts
+++ b/packages/contracts/src/settings.ts
@@ -2,7 +2,8 @@ import * as Effect from "effect/Effect";
import * as Duration from "effect/Duration";
import * as Schema from "effect/Schema";
import * as SchemaTransformation from "effect/SchemaTransformation";
-import { TrimmedNonEmptyString, TrimmedString } from "./baseSchemas.ts";
+import * as Struct from "effect/Struct";
+import { ChannelConnectionId, TrimmedNonEmptyString, TrimmedString } from "./baseSchemas.ts";
import { ThreadEnvMode } from "./environment.ts";
import {
DEFAULT_TEXT_GENERATION_MODEL,
@@ -14,6 +15,7 @@ import {
BotSandboxBrowserSharing,
DEFAULT_BOT_SANDBOX_BROWSER_SHARING,
DEFAULT_LOCAL_EXECUTION_MODE,
+ ChannelProvider,
LocalExecutionMode,
ModelSelection,
} from "./orchestration.ts";
@@ -665,6 +667,16 @@ export const BackgroundActivitySettings = Schema.Struct({
}).pipe(Schema.withDecodingDefault(Effect.succeed({})));
export type BackgroundActivitySettings = typeof BackgroundActivitySettings.Type;
+export const ChannelConnectionProfile = Schema.Struct({
+ id: ChannelConnectionId,
+ provider: ChannelProvider,
+ adapter: Schema.Literals(["telegram", "photon", "whatsapp"]),
+ name: TrimmedNonEmptyString,
+ externalIdentity: Schema.optional(TrimmedNonEmptyString),
+ managementUrl: Schema.optional(TrimmedNonEmptyString),
+});
+export type ChannelConnectionProfile = typeof ChannelConnectionProfile.Type;
+
export const SandboxProvider = BotSandbox;
export type SandboxProvider = BotSandbox;
export type CloudSandboxProvider = Exclude<SandboxProvider, "local">;
@@ -813,6 +825,9 @@ export const ServerSettings = Schema.Struct({
providerInstances: Schema.Record(ProviderInstanceId, ProviderInstanceConfig).pipe(
Schema.withDecodingDefault(Effect.succeed({})),
),
+ channelConnections: Schema.Array(ChannelConnectionProfile).pipe(
+ Schema.withDecodingDefault(Effect.succeed([])),
+ ),
sandbox: SandboxSettings,
observability: ObservabilitySettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
});
@@ -983,7 +998,7 @@ const SandboxSettingsPatch = Schema.Struct({
),
});
-export const ServerSettingsPatch = Schema.Struct({
+const ServerSettingsPatchFields = {
// Server settings
enableLegacyTokenStreaming: Schema.optionalKey(Schema.Boolean),
enableProviderUpdateChecks: Schema.optionalKey(Schema.Boolean),
@@ -1052,9 +1067,16 @@ export const ServerSettingsPatch = Schema.Struct({
// patches risk leaving driver-specific config in a half-merged state.
// The web UI sends a fully-formed map every time it edits this field.
providerInstances: Schema.optionalKey(Schema.Record(ProviderInstanceId, ProviderInstanceConfig)),
-});
+ channelConnections: Schema.optionalKey(Schema.Array(ChannelConnectionProfile)),
+} as const;
+export const ServerSettingsPatch = Schema.Struct(ServerSettingsPatchFields);
export type ServerSettingsPatch = typeof ServerSettingsPatch.Type;
+export const ServerSettingsRpcPatch = Schema.Struct(
+ Struct.omit(ServerSettingsPatchFields, ["channelConnections"]),
+);
+export type ServerSettingsRpcPatch = typeof ServerSettingsRpcPatch.Type;
+
export const ClientSettingsPatch = Schema.Struct({
reviewedPrivacyPolicyVersion: Schema.optionalKey(TrimmedString),
reviewedTermsVersion: Schema.optionalKey(TrimmedString),
diff --git a/packages/shared/src/serverSettings.ts b/packages/shared/src/serverSettings.ts
index 69fc9eaac..256b00083 100644
--- a/packages/shared/src/serverSettings.ts
+++ b/packages/shared/src/serverSettings.ts
@@ -188,6 +188,9 @@ export function applyServerSettingsPatch(
...(patch.providerInstances !== undefined
? { providerInstances: patch.providerInstances }
: {}),
+ ...(patch.channelConnections !== undefined
+ ? { channelConnections: patch.channelConnections }
+ : {}),
...(patch.sourceControlWriterModelSelection !== undefined
? { sourceControlWriterModelSelection: patch.sourceControlWriterModelSelection }
: {}),
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 004f5c503..ab205e2e6 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -455,6 +455,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/state-memory':
+ specifier: 4.39.0
+ '@chat-adapter/whatsapp':
+ specifier: 4.39.0
'@daytona/sdk':
specifier: ^0.207.0
@@ -485,9 +491,15 @@ importers:
'@mastra/memory':
specifier: 1.28.0
+ '@mastra/telegram':
+ specifier: 0.1.0
'@opencode-ai/sdk':
specifier: ^1.3.15
version: 1.15.13
+ '@photon-ai/chat-adapter-imessage':
+ specifier: 3.2.0
'@pierre/diffs':
specifier: 'catalog:'
version: 1.3.0-beta.10(patch_hash=7ef7cb0cbabb17c15cdb137554068b36f15f6f5265e73fb51452aa3380db91aa)(@shikijs/[email protected])([email protected]([email protected]))([email protected])
@@ -497,6 +509,9 @@ importers:
'@vercel/sandbox':
specifier: ^2.5.0
version: 2.9.2
+ chat:
+ specifier: 4.39.0
e2b:
specifier: ^2.32.0
version: 2.46.1
@@ -585,6 +600,9 @@ importers:
'@formkit/auto-animate':
specifier: ^0.9.0
version: 0.9.0
+ '@hello-pangea/dnd':
+ specifier: 18.0.1
'@hugeicons/core-free-icons':
specifier: ^4.3.0
version: 4.3.0
@@ -2121,6 +2139,22 @@ packages:
resolution: {integrity: sha512-CuNiSqg7+e1cO/GjffyMOm5Tt2jUF9CWHHnvQ/UkqvtkGfHdgwEC0wpmq7fkN3gxwpRnrAN0WzO3vREKmNolMQ==}
engines: {node: '>=18'}
+ '@chat-adapter/[email protected]':
+ resolution: {integrity: sha512-zc5mB5rYqbp4ts+Z3tG/YwkCypPYphriYpG95ZMRNGiEYx3cYZJZFmAFFM4YLfdz3VIQ99Fd0HFDYVNyAMV7cg==}
+ engines: {node: '>=20'}
+
+ '@chat-adapter/[email protected]':
+ resolution: {integrity: sha512-sTslMdRA9MG2MYUF9anD+eatZ1o3Nu64TkQCJ9GrGWfRCefM8DnIG/Op+Ej9XS6XjqOORb3eDJvy6IpvWrfT4A==}
+ engines: {node: '>=20'}
+
+ '@chat-adapter/[email protected]':
+ resolution: {integrity: sha512-mzifgrQ50UTrBOqzcqiixK9FlNUniqgfBSOAXWyufDr/1xTHibbmSxVeHqnuupGEwqOX2o4r7bl0TwoG7qJ2yQ==}
+ engines: {node: '>=20'}
+
+ '@chat-adapter/[email protected]':
+ resolution: {integrity: sha512-rI35+Iixl/S7J4UYDJEJJ4GhRtjaCDV2JLelMhRV6KJ2h5tQ07OMsTRtwT9PBv91C2bhMaGYOQ2alNkhzcdvVw==}
+ engines: {node: '>=20'}
+
'@chevrotain/[email protected]':
resolution: {integrity: sha512-U+HFai5+zmJCkK86QsaJtoITlboZHBqrVketcO2ROv865xfCMSFpELQoz1GkX5GzME8pTa+3kbKrZHQtI0gdbw==}
@@ -3168,6 +3202,12 @@ packages:
engines: {node: '>=6'}
hasBin: true
+ '@hello-pangea/[email protected]':
+ resolution: {integrity: sha512-xojVWG8s/TGrKT1fC8K2tIWeejJYTAeJuj36zM//yEm/ZrnZUSFGS15BpO+jGZT1ybWvyXmeDJwPYb4dhWlbZQ==}
+ peerDependencies:
+ react: ^18.0.0 || ^19.0.0
+ react-dom: ^18.0.0 || ^19.0.0
+
resolution: {integrity: sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw==}
engines: {node: '>=18.14.1'}
@@ -3703,6 +3743,12 @@ packages:
'@mastra/core': '>=1.0.0-0 <2.0.0-0'
zod: '>=3.0.0 || >=4.0.0'
+ '@mastra/[email protected]':
+ resolution: {integrity: sha512-BNbi2YuYuiQKoX+3uC/kYEQugeeKCkqDeg7ox6+Ys1pYKGqGZs2r0nIr7VfuBYotPhnmu+ZHthmCD8PYIKD8kQ==}
+ engines: {node: '>=22.13.0'}
+ peerDependencies:
+ '@mastra/core': '>=1.22.0 <2.0.0'
+
'@mermaid-js/[email protected]':
resolution: {integrity: sha512-n12NohV3mrUyUL2o93IgG/ifeW9FTyeJn3zDxkhwa8MJ9Fxg3HQMlA3RiGmD/3UnJvheztkjjQAjA2T4LmUcpw==}
@@ -3914,6 +3960,14 @@ packages:
'@opencode-ai/[email protected]':
resolution: {integrity: sha512-4TwojIoQ8EG6/mVBuUVYZXiFcwNmiiytEnjnvyuvSJjGwFIlw2YIBFxtSVC3FbwwbwHT63teh1RHiQUUC4U5xw==}
+ '@opentelemetry/[email protected]':
+ resolution: {integrity: sha512-fmEWp5kXlGEc3i/lR698Hz41DfGyN4Tbe4g7L1AxSc7fF8Xeh/FQ9Quqpa9dVA413Q1Ad43QOLzU4JoXgbFPWw==}
+ engines: {node: '>=8.0.0'}
+
+ '@opentelemetry/[email protected]':
+ resolution: {integrity: sha512-FFx7YnaYJlIjqWW/AG/yAZ0L/NEY724PipXXXQLdtZPbLwBGbUMTGL1i/esI56TWfTUXxhLfpgrnWJCG8aUJyg==}
+ engines: {node: '>=8.0.0'}
+
'@opentelemetry/[email protected]':
resolution: {integrity: sha512-OlanaW1vv7ufTqQ3/fPLI4arGt5ZoM+P8abOMki6uEYnpRazepSWDwDnnw+la7kE26SHVC18//SMccrDvLKOXQ==}
engines: {node: '>=8.0.0'}
@@ -3944,12 +3998,24 @@ packages:
peerDependencies:
'@opentelemetry/api': '>=1.0.0 <1.10.0'
+ '@opentelemetry/[email protected]':
+ resolution: {integrity: sha512-QAqIj32AtK6+pEVNG7EOVxHdE06RP+FM5qpiEJ4RtDcFIqKUZHYhl7/7UY5efhwmwNAg7j8QbJVBLxMerc0+gw==}
+ engines: {node: ^18.19.0 || >=20.6.0}
+ peerDependencies:
+ '@opentelemetry/api': '>=1.0.0 <1.10.0'
+
'@opentelemetry/[email protected]':
resolution: {integrity: sha512-txG1G0IrYSsKKMeiWZfj/i5cQmWB+h+hf3HzPpF3RqZVwp+iQQEIsv8Vtmzy6RWVdHdJZfygmVrBI39YTBvWcw==}
engines: {node: ^18.19.0 || >=20.6.0}
peerDependencies:
'@opentelemetry/api': ^1.3.0
+ '@opentelemetry/[email protected]':
+ resolution: {integrity: sha512-Qx+4rpVHzgg89dawcWRHyt+XRXeLnhFz/qBtvggmjkcgPUdr+NAB0/u/eIPA8yAeJV0J80Vz43JZCh/XFvZFGw==}
+ engines: {node: ^18.19.0 || >=20.6.0}
+ peerDependencies:
+ '@opentelemetry/api': ^1.3.0
+
'@opentelemetry/[email protected]':
resolution: {integrity: sha512-nKXkr4Tomi6fjYVOf+ytcW3dZAVr4v4Bv5gsT6dr2gvpUPJpKgHB4XbMufMsPotRE3g0XH2GwVVCkN2w6SON+Q==}
engines: {node: ^18.19.0 || >=20.6.0}
@@ -3968,6 +4034,12 @@ packages:
peerDependencies:
'@opentelemetry/api': ^1.3.0
+ '@opentelemetry/[email protected]':
+ resolution: {integrity: sha512-bV7d2OuMpZu2+gAaxUAhzfZ0h3WVZk8ETQUEE3DNSntbTaMpuITjtm8I0rNyHFdm7Ax57K6ty7SgFXlBmOLIvQ==}
+ engines: {node: ^18.19.0 || >=20.6.0}
+ peerDependencies:
+ '@opentelemetry/api': ^1.3.0
+
'@opentelemetry/[email protected]':
resolution: {integrity: sha512-sRfCKbOzgy8xZQV2as0RzIZlnCmCseCKZGLfRcrpo2CBngJDr+rPtX0zkG0+oUCV5kfQPUoW3W3C96Ag3Y/Clg==}
engines: {node: ^18.19.0 || >=20.6.0}
@@ -3992,6 +4064,12 @@ packages:
peerDependencies:
'@opentelemetry/api': ^1.3.0
+ '@opentelemetry/[email protected]':
+ resolution: {integrity: sha512-8dqezsmPhtKitIK/eTipZhYl9EX2/gNQ5zUMhaz3uxEURwfkNf8IPvo6yNfrzbxdtpAOybS/+h7wmIWYqFSpiw==}
+ engines: {node: ^18.19.0 || >=20.6.0}
+ peerDependencies:
+ '@opentelemetry/api': ^1.3.0
+
'@opentelemetry/[email protected]':
resolution: {integrity: sha512-AySXiKoC+meiWm6zdVj5T2LnPDZuatveBby1cMOeQteIWsYXAUxs8Sru13G2pVSPrUXz6vF+og7QVBX6GdC/oQ==}
engines: {node: ^18.19.0 || >=20.6.0}
@@ -4016,12 +4094,30 @@ packages:
peerDependencies:
'@opentelemetry/api': ^1.3.0
+ '@opentelemetry/[email protected]':
+ resolution: {integrity: sha512-SnA+0XgGc595jtnwFVfWy7Vgfr5hle4D5YKIlm0U4z8aK9YoCZVUn1xAkVZ2evaJyykiDF50FBzr1XZ0uj8CPA==}
+ engines: {node: ^18.19.0 || >=20.6.0}
+ peerDependencies:
+ '@opentelemetry/api': ^1.7.0
+
+ '@opentelemetry/[email protected]':
+ resolution: {integrity: sha512-X5t7I8GyIO9rmGHwoedZLREpQqrF1WW2nxzNNym6HOKpFiE+rvqV3ngC0xcZVO2YwIGf3KKmRdWrYwdwz3H9RQ==}
+ engines: {node: ^18.19.0 || >=20.6.0}
+ peerDependencies:
+ '@opentelemetry/api': ^1.3.0
+
'@opentelemetry/[email protected]':
resolution: {integrity: sha512-cCk80Z/iRDf/5gfsKMB4f74LqVA5yKETB/9ojPzVW/6/f70iu89nJvGxsFCxx4XfSohaOofkU19kiYm84AiAlw==}
engines: {node: ^18.19.0 || >=20.6.0}
peerDependencies:
'@opentelemetry/api': ^1.3.0
+ '@opentelemetry/[email protected]':
+ resolution: {integrity: sha512-ZwqpkNL5W7RyGJPDZ9g06DvKp8KFTWPJPN12anpMQYSKpTSU0z3EIZuPq9vPGpS8siFyOqDYDAuCwlNO9FqgbA==}
+ engines: {node: ^18.19.0 || >=20.6.0}
+ peerDependencies:
+ '@opentelemetry/api': ^1.3.0
+
'@opentelemetry/[email protected]':
resolution: {integrity: sha512-UFPIq80OH3Ns/oPFHRj14d4DTOxUo+MUFU8hUiCq5jTqFhdeJnfVSANHT+xp92409cA+oxzvlZCe6NM1wvCuBA==}
engines: {node: ^18.19.0 || >=20.6.0}
@@ -4034,6 +4130,12 @@ packages:
peerDependencies:
'@opentelemetry/api': ^1.3.0
+ '@opentelemetry/[email protected]':
+ resolution: {integrity: sha512-CFaKH87WAzjuJ4awowTTLzUvMfaRfiOFG5+qm5S5ncyalRtN4ecQ+YmuANJSCrVPuvZFEkUgKhBPBndxi3rHsQ==}
+ engines: {node: ^18.19.0 || >=20.6.0}
+ peerDependencies:
+ '@opentelemetry/api': ^1.3.0
+
'@opentelemetry/[email protected]':
resolution: {integrity: sha512-lg6lkOU08Az23jVcn/0Els9HP+V8PnR4Km6p0KgpTggS0n/WuhnmY64rSh83Of9iR9nD+dpWr6adlcX8KzAwjg==}
engines: {node: ^18.19.0 || >=20.6.0}
@@ -4058,6 +4160,18 @@ packages:
peerDependencies:
'@opentelemetry/api': '>=1.3.0 <1.10.0'
+ '@opentelemetry/[email protected]':
+ resolution: {integrity: sha512-DeT6KKolmC4e/dRQvMQ/RwlnzhaqeiFOXY5ngoOPJ07GgVVKxZOg9EcrNZb5aTzUn+iCrJldAgOfQm1O/QfPAQ==}
+ engines: {node: ^18.19.0 || >=20.6.0}
+ peerDependencies:
+ '@opentelemetry/api': '>=1.3.0 <1.10.0'
+
+ '@opentelemetry/[email protected]':
+ resolution: {integrity: sha512-QvnNdugatFTVCJXH0Mcu7GOOJSylA9j127kIezOE4YwTI4YbowRons2K4WZTv5FMS8T4q9P0NdaRHdkSmeAIag==}
+ engines: {node: ^18.19.0 || >=20.6.0}
+ peerDependencies:
+ '@opentelemetry/api': '>=1.4.0 <1.10.0'
+
'@opentelemetry/[email protected]':
resolution: {integrity: sha512-FaDcazjyMp7TZZZAsqbo4IkovP0UegoCu0EBkiNt+qCqvUf7FPAsfcrZ3+ZEkKgXZ/jHafop+JoGPDk3A0SmLg==}
engines: {node: ^18.19.0 || >=20.6.0}
@@ -4070,6 +4184,12 @@ packages:
peerDependencies:
'@opentelemetry/api': '>=1.9.0 <1.10.0'
+ '@opentelemetry/[email protected]':
+ resolution: {integrity: sha512-MpDJdkiFDs3Pm1RHO3KByuZbuBdJEXEAkiC0+yJdsZGVCdf1RpHR6n+LHDcS7ffmfrt5kVCzJSCfm4z2C7v0uQ==}
+ engines: {node: ^18.19.0 || >=20.6.0}
+ peerDependencies:
+ '@opentelemetry/api': '>=1.9.0 <1.10.0'
+
'@opentelemetry/[email protected]':
resolution: {integrity: sha512-UbYuvtBrQQB5Prsh9KOKy4kxzexFxfMs5MkteHeWMoswsEB7kiNhyUVkAOFW/qsEzNHtrkgyghrD2ilZJa+5YA==}
engines: {node: ^18.19.0 || >=20.6.0}
@@ -4082,6 +4202,12 @@ packages:
peerDependencies:
'@opentelemetry/api': '>=1.3.0 <1.10.0'
+ '@opentelemetry/[email protected]':
+ resolution: {integrity: sha512-NAYIlsF8MPUsKqJMiDQJTMPOmlbawC1Iz/omMLygZ1C9am8fTKYjTaI+OZM+WTY3t3Glo0wnOg/6/pac6RGPPw==}
+ engines: {node: ^18.19.0 || >=20.6.0}
+ peerDependencies:
+ '@opentelemetry/api': '>=1.3.0 <1.10.0'
+
'@opentelemetry/[email protected]':
resolution: {integrity: sha512-GZK/G6oZyBLGlH1pUgeDch7D91KoHd2uotUGIkWCPi9GI5T9X0p4L7nNAMDR1BQjkRYoDqo+ddfVx9t5Uhys+Q==}
engines: {node: ^18.19.0 || >=20.6.0}
@@ -4409,6 +4535,24 @@ packages:
resolution: {integrity: sha512-ODOov0sGMJMf3jPonOkgGqPknTsu+DdQ7kD++gz8aI+aFMOMHFbWAA2taqXXVTdP+OTOQR/znGvSpmkeI0WTYQ==}
engines: {node: '>=14.18.0'}
+ '@photon-ai/[email protected]':
+ resolution: {integrity: sha512-X5xaXy0SqPa9AuLxD0d/XI04e7WMO2rpXlT94TTMbtVkW0mTlb88fnp3SCwZKl/zEpCC3wQkuEfpNAM2Xgnyww==}
+ engines: {node: '>=18.17'}
+
+ '@photon-ai/[email protected]':
+ resolution: {integrity: sha512-2/cWJDjZ1MsgLlE1+D0iv+sUgMKAkGijVADsmdBPv4wKXbeXaf1vJeXqARGpcyi6ShhhTSNjS6uIGJTq8n6s+w==}
+ peerDependencies:
+ chat: ^4.14.0
+
+ '@photon-ai/[email protected]':
+ resolution: {integrity: sha512-N+fwhvvx/T2tNR8747vFJQgUuLxqyjAVMMLwmakEupgcE4X2M8nbqrfZNSPKN5DL/lpLXYP27a/ACW+jSWAqyA==}
+ engines: {node: '>=20'}
+ peerDependencies:
+ typescript: ^5 || ^6.0.0
+
+ '@photon-ai/[email protected]':
+ resolution: {integrity: sha512-DQANEp0gHvtwqpMGEF0ufa0hs1nniRdsSuo0Q/TG6GoL1WjC5tp59tHFSLUeIm6fvnAuRjREsGzURz3+/69g7g==}
+
'@pierre/[email protected]':
resolution: {integrity: sha512-efyFM9GRfI6WkmHJP0CnZBopuM8yCwGqIKbZHoe1D5PV15VDkr7Vpi8EZt40AYrN1km//utQtYhHDSwt2KwjSg==}
peerDependencies:
@@ -4861,6 +5005,9 @@ packages:
'@react-navigation/[email protected]':
resolution: {integrity: sha512-lblhDXfS75jLc7G2K7BZGM+7cjqQXk13X/MA4fq/12r62zM+fBhhreLzYflSitrDDXFRJpSvJXy0ziiGU04Xow==}
+ '@repeaterjs/[email protected]':
+ resolution: {integrity: sha512-TaoVksZRSx2KWYYpyLQtMQXXeS98VsgZImzW65xmiVgbYhXLk+aEsmzPLirqVuE4/XuUapH2iMtxUzaBNDzdSQ==}
+
'@rolldown/[email protected]':
resolution: {integrity: sha512-b+jTcARdTiFLI6jB4a5XjTm0RWd6KcRfQj/I2356fxUZemiho9zQLxo0RtCuMDAyKcLo6cEltkgbQp6d1+sjjQ==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -5468,6 +5615,21 @@ packages:
'@socket.io/[email protected]':
resolution: {integrity: sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==}
+ '@spectrum-ts/[email protected]':
+ resolution: {integrity: sha512-HtlpDKkgsJJcXx+lmQS53pGI7Uk9GSK4oTyNzUgafymrGsk5F0VhdlEWJTqQvnM74G9WaGzFPcAiPzmoCUBkoQ==}
+ peerDependencies:
+ ffmpeg-static: ^5
+ typescript: ^5 || ^6.0.0
+ peerDependenciesMeta:
+ ffmpeg-static:
+ optional: true
+
+ '@spectrum-ts/[email protected]':
+ resolution: {integrity: sha512-3cLT8VYAwvhZAgci/lCHuYml6B4plUJKkj98nDfKuB9A/NLp6cB27Vjz8YJkZW1SCP9TO02BLt2TBu1zFz6GuA==}
+ peerDependencies:
+ '@spectrum-ts/core': ^10.0.0
+ typescript: ^5 || ^6.0.0
+
'@standard-schema/[email protected]':
resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}
@@ -6040,6 +6202,9 @@ packages:
resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==}
+
resolution: {integrity: sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==}
@@ -6442,6 +6607,9 @@ packages:
resolution: {integrity: sha512-a1wflyaL0tHtJSmLSOVybYhy22vRih4eduhhrkcjgrWGnRfrZtovJ2FRjxuTtkkj47O/baf0R86QU5OuYpz8fA==}
engines: {node: ^20.17.0 || >=22.9.0}
+ resolution: {integrity: sha512-yTt9CI0x+nRfX6BFMenEGP8ooPvErGH6AbFz20C2IeOLIlDsrw/VHpgne3GsCEuTA410IiFiaLVFKmgM4bKEPQ==}
+
resolution: {integrity: sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==}
engines: {node: '>=6.5'}
@@ -7027,6 +7195,10 @@ packages:
resolution: {integrity: sha512-HpX65o1Hnr9HH25ojC1YGs7HCQLq0GCOibSaWER0eNpgJ/Z1MZv2mTc7+xh6WOPxbRVcmgbv4hGU+uSQ/2xFZQ==}
+ resolution: {integrity: sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==}
+ engines: {node: '>=6'}
+
resolution: {integrity: sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==}
engines: {node: '>=10'}
@@ -7068,8 +7240,11 @@ packages:
resolution: {integrity: sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw==}
- resolution: {integrity: sha512-FD6vNLT8clXHKhN3I1m+3Bn2nz0rsB6/bmNPsJeh6Cr7kwWLg0MYl2uor9YaKBp38F77sBRVKdYKVA6ihUby3w==}
+ resolution: {integrity: sha512-rddelWYNPRrXq6PtNEN2S3f6t9ILzvqaN5pVgi4kqt9jHQaXIial9PznB5iSPVlQSLNaaH22ItWz3EJtQ10+OA==}
+
+ resolution: {integrity: sha512-o7D+oAbQAYFVoc9+OH8wya11609ybRThNTF3s/5C1LAABGGi6IrxoQQEN/aIe+4h5pmKYzUjXeqTcuOZcpIAZA==}
engines: {node: '>=20'}
peerDependencies:
ai: ^6.0.182 || ^7.0.0
@@ -7383,6 +7558,9 @@ packages:
resolution: {integrity: sha512-ojKiDvcmByhwa8YYqbQI/hg7MEU0NC03+pSdEq4ZUnZR9xXpwk7E43SMNGkn+JxJGPFtNvQ48+vV2p+P1ml5PA==}
+ resolution: {integrity: sha512-a7Vr4Q/kd/aw96bnJG332W9V9LkJO69JRcaCYDUqjp6/z0w6VcZjgAcTbgFxEPfBgdnAwlh3iwu+hLopa+flJw==}
+
resolution: {integrity: sha512-TizTzUddG/xYLA3NXodFM0fSbNizXjOKhqiQQwvhlspadZokn1KDy0NZFS0wuEubIYAV5/c1/lAr0TaaFXEXzw==}
@@ -8673,6 +8851,9 @@ packages:
resolution: {integrity: sha512-3PYnM29RFXwvAN6Pc/scUfkI7RwhQ/xqyLUyPNlXUp9S40zI8nup9tUSrTLSVnWGBN38FNiGWbwZOB6uR4OGdw==}
+ resolution: {integrity: sha512-9SheyADS50hjvFYjFJ3OB/GlDz2mD1T2CHd7auIk4Uto5YYWPBcw8iYo3F+gENJ+/SOeH9tT0loHZSqlUlumTA==}
+
resolution: {integrity: sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==}
engines: {node: '>=4.0'}
@@ -9942,6 +10123,11 @@ packages:
engines: {node: '>= 20'}
hasBin: true
+ resolution: {integrity: sha512-HnslJfsZkRPBDJRHvVtAaWlZHEpSu7u8LgQuJCELjRKuWR+hpq4A7sLq3p8HaI9ypVoXDXxV34CsQJEe1+J5Aw==}
+ engines: {node: '>= 20'}
+ hasBin: true
+
resolution: {integrity: sha512-ocnPZQLNpvbedwTy9kNrQEsknEfgvcLMvOtz3sFeWApDq1MXH1TqkCIx58xlpESsfwQOnuBO9beyQuNGzVvuhQ==}
@@ -10435,6 +10621,12 @@ packages:
resolution: {integrity: sha512-eonl3sLUha+S1GzTPxychyhnUzKyeQkZ7jLjKrBagJgPla13F+uQ71HgpFefyHgqrjEbCPkDArxYsjY8/+gLKA==}
engines: {node: '>= 0.4.0'}
+ resolution: {integrity: sha512-gOEXlD6ShXZMZ8k+49wm/bA2j1+3IKbEFV9WYREJcvZV4kM5L1KkILYTX9VYBzZF2OuYCe1wp8c82bQkvR0fHw==}
+
+ resolution: {integrity: sha512-pu9xYPlWSeqoYQOCqb2ftQqZi/P2DaI70PSuwnxvoyIRiilaOVtktyPe6LmuXegWB4Ic1sPuDGCnCCASbwzK0w==}
+
resolution: {integrity: sha512-YKLBCcUYKAg0FNlOBT6aI91qFmSiFKiluk655WzPF+DDMA02qIyy8uiRqI8QXtcFpEvll12LpL5MXqEmAZ+dcA==}
@@ -10636,6 +10828,10 @@ packages:
resolution: {integrity: sha512-OHl6PiOEOqxaLHL0N9eFrbzS7IGmu3BtJNH3RTEnRAheCIkfc3gjcjl4sGcjp9C22ZC9YTquDOxSdT/stBQ6BQ==}
os: [win32, darwin, linux]
+ resolution: {integrity: sha512-x0fS3eHxdCox+rFBhQSVe+qBznSPn1pspp8A4BoaVEkiECZEwagEb8z06swLfaFFE2gefj1BvEBeJmdeGTDnYw==}
+ engines: {node: '>=20.0.0'}
+
resolution: {integrity: sha512-MVHddDVweXZF3awtlAS+6pgKLlm/JgxZ90+/NBurBoQctVOOB/zDdVjcyPzQ+0laDGbsWgrRkflI65sQeOgT9Q==}
engines: {node: '>=8'}
@@ -11202,6 +11398,9 @@ packages:
resolution: {integrity: sha512-b484I/7b8rDEdSDKckSSBA8knMpcdsXudlE/LNL639wFoHKwLbEkQFZHWEYwDC0wa0FKUcCY+GAF73Z7wxNVFA==}
+ resolution: {integrity: sha512-tQkJl2GRWh83ui2DiPTJz9wEiMN20syf+5oKfB03yYP7ioZcJwsIK8FjrtLwH1m7C7e+Tt2yYBlrOpdT+dyeIQ==}
+
resolution: {integrity: sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==}
engines: {node: '>= 0.6'}
@@ -11395,6 +11594,18 @@ packages:
peerDependencies:
react: ^19.2.0
+ resolution: {integrity: sha512-KQopgqFo/p/fgmAs5qz6p5RWaNAzq40WAu7fJIXnQpYxFPbJYtsJPWvGeF2rOBaY/kEuV77AVsX8TsQzKm+A/g==}
+ peerDependencies:
+ '@types/react': ^18.2.25 || ^19
+ react: ^18.0 || ^19
+ redux: ^5.0.0
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ redux:
+ optional: true
+
resolution: {integrity: sha512-jCvmsr+1IUSMUyzOkRcvnVbX3ZYC6g9TDrDbFuFmRDq7PD4yaGbLKNQL6k2jnArV8hjYxh7hVhAZB6s9HDGpZA==}
engines: {node: '>=0.10.0'}
@@ -11479,6 +11690,9 @@ packages:
resolution: {integrity: sha512-DJnGAeenTdpMEH6uAJRK/uiyEIH9WVsUmoLwzudwGJUwZPp80PDBWPHXSAGNPwNvIXAbe7MSUB1zQFugFml66A==}
engines: {node: '>=4'}
+ resolution: {integrity: sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==}
+
resolution: {integrity: sha512-OVede/NQE13xBQ+ob5CKd5KyeJYU2YInb1bmV4nRoOfquZPkAkxuOXicSe1PvqIuZZ4kD13sPKBbR7UFDmli6w==}
@@ -12253,6 +12467,9 @@ packages:
resolution: {integrity: sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==}
+ resolution: {integrity: sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==}
+
resolution: {integrity: sha512-qVtvMxeXbVej0cQWKqVSSAHmKZEHAvxdF8HEUBFWts8h+xEo5m/lEiPakuyZ3BnCBjOD8i24kzNOiOLLgsSxhA==}
@@ -12345,6 +12562,9 @@ packages:
resolution: {integrity: sha512-JfJeIHke7y2egdGGgRAvpCwYFUsHlM2gPcrVOxFkznt/4uzQ7HFmvE63iFHVLBJNDuyDOQgijDK/tXH/f6Msjg==}
engines: {node: '>=6.10'}
+ resolution: {integrity: sha512-tLJxacIQUM82IR7JO1UUkKlYuUTmoY9HBJAmNWFzheSlDS5SPMcNIepejHJa4BpPQLAcbRhRf3GDJzyj6rbKvA==}
+
resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}
@@ -12685,6 +12905,9 @@ packages:
react: ^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc
react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc
+ resolution: {integrity: sha512-oLYtZ+GJPjpKS950fw70+HavdP7ZO2Q+xMCMeCyiUKuXkJJJG1/wUjCKTagPryS1gApYjZOWW/khmdLsch8jxg==}
+
resolution: {integrity: sha512-5yXvWDEgqeiYiBe1lbxYF7UMAIm/IcopxMHrMQDq3nvKcjPKIhZklUKL+AE7J7uApI4kwe2snsK+eI6UTj9EHg==}
@@ -14717,6 +14940,44 @@ snapshots:
dependencies:
fontkitten: 1.0.3
+ dependencies:
+ transitivePeerDependencies:
+ - ai
+ - supports-color
+ - workflow
+ - zod
+
+ dependencies:
+ transitivePeerDependencies:
+ - ai
+ - supports-color
+ - workflow
+ - zod
+
+ dependencies:
+ '@chat-adapter/shared': 4.39.0([email protected]([email protected]))([email protected])
+ transitivePeerDependencies:
+ - ai
+ - supports-color
+ - workflow
+ - zod
+
+ dependencies:
+ '@chat-adapter/shared': 4.39.0([email protected]([email protected]))([email protected])
+ transitivePeerDependencies:
+ - ai
+ - supports-color
+ - workflow
+ - zod
+
'@chevrotain/[email protected]': {}
@@ -16068,6 +16329,18 @@ snapshots:
protobufjs: 7.6.5
yargs: 17.7.2
+ dependencies:
+ '@babel/runtime': 7.29.7
+ css-box-model: 1.2.1
+ raf-schd: 4.0.3
+ react: 19.2.6
+ react-dom: 19.2.6([email protected])
+ redux: 5.0.1
+ transitivePeerDependencies:
+ - '@types/react'
+
dependencies:
hono: 4.12.27
@@ -16645,7 +16918,7 @@ snapshots:
'@sindresorhus/slugify': 2.2.1
'@standard-schema/spec': 1.1.0
ajv: 8.20.0
croner: 10.0.1
dotenv: 17.4.2
execa: 9.6.1
@@ -16786,6 +17059,16 @@ snapshots:
- debug
- supports-color
+ dependencies:
+ '@chat-adapter/telegram': 4.39.0([email protected]([email protected]))([email protected])
+ transitivePeerDependencies:
+ - ai
+ - supports-color
+ - workflow
+ - zod
+
'@mermaid-js/[email protected]':
dependencies:
'@chevrotain/types': 11.1.2
@@ -17016,6 +17299,15 @@ snapshots:
dependencies:
cross-spawn: 7.0.6
+ '@opentelemetry/[email protected]':
+ dependencies:
+ '@opentelemetry/api': 1.9.1
+
+ '@opentelemetry/[email protected]':
+ dependencies:
+ '@opentelemetry/api': 1.9.1
+ optional: true
+
'@opentelemetry/[email protected]':
dependencies:
'@opentelemetry/api': 1.9.1
@@ -17039,6 +17331,11 @@ snapshots:
'@opentelemetry/api': 1.9.1
'@opentelemetry/semantic-conventions': 1.43.0
+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':
+ dependencies:
+ '@opentelemetry/api': 1.9.1
+ '@opentelemetry/semantic-conventions': 1.43.0
+
'@opentelemetry/[email protected](@opentelemetry/[email protected])':
dependencies:
'@opentelemetry/api': 1.9.1
@@ -17047,6 +17344,15 @@ snapshots:
'@opentelemetry/otlp-transformer': 0.221.0(@opentelemetry/[email protected])
'@opentelemetry/sdk-logs': 0.221.0(@opentelemetry/[email protected])
+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':
+ dependencies:
+ '@opentelemetry/api': 1.9.1
+ '@opentelemetry/api-logs': 0.218.0
+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-exporter-base': 0.218.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-transformer': 0.218.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-logs': 0.218.0(@opentelemetry/[email protected])
+
'@opentelemetry/[email protected](@opentelemetry/[email protected])':
dependencies:
'@opentelemetry/api': 1.9.1
@@ -17068,6 +17374,15 @@ snapshots:
'@opentelemetry/otlp-grpc-exporter-base': 0.221.0(@opentelemetry/[email protected])
'@opentelemetry/otlp-transformer': 0.221.0(@opentelemetry/[email protected])
+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':
+ dependencies:
+ '@opentelemetry/api': 1.9.1
+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-exporter-base': 0.218.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-transformer': 0.218.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-metrics': 2.7.1(@opentelemetry/[email protected])
+
'@opentelemetry/[email protected](@opentelemetry/[email protected])':
dependencies:
'@opentelemetry/api': 1.9.1
@@ -17100,6 +17415,15 @@ snapshots:
'@opentelemetry/otlp-transformer': 0.221.0(@opentelemetry/[email protected])
'@opentelemetry/sdk-trace': 2.10.0(@opentelemetry/[email protected])
+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':
+ dependencies:
+ '@opentelemetry/api': 1.9.1
+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-exporter-base': 0.218.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-transformer': 0.218.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace-base': 2.7.1(@opentelemetry/[email protected])
+
'@opentelemetry/[email protected](@opentelemetry/[email protected])':
dependencies:
'@opentelemetry/api': 1.9.1
@@ -17132,6 +17456,26 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':
+ dependencies:
+ '@opentelemetry/api': 1.9.1
+ '@opentelemetry/core': 2.10.0(@opentelemetry/[email protected])
+ '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/[email protected])
+ '@opentelemetry/semantic-conventions': 1.43.0
+ transitivePeerDependencies:
+ - supports-color
+ optional: true
+
+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':
+ dependencies:
+ '@opentelemetry/api': 1.9.1
+ '@opentelemetry/api-logs': 0.219.0
+ import-in-the-middle: 3.3.3
+ require-in-the-middle: 8.0.1
+ transitivePeerDependencies:
+ - supports-color
+ optional: true
+
'@opentelemetry/[email protected](@opentelemetry/[email protected])':
dependencies:
'@opentelemetry/api': 1.9.1
@@ -17141,6 +17485,12 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':
+ dependencies:
+ '@opentelemetry/api': 1.9.1
+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-transformer': 0.218.0(@opentelemetry/[email protected])
+
'@opentelemetry/[email protected](@opentelemetry/[email protected])':
dependencies:
'@opentelemetry/api': 1.9.1
@@ -17155,6 +17505,16 @@ snapshots:
'@opentelemetry/otlp-exporter-base': 0.221.0(@opentelemetry/[email protected])
'@opentelemetry/otlp-transformer': 0.221.0(@opentelemetry/[email protected])
+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':
+ dependencies:
+ '@opentelemetry/api': 1.9.1
+ '@opentelemetry/api-logs': 0.218.0
+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-logs': 0.218.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-metrics': 2.7.1(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace-base': 2.7.1(@opentelemetry/[email protected])
+
'@opentelemetry/[email protected](@opentelemetry/[email protected])':
dependencies:
'@opentelemetry/api': 1.9.1
@@ -17181,6 +17541,20 @@ snapshots:
'@opentelemetry/core': 2.10.0(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.43.0
+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':
+ dependencies:
+ '@opentelemetry/api': 1.9.1
+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])
+ '@opentelemetry/semantic-conventions': 1.43.0
+
+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':
+ dependencies:
+ '@opentelemetry/api': 1.9.1
+ '@opentelemetry/api-logs': 0.218.0
+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])
+ '@opentelemetry/semantic-conventions': 1.43.0
+
'@opentelemetry/[email protected](@opentelemetry/[email protected])':
dependencies:
'@opentelemetry/api': 1.9.1
@@ -17195,6 +17569,12 @@ snapshots:
'@opentelemetry/core': 2.10.0(@opentelemetry/[email protected])
'@opentelemetry/resources': 2.10.0(@opentelemetry/[email protected])
+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':
+ dependencies:
+ '@opentelemetry/api': 1.9.1
+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])
+
'@opentelemetry/[email protected](@opentelemetry/[email protected])':
dependencies:
'@opentelemetry/api': 1.9.1
@@ -17236,6 +17616,13 @@ snapshots:
'@opentelemetry/sdk-trace': 2.10.0(@opentelemetry/[email protected])
'@opentelemetry/semantic-conventions': 1.43.0
+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':
+ dependencies:
+ '@opentelemetry/api': 1.9.1
+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])
+ '@opentelemetry/semantic-conventions': 1.43.0
+
'@opentelemetry/[email protected](@opentelemetry/[email protected])':
dependencies:
'@opentelemetry/api': 1.9.1
@@ -17421,6 +17808,54 @@ snapshots:
tslib: 2.8.1
webcrypto-core: 1.9.2
+ '@photon-ai/[email protected]':
+ dependencies:
+ '@bufbuild/protobuf': 2.14.0
+ '@grpc/grpc-js': 1.14.4
+ nice-grpc: 2.1.17
+ nice-grpc-common: 2.0.4
+
+ dependencies:
+ '@chat-adapter/shared': 4.39.0([email protected]([email protected]))([email protected])
+ '@spectrum-ts/core': 10.0.0([email protected])
+ '@spectrum-ts/imessage': 10.0.0(@spectrum-ts/[email protected]([email protected]))([email protected])
+ mime-types: 3.0.2
+ transitivePeerDependencies:
+ - ai
+ - ffmpeg-static
+ - supports-color
+ - typescript
+ - workflow
+ - zod
+
+ dependencies:
+ '@opentelemetry/api': 1.9.1
+ '@opentelemetry/api-logs': 0.218.0
+ '@opentelemetry/context-async-hooks': 2.10.0(@opentelemetry/[email protected])
+ '@opentelemetry/core': 2.10.0(@opentelemetry/[email protected])
+ '@opentelemetry/exporter-logs-otlp-http': 0.218.0(@opentelemetry/[email protected])
+ '@opentelemetry/exporter-metrics-otlp-http': 0.218.0(@opentelemetry/[email protected])
+ '@opentelemetry/exporter-trace-otlp-http': 0.218.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.10.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-logs': 0.218.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-metrics': 2.10.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace-base': 2.10.0(@opentelemetry/[email protected])
+ '@opentelemetry/semantic-conventions': 1.43.0
+ typescript: 6.0.3
+ optionalDependencies:
+ '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/[email protected])
+ '@opentelemetry/instrumentation-undici': 0.29.0(@opentelemetry/[email protected])
+ transitivePeerDependencies:
+ - supports-color
+
+ '@photon-ai/[email protected]':
+ dependencies:
+ '@bufbuild/protobuf': 2.14.0
+ nice-grpc-common: 2.0.4
+
'@pierre/[email protected](patch_hash=7ef7cb0cbabb17c15cdb137554068b36f15f6f5265e73fb51452aa3380db91aa)(@shikijs/[email protected])([email protected]([email protected]))([email protected])':
dependencies:
'@pierre/theme': 1.1.0
@@ -18204,6 +18639,8 @@ snapshots:
dependencies:
nanoid: 3.3.12
+ '@repeaterjs/[email protected]': {}
+
'@rolldown/[email protected]':
optional: true
@@ -18628,6 +19065,32 @@ snapshots:
'@socket.io/[email protected]': {}
+ dependencies:
+ '@photon-ai/otel': 3.7.0([email protected])
+ '@photon-ai/proto': 0.2.4
+ '@repeaterjs/repeater': 3.1.0
+ marked: 18.0.11
+ mime-types: 3.0.2
+ open-graph-scraper: 6.12.0
+ typescript: 6.0.3
+ vcf: 2.1.2
+ zod: 4.4.3
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@photon-ai/advanced-imessage': 1.0.0
+ '@photon-ai/otel': 3.7.0([email protected])
+ '@spectrum-ts/core': 10.0.0([email protected])
+ lru-cache: 11.5.1
+ marked: 18.0.11
+ typescript: 6.0.3
+ zod: 4.4.3
+ transitivePeerDependencies:
+ - supports-color
+
'@standard-schema/[email protected]': {}
'@szmarczak/[email protected]':
@@ -19226,6 +19689,8 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]': {}
+
'@types/[email protected]': {}
@@ -19595,6 +20060,8 @@ snapshots:
+
dependencies:
event-target-shim: 5.0.1
@@ -20469,6 +20936,8 @@ snapshots:
+
@@ -20500,7 +20969,9 @@ snapshots:
+
dependencies:
'@workflow/serde': 4.1.0-beta.2
mdast-util-to-string: 4.0.0
@@ -20535,7 +21006,7 @@ snapshots:
parse5: 7.3.0
parse5-htmlparser2-tree-adapter: 7.1.0
parse5-parser-stream: 7.1.2
- undici: 7.27.1
+ undici: 7.29.0
whatwg-mimetype: 4.0.0
@@ -20817,6 +21288,10 @@ snapshots:
dependencies:
uncrypto: 0.1.3
+ dependencies:
+ tiny-invariant: 1.3.3
+
dependencies:
boolbase: 1.0.0
@@ -22419,6 +22894,8 @@ snapshots:
+
@@ -23669,6 +24146,8 @@ snapshots:
+
@@ -24477,6 +24956,16 @@ snapshots:
+ dependencies:
+ ts-error: 1.0.6
+
+ dependencies:
+ '@grpc/grpc-js': 1.14.4
+ abort-controller-x: 0.5.0
+ nice-grpc-common: 2.0.4
+
dependencies:
'@types/nlcst': 2.0.3
@@ -24694,6 +25183,13 @@ snapshots:
global-agent: 4.1.3
onnxruntime-common: 1.26.0
+ dependencies:
+ chardet: 2.2.0
+ cheerio: 1.2.0
+ iconv-lite: 0.7.2
+ undici: 7.29.0
+
dependencies:
is-docker: 2.2.1
@@ -25328,6 +25824,8 @@ snapshots:
+
@@ -25704,6 +26202,15 @@ snapshots:
react: 19.2.6
scheduler: 0.27.0
+ dependencies:
+ '@types/use-sync-external-store': 0.0.6
+ react: 19.2.6
+ use-sync-external-store: 1.6.0([email protected])
+ optionalDependencies:
+ '@types/react': 19.2.16
+ redux: 5.0.1
+
@@ -25819,6 +26326,8 @@ snapshots:
dependencies:
redis-errors: 1.2.0
+
@@ -26875,6 +27384,8 @@ snapshots:
+
@@ -26942,6 +27453,8 @@ snapshots:
+
@@ -27243,6 +27756,11 @@ snapshots:
- '@types/react-dom'
optional: true
+ dependencies:
+ camelcase: 5.3.1
+ foldline: 1.1.0
+
dependencies:
'@types/unist': 3.0.3