Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(bots): bot management (#4720)

teo0eb5806c91ed
diff --git a/js/app/packages/app/component/settings/BotSettingsList.tsx b/js/app/packages/app/component/settings/BotSettingsList.tsx
new file mode 100644
index 0000000000..086b554d3c
--- /dev/null
+++ b/js/app/packages/app/component/settings/BotSettingsList.tsx
@@ -0,0 +1,120 @@
+import { BotAvatar } from '@channel/Bots/BotAvatar';
+import { LoadingSpinner } from '@core/component/LoadingSpinner';
+import CaretRightIcon from '@phosphor/caret-right.svg';
+import PlusIcon from '@phosphor/plus.svg';
+import RobotIcon from '@phosphor/robot.svg';
+import { useBotChannelsQuery } from '@queries/bots/bots';
+import type { Bot } from '@service-storage/generated/schemas/bot';
+import { Button } from '@ui';
+import { For, Show } from 'solid-js';
+import { SettingsCard, SettingsPage, SettingsSection } from './primitives';
+
+function BotSettingsRow(props: { bot: Bot; onOpen: (botId: string) => void }) {
+ const channelsQuery = useBotChannelsQuery(() => props.bot.id);
+ const channels = () => channelsQuery.data ?? [];
+
+ const channelSummary = () => {
+ if (channelsQuery.isLoading) return 'Loading channels…';
+ if (channels().length === 0) return 'Not in any channels yet';
+ if (channels().length === 1) {
+ return `In ${channels()[0]?.name ?? '1 channel'}`;
+ }
+ return `In ${channels().length} channels`;
+ };
+
+ return (
+ <button
+ type="button"
+ class="flex w-full items-center gap-4 px-6 py-4 text-left outline-none hover:bg-hover focus-visible:bg-hover mobile:items-start mobile:px-4"
+ onClick={() => props.onOpen(props.bot.id)}
+ >
+ <BotAvatar bot={props.bot} size="lg" />
+ <div class="min-w-0 flex-1">
+ <div class="flex min-w-0 items-baseline gap-2">
+ <span class="truncate text-sm font-medium text-ink">
+ {props.bot.name}
+ </span>
+ <span class="truncate text-xs text-ink-extra-muted">
+ @{props.bot.handle}
+ </span>
+ </div>
+ <div class="mt-0.5 truncate text-xs text-ink-muted">
+ {props.bot.description || channelSummary()}
+ </div>
+ <Show when={props.bot.description}>
+ <div class="mt-1 text-xs text-ink-extra-muted">
+ {channelSummary()}
+ </div>
+ </Show>
+ </div>
+ <CaretRightIcon class="size-4 shrink-0 text-ink-extra-muted" />
+ </button>
+ );
+}
+
+export function BotSettingsList(props: {
+ bots?: Bot[];
+ loading: boolean;
+ onCreate: () => void;
+ onOpen: (botId: string) => void;
+}) {
+ return (
+ <SettingsPage
+ title="Bots"
+ description="Create webhook-powered teammates and connect them to channels."
+ actions={
+ <Button variant="cta" size="sm" onClick={props.onCreate}>
+ <PlusIcon />
+ Create bot
+ </Button>
+ }
+ >
+ <SettingsSection
+ title="Your bots"
+ description="Each bot can join multiple channels. Webhook URLs are scoped to the channel."
+ >
+ <SettingsCard>
+ <Show
+ when={!props.loading}
+ fallback={
+ <div class="flex min-h-36 items-center justify-center">
+ <LoadingSpinner class="size-10 p-2" />
+ </div>
+ }
+ >
+ <Show
+ when={(props.bots?.length ?? 0) > 0}
+ fallback={
+ <div class="flex min-h-52 flex-col items-center justify-center px-8 text-center">
+ <div class="flex size-11 items-center justify-center rounded-xl bg-accent-bg text-accent">
+ <RobotIcon class="size-6" />
+ </div>
+ <div class="mt-3 text-sm font-medium text-ink">
+ Create your first bot
+ </div>
+ <div class="mt-1 max-w-80 text-xs text-ink-muted">
+ Bots post to channels through a secure webhook and can be
+ mentioned like any other participant.
+ </div>
+ <Button
+ class="mt-4"
+ variant="cta"
+ size="sm"
+ onClick={props.onCreate}
+ >
+ <PlusIcon />
+ Create bot
+ </Button>
+ </div>
+ }
+ >
+ <For each={props.bots}>
+ {(bot) => <BotSettingsRow bot={bot} onOpen={props.onOpen} />}
+ </For>
+ </Show>
+ </Show>
+ </SettingsCard>
+ </SettingsSection>
+ </SettingsPage>
+ );
+}
diff --git a/js/app/packages/app/component/settings/Bots.tsx b/js/app/packages/app/component/settings/Bots.tsx
new file mode 100644
index 0000000000..b1f76a7620
--- /dev/null
+++ b/js/app/packages/app/component/settings/Bots.tsx
@@ -0,0 +1,66 @@
+import { BotCreate } from '@channel/Bots/BotCreatePage';
+import { BotDetail } from '@channel/Bots/BotDetailPage';
+import {
+ botSettingsRequest,
+ consumeBotSettingsRequest,
+} from '@channel/Bots/botSettingsState';
+import { useBotsQuery } from '@queries/bots/bots';
+import { createEffect, createSignal, on, Show } from 'solid-js';
+import { BotSettingsList } from './BotSettingsList';
+
+type BotSettingsView =
+ | { type: 'list' }
+ | { type: 'create'; initialChannelId?: string }
+ | { type: 'detail'; botId: string };
+
+export function Bots() {
+ const botsQuery = useBotsQuery();
+ const [view, setView] = createSignal<BotSettingsView>({ type: 'list' });
+ const createView = () => {
+ const current = view();
+ return current.type === 'create' ? current : undefined;
+ };
+ const selectedBotId = () => {
+ const current = view();
+ return current.type === 'detail' ? current.botId : undefined;
+ };
+
+ const openCreateBot = (initialChannelId?: string) =>
+ setView({ type: 'create', initialChannelId });
+ const openBot = (botId: string) => setView({ type: 'detail', botId });
+ const showList = () => setView({ type: 'list' });
+
+ createEffect(
+ on(botSettingsRequest, (request) => {
+ if (!request) return;
+ if (request.type === 'create') openCreateBot(request.initialChannelId);
+ else openBot(request.botId);
+ consumeBotSettingsRequest(request.id);
+ })
+ );
+
+ return (
+ <Show
+ when={createView()}
+ fallback={
+ <Show
+ when={selectedBotId()}
+ fallback={
+ <BotSettingsList
+ bots={botsQuery.data}
+ loading={botsQuery.isLoading}
+ onCreate={() => openCreateBot()}
+ onOpen={openBot}
+ />
+ }
+ >
+ {(botId) => <BotDetail botId={botId()} onBack={showList} />}
+ </Show>
+ }
+ >
+ {(create) => (
+ <BotCreate channelId={create().initialChannelId} onBack={showList} />
+ )}
+ </Show>
+ );
+}
diff --git a/js/app/packages/app/component/settings/Settings.tsx b/js/app/packages/app/component/settings/Settings.tsx
index 82e605da77..ef6e63aaf1 100644
--- a/js/app/packages/app/component/settings/Settings.tsx
+++ b/js/app/packages/app/component/settings/Settings.tsx
@@ -1,4 +1,5 @@
import { Billing } from '@app/component/settings/Billing';
+import { Bots } from '@app/component/settings/Bots';
import { useLogout } from '@core/auth/logout';
import { TabsInsetDropdown } from '@core/component/TabsInsetDropdown';
import {
@@ -412,6 +413,11 @@ export function SettingsPanel(props: SettingsPanelProps) {
<Show when={isCurrentTab('Agent')}>
<Agent />
</Show>
+ <Show when={isCurrentTab('Bots')}>
+ <Suspense>
+ <Bots />
+ </Suspense>
+ </Show>
<Show when={isCurrentTab('Admin')}>
<Admin />
</Show>
diff --git a/js/app/packages/block-channel/component/NewChannelBlockAdapter.tsx b/js/app/packages/block-channel/component/NewChannelBlockAdapter.tsx
index 4c38e7776d..680882c2d8 100644
--- a/js/app/packages/block-channel/component/NewChannelBlockAdapter.tsx
+++ b/js/app/packages/block-channel/component/NewChannelBlockAdapter.tsx
@@ -60,6 +60,7 @@ import {
Switch,
} from 'solid-js';
import { ChannelTopLeft } from './Top';
+import { useChannelBotManagement } from './useChannelBotManagement';
const CHANNEL_STATE_ENTRY_KEY = 'channel.state';
@@ -254,6 +255,13 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {
setActiveTabInternal(tab);
};
+ const botManagement = useChannelBotManagement({
+ channelId,
+ hotkeyScopeId: splitPanel.splitHotkeyScope,
+ isPreview,
+ openParticipants: () => setActiveTab('participants'),
+ });
+
// CallContext: which channel has the Call tab selected (for isCallPage(), etc.).
// `createComputed` (not `createEffect`) so this runs before paint and matches
// `activeTab` on the first frame (e.g. deep-link opens on Call tab).
@@ -423,7 +431,13 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {
<ChannelAttachmentsTab channelId={channelId} />
</Match>
<Match when={activeTab() === 'participants'}>
- <ChannelParticipantsTab channelId={channelId} />
+ <ChannelParticipantsTab
+ channelId={channelId}
+ botManagementEnabled={botManagement.enabled()}
+ onCreateBot={botManagement.openCreateBot}
+ inviteBotFocusRequest={botManagement.inviteFocusRequest()}
+ onOpenBot={botManagement.openBot}
+ />
</Match>
<Match when={activeTab() === 'call' && canUseInlineCallTab()}>
<ChannelCallTab
diff --git a/js/app/packages/block-channel/component/useChannelBotManagement.ts b/js/app/packages/block-channel/component/useChannelBotManagement.ts
new file mode 100644
index 0000000000..11aaaf8688
--- /dev/null
+++ b/js/app/packages/block-channel/component/useChannelBotManagement.ts
@@ -0,0 +1,119 @@
+import { useFeatureFlag } from '@app/lib/analytics/posthog';
+import {
+ requestBotCreation,
+ requestBotDetail,
+} from '@channel/Bots/botSettingsState';
+import { channelWebhookUrl } from '@channel/Bots/webhook';
+import { toast } from '@core/component/Toast/Toast';
+import {
+ BOT_MANAGEMENT_FLAG,
+ BOT_MANAGEMENT_OVERRIDE,
+} from '@core/constant/featureFlags';
+import { useSettingsState } from '@core/constant/SettingsState';
+import { useChannelType } from '@core/context/channels';
+import { createHotkeyGroup, registerHotkey } from '@core/hotkey/hotkeys';
+import CopyIcon from '@phosphor/copy.svg';
+import PlusIcon from '@phosphor/plus.svg';
+import RobotIcon from '@phosphor/robot.svg';
+import { ChannelTypeEnum } from '@service-storage/client';
+import { createSignal, onCleanup } from 'solid-js';
+
+type UseChannelBotManagementOptions = {
+ channelId: string;
+ hotkeyScopeId: string;
+ isPreview: boolean;
+ openParticipants: () => void;
+};
+
+export function useChannelBotManagement(
+ options: UseChannelBotManagementOptions
+) {
+ const { openSettings } = useSettingsState();
+ const channelType = useChannelType(options.channelId);
+ const featureFlag = useFeatureFlag(BOT_MANAGEMENT_FLAG, {
+ enabledOverride: BOT_MANAGEMENT_OVERRIDE,
+ });
+ const [inviteFocusRequest, setInviteFocusRequest] = createSignal(0);
+
+ const enabled = () => featureFlag().enabled;
+ const canManageBots = () =>
+ !options.isPreview &&
+ enabled() &&
+ channelType() === ChannelTypeEnum.Private;
+
+ const openCreateBot = () => {
+ requestBotCreation(options.channelId);
+ openSettings('Bots');
+ };
+
+ const openInviteBot = () => {
+ options.openParticipants();
+ setInviteFocusRequest((request) => request + 1);
+ };
+
+ const openBot = (botId: string) => {
+ requestBotDetail(botId);
+ openSettings('Bots');
+ };
+
+ const copyWebhookUrl = async () => {
+ try {
+ await navigator.clipboard.writeText(channelWebhookUrl(options.channelId));
+ toast.success('Webhook URL copied');
+ } catch {
+ toast.failure('Failed to copy webhook URL');
+ }
+ };
+
+ // Unkeyed commands appear in the command menu while this channel's split is
+ // active, even when a child input or message-list scope owns focus.
+ const commandGroup = createHotkeyGroup();
+
+ registerHotkey({
+ scopeId: options.hotkeyScopeId,
+ description: 'Create bot for channel',
+ icon: PlusIcon,
+ keywords: ['webhook', 'automation', 'agent'],
+ displayPriority: 9,
+ condition: canManageBots,
+ keyDownHandler: () => {
+ openCreateBot();
+ return true;
+ },
+ }).withGroup(commandGroup);
+
+ registerHotkey({
+ scopeId: options.hotkeyScopeId,
+ description: 'Invite bot to channel',
+ icon: RobotIcon,
+ keywords: ['add bot', 'webhook', 'participant'],
+ displayPriority: 9,
+ condition: canManageBots,
+ keyDownHandler: () => {
+ openInviteBot();
+ return true;
+ },
+ }).withGroup(commandGroup);
+
+ registerHotkey({
+ scopeId: options.hotkeyScopeId,
+ description: 'Copy channel webhook URL',
+ icon: CopyIcon,
+ keywords: ['bot', 'webhook', 'endpoint'],
+ displayPriority: 8,
+ condition: () => enabled() && !options.isPreview,
+ keyDownHandler: () => {
+ void copyWebhookUrl();
+ return true;
+ },
+ }).withGroup(commandGroup);
+
+ onCleanup(() => commandGroup.dispose());
+
+ return {
+ enabled,
+ inviteFocusRequest,
+ openBot,
+ openCreateBot,
+ };
+}
diff --git a/js/app/packages/channel/Bots/BotAvatar.tsx b/js/app/packages/channel/Bots/BotAvatar.tsx
new file mode 100644
index 0000000000..2eacd51d9c
--- /dev/null
+++ b/js/app/packages/channel/Bots/BotAvatar.tsx
@@ -0,0 +1,24 @@
+import RobotIcon from '@phosphor/robot.svg';
+import type { Bot } from '@service-storage/generated/schemas/bot';
+import { Avatar } from '@ui';
+import { Show } from 'solid-js';
+
+export function BotAvatar(props: {
+ bot: Pick<Bot, 'name' | 'avatar_url'>;
+ size?: 'sm' | 'md' | 'lg';
+}) {
+ return (
+ <Avatar size={props.size ?? 'md'}>
+ <Show
+ when={props.bot.avatar_url}
+ fallback={
+ <Avatar.Fallback>
+ <RobotIcon class="size-4" />
+ </Avatar.Fallback>
+ }
+ >
+ {(avatarUrl) => <Avatar.Image src={avatarUrl()} alt={props.bot.name} />}
+ </Show>
+ </Avatar>
+ );
+}
diff --git a/js/app/packages/channel/Bots/BotCreatePage.tsx b/js/app/packages/channel/Bots/BotCreatePage.tsx
new file mode 100644
index 0000000000..bedd22edb2
--- /dev/null
+++ b/js/app/packages/channel/Bots/BotCreatePage.tsx
@@ -0,0 +1,290 @@
+import { LoadingSpinner } from '@core/component/LoadingSpinner';
+import { toast } from '@core/component/Toast/Toast';
+import { useChannelsContext } from '@core/context/channels';
+import CaretLeftIcon from '@phosphor/caret-left.svg';
+import RobotIcon from '@phosphor/robot.svg';
+import {
+ useCreateBotMutation,
+ useCreateBotTokenMutation,
+} from '@queries/bots/bots';
+import {
+ useAddBotToChannelsMutation,
+ useCreateChannelScopedBotMutation,
+} from '@queries/channel/channel-bots';
+import { ChannelTypeEnum } from '@service-storage/client';
+import type { Bot } from '@service-storage/generated/schemas/bot';
+import { Button } from '@ui';
+import { createMemo, createSignal, Show } from 'solid-js';
+import { createStore } from 'solid-js/store';
+import { BotCreationResult } from './BotCreationResult';
+import { BotFormSection } from './BotFormSection';
+import { BotProfileFields } from './BotProfileFields';
+import {
+ type BotFormErrors,
+ EMPTY_BOT_FORM,
+ slugBotHandle,
+ validateBotForm,
+} from './botForm';
+import { ChannelMultiSelect } from './ChannelMultiSelect';
+import { createBotAvatarUpload } from './createBotAvatarUpload';
+
+type Stage = 'form' | 'creating' | 'ready';
+
+export function BotCreate(props: { channelId?: string; onBack: () => void }) {
+ const channelsContext = useChannelsContext();
+ const createBotMutation = useCreateBotMutation();
+ const createTokenMutation = useCreateBotTokenMutation();
+ const createScopedBotMutation = useCreateChannelScopedBotMutation();
+ const addBotToChannelsMutation = useAddBotToChannelsMutation();
+ const [stage, setStage] = createSignal<Stage>('form');
+ const [handleEdited, setHandleEdited] = createSignal(false);
+ const [errors, setErrors] = createSignal<BotFormErrors>({});
+ const [createdBot, setCreatedBot] = createSignal<Bot>();
+ const [createdChannelIds, setCreatedChannelIds] = createSignal<string[]>([]);
+ const [rawToken, setRawToken] = createSignal<string>();
+ const [tokenFailed, setTokenFailed] = createSignal(false);
+ const [selectedChannelIds, setSelectedChannelIds] = createSignal<string[]>(
+ props.channelId ? [props.channelId] : []
+ );
+ const [form, setForm] = createStore({ ...EMPTY_BOT_FORM });
+ const avatarUpload = createBotAvatarUpload((url) =>
+ setForm('avatarUrl', url)
+ );
+
+ const channelOptions = createMemo(() =>
+ channelsContext
+ .channels()
+ .filter((channel) => channel.channel_type === ChannelTypeEnum.Private)
+ .map((channel) => ({
+ id: channel.id,
+ name: channel.name?.trim() || 'Unnamed channel',
+ }))
+ .sort((a, b) => a.name.localeCompare(b.name))
+ );
+ const resultChannels = createMemo(() => {
+ const selected = new Set(createdChannelIds());
+ return channelOptions().filter((channel) => selected.has(channel.id));
+ });
+ const pending = () => stage() === 'creating' || avatarUpload.uploading();
+
+ const leave = () => {
+ if (pending()) return;
+ props.onBack();
+ };
+
+ const finish = (bot: Bot, token?: string) => {
+ setCreatedBot(bot);
+ setRawToken(token);
+ setStage('ready');
+ };
+
+ const submit = () => {
+ const parsed = validateBotForm({
+ ...form,
+ handle: form.handle || slugBotHandle(form.name),
+ });
+ if (!parsed.success) {
+ setErrors(parsed.errors);
+ return;
+ }
+
+ const values = parsed.data;
+ const channelIds = selectedChannelIds();
+ const [firstChannelId, ...remainingChannelIds] = channelIds;
+ setErrors({});
+ setCreatedChannelIds(channelIds);
+ setStage('creating');
+
+ if (firstChannelId) {
+ createScopedBotMutation.mutate(
+ {
+ channelId: firstChannelId,
+ name: values.name,
+ handle: values.handle,
+ description: values.description || undefined,
+ avatar_url: values.avatarUrl || undefined,
+ token_label: 'webhook',
+ },
+ {
+ onSuccess: async ({ bot, bot_token }) => {
+ if (remainingChannelIds.length > 0) {
+ const result = await addBotToChannelsMutation.mutateAsync({
+ botId: bot.id,
+ channelIds: remainingChannelIds,
+ });
+ setCreatedChannelIds([firstChannelId, ...result.addedChannelIds]);
+ if (result.failedCount > 0) {
+ toast.failure(
+ `${result.failedCount} channel assignment${result.failedCount === 1 ? '' : 's'} could not be completed`
+ );
+ }
+ }
+ finish(bot, bot_token);
+ },
+ onError: () => {
+ setStage('form');
+ toast.failure('Failed to create bot');
+ },
+ }
+ );
+ return;
+ }
+
+ createBotMutation.mutate(
+ {
+ name: values.name,
+ handle: values.handle,
+ description: values.description || undefined,
+ avatarUrl: values.avatarUrl || undefined,
+ },
+ {
+ onSuccess: (bot) => {
+ setCreatedBot(bot);
+ createTokenMutation.mutate(
+ { botId: bot.id, label: 'webhook' },
+ {
+ onSuccess: ({ bearer_token }) => finish(bot, bearer_token),
+ onError: () => {
+ setTokenFailed(true);
+ finish(bot);
+ },
+ }
+ );
+ },
+ onError: () => {
+ setStage('form');
+ toast.failure('Failed to create bot');
+ },
+ }
+ );
+ };
+
+ return (
+ <div class="size-full overflow-y-auto bg-surface text-ink">
+ <main class="mx-auto w-full max-w-[560px] px-8 pt-14 pb-24 mobile:px-5 mobile:pt-8 mobile:pb-12">
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ class="-ml-2 mb-7"
+ disabled={pending()}
+ onClick={leave}
+ >
+ <CaretLeftIcon />
+ Back to bots
+ </Button>
+ <Show when={stage() !== 'ready'}>
+ <header class="flex items-center gap-3">
+ <div class="flex size-10 shrink-0 items-center justify-center rounded-xl border border-edge-muted bg-ink/[0.025] text-ink-muted">
+ <RobotIcon class="size-5" />
+ </div>
+ <div class="min-w-0">
+ <h1 class="text-lg font-semibold tracking-[-0.01em]">
+ Create a bot
+ </h1>
+ <p class="mt-0.5 text-sm text-ink-muted">
+ Give an integration a profile and a secure channel webhook.
+ </p>
+ </div>
+ </header>
+ </Show>
+
+ <Show when={stage() === 'form'}>
+ <form
+ class="mt-8 flex flex-col gap-5"
+ onSubmit={(event) => {
+ event.preventDefault();
+ submit();
+ }}
+ >
+ <BotFormSection
+ title="Profile"
+ description="This is how the bot appears in channels and mentions."
+ >
+ <BotProfileFields
+ value={form}
+ errors={errors()}
+ uploadingAvatar={avatarUpload.uploading()}
+ onUploadAvatar={avatarUpload.open}
+ onNameChange={(value) => {
+ setForm('name', value);
+ setErrors((current) => ({
+ ...current,
+ name: undefined,
+ }));
+ if (!handleEdited()) {
+ setForm('handle', slugBotHandle(value));
+ }
+ }}
+ onHandleChange={(value) => {
+ setHandleEdited(true);
+ setForm('handle', slugBotHandle(value));
+ setErrors((current) => ({
+ ...current,
+ handle: undefined,
+ }));
+ }}
+ onDescriptionChange={(value) => setForm('description', value)}
+ />
+ </BotFormSection>
+
+ <BotFormSection
+ title="Channels"
+ description="Add the bot now to get ready-to-use webhook URLs."
+ >
+ <label class="mb-1.5 block text-xs font-medium">
+ Add to channels <span class="text-ink-muted">· optional</span>
+ </label>
+ <ChannelMultiSelect
+ channelIds={selectedChannelIds()}
+ onChange={setSelectedChannelIds}
+ />
+ <p class="mt-2 text-xs text-ink-muted">
+ Each selected channel gets its own webhook URL. You can change
+ these assignments later.
+ </p>
+ </BotFormSection>
+
+ <div class="flex items-center justify-between gap-4 pt-1">
+ <p class="text-xs text-ink-muted">
+ A webhook token is generated automatically.
+ </p>
+ <div class="flex shrink-0 gap-2">
+ <Button type="button" variant="ghost" size="sm" onClick={leave}>
+ Cancel
+ </Button>
+ <Button type="submit" variant="cta" size="sm">
+ Create bot
+ </Button>
+ </div>
+ </div>
+ </form>
+ </Show>
+
+ <Show when={stage() === 'creating'}>
+ <div class="flex min-h-96 flex-col items-center justify-center gap-4 text-center">
+ <LoadingSpinner class="size-16 p-4" />
+ <div>
+ <div class="text-sm font-medium">Creating your bot…</div>
+ <div class="mt-1 text-xs text-ink-muted">
+ Setting up its profile, channels, and webhook token.
+ </div>
+ </div>
+ </div>
+ </Show>
+
+ <Show when={stage() === 'ready' && createdBot()}>
+ {(bot) => (
+ <BotCreationResult
+ bot={bot()}
+ channels={resultChannels()}
+ token={rawToken()}
+ tokenFailed={tokenFailed()}
+ onDone={leave}
+ />
+ )}
+ </Show>
+ </main>
+ </div>
+ );
+}
diff --git a/js/app/packages/channel/Bots/BotCreationResult.tsx b/js/app/packages/channel/Bots/BotCreationResult.tsx
new file mode 100644
index 0000000000..679511b885
--- /dev/null
+++ b/js/app/packages/channel/Bots/BotCreationResult.tsx
@@ -0,0 +1,114 @@
+import HashIcon from '@phosphor/hash.svg';
+import CheckCircleIcon from '@phosphor-icons/core/assets/fill/check-circle-fill.svg?component-solid';
+import type { Bot } from '@service-storage/generated/schemas/bot';
+import { Button, Surface } from '@ui';
+import { For, Show } from 'solid-js';
+import { BotAvatar } from './BotAvatar';
+import type { BotChannelOption } from './ChannelMultiSelect';
+import { CredentialField } from './CredentialField';
+import { channelWebhookUrl, webhookExample } from './webhook';
+
+export function BotCreationResult(props: {
+ bot: Bot;
+ channels: BotChannelOption[];
+ token?: string;
+ tokenFailed: boolean;
+ onDone: () => void;
+}) {
+ return (
+ <div>
+ <header class="flex items-center gap-3">
+ <div class="flex size-10 shrink-0 items-center justify-center rounded-xl bg-success-bg text-success">
+ <CheckCircleIcon class="size-5" />
+ </div>
+ <div class="min-w-0">
+ <h1 class="text-lg font-semibold tracking-[-0.01em]">Bot created</h1>
+ <p class="mt-0.5 text-sm text-ink-muted">
+ Copy the credentials now. The token is shown only once.
+ </p>
+ </div>
+ </header>
+
+ <Surface
+ depth={2}
+ class="mt-7 flex items-center gap-3 rounded-xl border border-ink/[0.06] p-4"
+ >
+ <BotAvatar bot={props.bot} size="lg" />
+ <div class="min-w-0 flex-1">
+ <div class="truncate text-sm font-medium">{props.bot.name}</div>
+ <div class="truncate text-xs text-ink-muted">@{props.bot.handle}</div>
+ </div>
+ <Show when={props.channels.length > 0}>
+ <div class="flex max-w-64 flex-wrap justify-end gap-1">
+ <For each={props.channels}>
+ {(channel) => (
+ <div class="flex min-w-0 items-center gap-1.5 rounded-md bg-ink/[0.04] px-2 py-1 text-xs text-ink-muted">
+ <HashIcon class="size-3.5 shrink-0" />
+ <span class="max-w-32 truncate">{channel.name}</span>
+ </div>
+ )}
+ </For>
+ </div>
+ </Show>
+ </Surface>
+
+ <div class="mt-7 flex flex-col gap-5">
+ <For each={props.channels}>
+ {(channel) => (
+ <CredentialField
+ label={`${channel.name} webhook URL`}
+ value={channelWebhookUrl(channel.id)}
+ help="Paste into GitHub or any webhook provider"
+ />
+ )}
+ </For>
+
+ <Show
+ when={props.token}
+ fallback={
+ <div class="rounded-lg border border-alert/30 bg-alert-bg px-3 py-2.5 text-xs text-alert-ink">
+ {props.tokenFailed
+ ? 'The bot was created, but its first token could not be generated. Use New token on the Bots settings page to retry.'
+ : 'No token was generated.'}
+ </div>
+ }
+ >
+ {(token) => (
+ <>
+ <CredentialField
+ label="Webhook token"
+ value={token()}
+ help="Send as x-macro-channel-bot-token"
+ />
+ <Show when={props.channels[0]}>
+ {(channel) => (
+ <CredentialField
+ label="Example request"
+ value={webhookExample(
+ channelWebhookUrl(channel().id),
+ token()
+ )}
+ help="Copy and run"
+ />
+ )}
+ </Show>
+ </>
+ )}
+ </Show>
+
+ <Show when={props.channels.length === 0}>
+ <div class="rounded-lg border border-edge-muted bg-ink/[0.025] px-3 py-2.5 text-xs text-ink-muted">
+ Invite this bot to a channel to get its webhook URL. The token above
+ will still work after it is invited.
+ </div>
+ </Show>
+ </div>
+
+ <div class="mt-8 flex justify-end border-t border-edge-muted pt-4">
+ <Button type="button" variant="cta" size="sm" onClick={props.onDone}>
+ Done
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/js/app/packages/channel/Bots/BotDeleteDialog.tsx b/js/app/packages/channel/Bots/BotDeleteDialog.tsx
new file mode 100644
index 0000000000..1b3d448b6b
--- /dev/null
+++ b/js/app/packages/channel/Bots/BotDeleteDialog.tsx
@@ -0,0 +1,54 @@
+import TrashIcon from '@phosphor/trash.svg';
+import { Button, Dialog, Surface } from '@ui';
+
+export function BotDeleteDialog(props: {
+ open: boolean;
+ botName?: string;
+ pending: boolean;
+ onClose: () => void;
+ onConfirm: () => void;
+}) {
+ return (
+ <Dialog
+ open={props.open}
+ onOpenChange={(open) => !open && !props.pending && props.onClose()}
+ position="center"
+ class="w-[90%] max-w-120"
+ >
+ <Surface depth={2} class="rounded-xl text-ink">
+ <div class="border-b border-edge-muted px-5 py-3">
+ <Dialog.Title class="text-sm font-semibold">
+ Delete {props.botName ?? 'bot'}?
+ </Dialog.Title>
+ </div>
+ <div class="flex flex-col gap-4 p-5">
+ <Dialog.Description class="text-sm leading-5 text-ink-muted">
+ This removes the bot from every channel and disables its webhook
+ URLs. This action cannot be undone.
+ </Dialog.Description>
+ <div class="flex justify-end gap-2">
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ disabled={props.pending}
+ onClick={props.onClose}
+ >
+ Cancel
+ </Button>
+ <Button
+ type="button"
+ variant="danger"
+ size="sm"
+ disabled={props.pending}
+ onClick={props.onConfirm}
+ >
+ <TrashIcon />
+ {props.pending ? 'Deleting…' : 'Delete bot'}
+ </Button>
+ </div>
+ </div>
+ </Surface>
+ </Dialog>
+ );
+}
diff --git a/js/app/packages/channel/Bots/BotDetailActions.tsx b/js/app/packages/channel/Bots/BotDetailActions.tsx
new file mode 100644
index 0000000000..e70c543e1a
--- /dev/null
+++ b/js/app/packages/channel/Bots/BotDetailActions.tsx
@@ -0,0 +1,46 @@
+import TrashIcon from '@phosphor/trash.svg';
+import { Button } from '@ui';
+
+type BotDetailActionsProps = {
+ dirty: boolean;
+ pending: boolean;
+ saving: boolean;
+ onBack: () => void;
+ onDelete: () => void;
+};
+
+export function BotDetailActions(props: BotDetailActionsProps) {
+ return (
+ <div class="flex items-center justify-between gap-3 pt-1">
+ <Button
+ type="button"
+ variant="danger"
+ size="sm"
+ disabled={props.pending}
+ onClick={props.onDelete}
+ >
+ <TrashIcon />
+ Delete bot
+ </Button>
+ <div class="flex items-center gap-2">
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ disabled={props.pending}
+ onClick={props.onBack}
+ >
+ Back
+ </Button>
+ <Button
+ type="submit"
+ variant="cta"
+ size="sm"
+ disabled={!props.dirty || props.pending}
+ >
+ {props.saving ? 'Saving…' : 'Save changes'}
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/js/app/packages/channel/Bots/BotDetailPage.tsx b/js/app/packages/channel/Bots/BotDetailPage.tsx
new file mode 100644
index 0000000000..7f500e3ec1
--- /dev/null
+++ b/js/app/packages/channel/Bots/BotDetailPage.tsx
@@ -0,0 +1,289 @@
+import { LoadingSpinner } from '@core/component/LoadingSpinner';
+import { toast } from '@core/component/Toast/Toast';
+import { useChannelsContext } from '@core/context/channels';
+import CaretLeftIcon from '@phosphor/caret-left.svg';
+import {
+ useBotChannelsQuery,
+ useBotQuery,
+ useDeleteBotMutation,
+ useUpdateBotMutation,
+} from '@queries/bots/bots';
+import { useSyncBotChannelsMutation } from '@queries/channel/channel-bots';
+import { Button } from '@ui';
+import { createEffect, createMemo, createSignal, on, Show } from 'solid-js';
+import { createStore } from 'solid-js/store';
+import { BotAvatar } from './BotAvatar';
+import { BotDeleteDialog } from './BotDeleteDialog';
+import { BotDetailActions } from './BotDetailActions';
+import { BotFormSection } from './BotFormSection';
+import { BotProfileFields } from './BotProfileFields';
+import { BotWebhooksSection } from './BotWebhooksSection';
+import {
+ type BotFormErrors,
+ botToFormValues,
+ EMPTY_BOT_FORM,
+ slugBotHandle,
+ validateBotForm,
+} from './botForm';
+import { ChannelMultiSelect } from './ChannelMultiSelect';
+import { CreateBotTokenDialog } from './CreateBotTokenDialog';
+import { createBotAvatarUpload } from './createBotAvatarUpload';
+
+export function BotDetail(props: { botId: string; onBack: () => void }) {
+ const channelsContext = useChannelsContext();
+ const botQuery = useBotQuery(() => props.botId);
+ const botChannelsQuery = useBotChannelsQuery(() => props.botId);
+ const updateBotMutation = useUpdateBotMutation();
+ const deleteBotMutation = useDeleteBotMutation();
+ const syncChannelsMutation = useSyncBotChannelsMutation();
+ const [initialized, setInitialized] = createSignal(false);
+ const [saving, setSaving] = createSignal(false);
+ const [tokenOpen, setTokenOpen] = createSignal(false);
+ const [deleteOpen, setDeleteOpen] = createSignal(false);
+ const [errors, setErrors] = createSignal<BotFormErrors>({});
+ const [channelIds, setChannelIds] = createSignal<string[]>([]);
+ const [initialChannelIds, setInitialChannelIds] = createSignal<string[]>([]);
+ const [initialForm, setInitialForm] = createSignal({ ...EMPTY_BOT_FORM });
+ const [form, setForm] = createStore({ ...EMPTY_BOT_FORM });
+ const avatarUpload = createBotAvatarUpload((url) =>
+ setForm('avatarUrl', url)
+ );
+
+ createEffect(
+ on(
+ [() => botQuery.data, () => botChannelsQuery.data],
+ ([bot, channels]) => {
+ if (initialized() || !bot || channels === undefined) return;
+ const nextForm = botToFormValues(bot);
+ const nextChannelIds = channels.map((channel) => channel.channel_id);
+ setForm(nextForm);
+ setInitialForm(nextForm);
+ setChannelIds(nextChannelIds);
+ setInitialChannelIds(nextChannelIds);
+ setInitialized(true);
+ }
+ )
+ );
+
+ const assignedChannels = createMemo(() => {
+ const channelsById = channelsContext.channelsById();
+ return (botChannelsQuery.data ?? []).map((channel) => ({
+ id: channel.channel_id,
+ name:
+ channelsById[channel.channel_id]?.name?.trim() ||
+ channel.name?.trim() ||
+ 'Unnamed channel',
+ }));
+ });
+ const isDirty = createMemo(() => {
+ const original = initialForm();
+ const sameForm =
+ form.name === original.name &&
+ form.handle === original.handle &&
+ form.description === original.description &&
+ form.avatarUrl === original.avatarUrl;
+ const originalChannels = [...initialChannelIds()].sort();
+ const nextChannels = [...channelIds()].sort();
+ return (
+ !sameForm ||
+ originalChannels.length !== nextChannels.length ||
+ originalChannels.some((id, index) => id !== nextChannels[index])
+ );
+ });
+ const pending = () =>
+ saving() || avatarUpload.uploading() || deleteBotMutation.isPending;
+
+ const leave = () => {
+ if (pending()) return;
+ props.onBack();
+ };
+
+ const save = async () => {
+ const parsed = validateBotForm(form);
+ if (!parsed.success) {
+ setErrors(parsed.errors);
+ return;
+ }
+
+ setSaving(true);
+ setErrors({});
+ try {
+ const bot = await updateBotMutation.mutateAsync({
+ botId: props.botId,
+ name: parsed.data.name,
+ handle: parsed.data.handle,
+ description: parsed.data.description ?? '',
+ avatarUrl: parsed.data.avatarUrl ?? '',
+ });
+ const channelResult = await syncChannelsMutation.mutateAsync({
+ botId: props.botId,
+ currentChannelIds: initialChannelIds(),
+ nextChannelIds: channelIds(),
+ });
+ const nextForm = botToFormValues(bot);
+ setForm(nextForm);
+ setInitialForm(nextForm);
+ if (channelResult.failedCount > 0) {
+ const refreshed = await botChannelsQuery.refetch();
+ const actualChannelIds =
+ refreshed.data?.map((channel) => channel.channel_id) ??
+ initialChannelIds();
+ setChannelIds(actualChannelIds);
+ setInitialChannelIds(actualChannelIds);
+ toast.failure(
+ `${channelResult.failedCount} channel change${channelResult.failedCount === 1 ? '' : 's'} could not be saved`
+ );
+ } else {
+ setInitialChannelIds([...channelIds()]);
+ toast.success('Bot updated');
+ }
+ } catch {
+ toast.failure('Failed to update bot');
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const deleteBot = async () => {
+ try {
+ await deleteBotMutation.mutateAsync({
+ botId: props.botId,
+ channelIds: (botChannelsQuery.data ?? []).map(
+ (channel) => channel.channel_id
+ ),
+ });
+ setDeleteOpen(false);
+ toast.success('Bot deleted');
+ props.onBack();
+ } catch {
+ toast.failure('Failed to delete bot');
+ }
+ };
+
+ return (
+ <>
+ <div class="size-full overflow-y-auto bg-surface text-ink">
+ <main class="mx-auto w-full max-w-[560px] px-8 pt-14 pb-24 mobile:px-5 mobile:pt-8 mobile:pb-12">
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ class="-ml-2 mb-7"
+ disabled={pending()}
+ onClick={leave}
+ >
+ <CaretLeftIcon />
+ Back to bots
+ </Button>
+ <Show
+ when={initialized() && botQuery.data}
+ fallback={
+ <div class="flex min-h-96 items-center justify-center">
+ <LoadingSpinner class="size-16 p-4" />
+ </div>
+ }
+ >
+ {(bot) => (
+ <form
+ class="flex flex-col gap-5"
+ onSubmit={(event) => {
+ event.preventDefault();
+ void save();
+ }}
+ >
+ <header class="flex items-center gap-3">
+ <BotAvatar
+ bot={{
+ name: form.name || bot().name,
+ avatar_url: form.avatarUrl || undefined,
+ }}
+ size="lg"
+ />
+ <div class="min-w-0">
+ <h1 class="truncate text-lg font-semibold tracking-[-0.01em]">
+ {form.name || bot().name}
+ </h1>
+ <p class="mt-0.5 truncate text-sm text-ink-muted">
+ @{form.handle || bot().handle}
+ </p>
+ </div>
+ </header>
+
+ <BotFormSection
+ class="mt-3"
+ title="Profile"
+ description="Update how this bot appears in channels and mentions."
+ >
+ <BotProfileFields
+ value={form}
+ errors={errors()}
+ uploadingAvatar={avatarUpload.uploading()}
+ onUploadAvatar={avatarUpload.open}
+ onNameChange={(value) => {
+ setForm('name', value);
+ setErrors((current) => ({
+ ...current,
+ name: undefined,
+ }));
+ }}
+ onHandleChange={(value) => {
+ setForm('handle', slugBotHandle(value));
+ setErrors((current) => ({
+ ...current,
+ handle: undefined,
+ }));
+ }}
+ onDescriptionChange={(value) =>
+ setForm('description', value)
+ }
+ />
+ </BotFormSection>
+
+ <BotFormSection
+ title="Channels"
+ description="Choose every channel this bot can post to."
+ >
+ <ChannelMultiSelect
+ channelIds={channelIds()}
+ onChange={setChannelIds}
+ disabled={saving()}
+ />
+ <p class="mt-2 text-xs text-ink-muted">
+ Each assigned channel has a separate webhook URL.
+ </p>
+ </BotFormSection>
+
+ <BotWebhooksSection
+ channels={assignedChannels()}
+ onNewToken={() => setTokenOpen(true)}
+ />
+
+ <BotDetailActions
+ dirty={isDirty()}
+ pending={pending()}
+ saving={saving()}
+ onBack={leave}
+ onDelete={() => setDeleteOpen(true)}
+ />
+ </form>
+ )}
+ </Show>
+ </main>
+ </div>
+
+ <CreateBotTokenDialog
+ open={tokenOpen()}
+ onOpenChange={setTokenOpen}
+ bot={botQuery.data}
+ />
+
+ <BotDeleteDialog
+ open={deleteOpen()}
+ botName={botQuery.data?.name}
+ pending={deleteBotMutation.isPending}
+ onClose={() => setDeleteOpen(false)}
+ onConfirm={() => void deleteBot()}
+ />
+ </>
+ );
+}
diff --git a/js/app/packages/channel/Bots/BotFormSection.tsx b/js/app/packages/channel/Bots/BotFormSection.tsx
new file mode 100644
index 0000000000..fb34968591
--- /dev/null
+++ b/js/app/packages/channel/Bots/BotFormSection.tsx
@@ -0,0 +1,25 @@
+import { Surface } from '@ui';
+import type { JSX } from 'solid-js';
+
+export function BotFormSection(props: {
+ title: string;
+ description: string;
+ action?: JSX.Element;
+ class?: string;
+ children: JSX.Element;
+}) {
+ return (
+ <section class={props.class}>
+ <div class="mb-2 flex items-end justify-between gap-3 px-1">
+ <div>
+ <h2 class="text-sm font-semibold">{props.title}</h2>
+ <p class="mt-0.5 text-xs text-ink-muted">{props.description}</p>
+ </div>
+ {props.action}
+ </div>
+ <Surface depth={2} class="rounded-xl border border-ink/[0.06] p-4">
+ {props.children}
+ </Surface>
+ </section>
+ );
+}
diff --git a/js/app/packages/channel/Bots/BotInviteSelect.tsx b/js/app/packages/channel/Bots/BotInviteSelect.tsx
new file mode 100644
index 0000000000..9ae0f8b20c
--- /dev/null
+++ b/js/app/packages/channel/Bots/BotInviteSelect.tsx
@@ -0,0 +1,163 @@
+import { toast } from '@core/component/Toast/Toast';
+import {
+ Combobox,
+ type ComboboxRootItemComponentProps,
+} from '@kobalte/core/combobox';
+import CaretDownIcon from '@phosphor/caret-down.svg';
+import { useBotsQuery } from '@queries/bots/bots';
+import { useAddBotToChannelMutation } from '@queries/channel/channel-bots';
+import type { Bot } from '@service-storage/generated/schemas/bot';
+import { Surface } from '@ui';
+import {
+ type Component,
+ createEffect,
+ createMemo,
+ createSignal,
+ on,
+ onMount,
+ Show,
+} from 'solid-js';
+import { BotAvatar } from './BotAvatar';
+
+const BotInviteItem: Component<ComboboxRootItemComponentProps<Bot>> = (
+ props
+) => (
+ <Combobox.Item
+ item={props.item}
+ class="flex w-full cursor-default items-center gap-3 rounded-lg px-2.5 py-2 text-left text-ink outline-none data-highlighted:bg-hover"
+ >
+ <BotAvatar bot={props.item.rawValue} size="md" />
+ <div class="min-w-0 flex-1">
+ <div class="flex min-w-0 items-baseline gap-1.5">
+ <Combobox.ItemLabel class="truncate text-sm font-medium">
+ {props.item.rawValue.name}
+ </Combobox.ItemLabel>
+ <span class="truncate text-xs text-ink-extra-muted">
+ @{props.item.rawValue.handle}
+ </span>
+ </div>
+ <Show when={props.item.rawValue.description}>
+ {(description) => (
+ <div class="mt-0.5 truncate text-xs text-ink-muted">
+ {description()}
+ </div>
+ )}
+ </Show>
+ </div>
+ </Combobox.Item>
+);
+
+export function BotInviteSelect(props: {
+ channelId: string;
+ channelBotIds: string[];
+ focusRequest: number;
+}) {
+ const botsQuery = useBotsQuery();
+ const addBotMutation = useAddBotToChannelMutation();
+ const [selectedBot, setSelectedBot] = createSignal<Bot>();
+ let inputRef: HTMLInputElement | undefined;
+
+ const availableBots = createMemo(() => {
+ const channelBotIds = new Set(props.channelBotIds);
+ return (botsQuery.data ?? []).filter((bot) => !channelBotIds.has(bot.id));
+ });
+
+ const focusInput = () => {
+ requestAnimationFrame(() => inputRef?.focus());
+ };
+
+ onMount(() => {
+ if (props.focusRequest > 0) focusInput();
+ });
+
+ createEffect(
+ on(
+ () => props.focusRequest,
+ (request) => {
+ if (request > 0) focusInput();
+ },
+ { defer: true }
+ )
+ );
+
+ const inviteBot = async () => {
+ const bot = selectedBot();
+ if (!bot) return;
+
+ try {
+ await addBotMutation.mutateAsync({
+ channelId: props.channelId,
+ botId: bot.id,
+ });
+ setSelectedBot(undefined);
+ toast.success(`${bot.name} invited to channel`);
+ focusInput();
+ } catch {
+ toast.failure('Failed to invite bot');
+ }
+ };
+
+ return (
+ <div class="flex flex-col gap-2 md:flex-row md:items-center">
+ <div class="min-w-0 flex-1">
+ <Combobox<Bot>
+ multiple={false}
+ options={availableBots()}
+ value={selectedBot() ?? null}
+ optionValue={(bot) => bot.id}
+ optionLabel={(bot) => bot.name}
+ optionTextValue={(bot) =>
+ [bot.name, bot.handle, bot.description].filter(Boolean).join(' ')
+ }
+ onChange={(bot) => setSelectedBot(bot ?? undefined)}
+ placeholder={
+ botsQuery.isLoading ? 'Loading bots…' : 'Search existing bots…'
+ }
+ itemComponent={BotInviteItem}
+ placement="bottom-start"
+ allowsEmptyCollection
+ disabled={botsQuery.isLoading || addBotMutation.isPending}
+ >
+ <Combobox.Control<Bot> class="block w-full">
+ <div class="flex w-full items-center rounded-lg border border-edge-muted bg-surface px-3 py-2 text-sm text-ink outline-none focus-within:border-accent">
+ <Combobox.Input
+ ref={inputRef}
+ class="min-h-7 min-w-0 flex-1 bg-transparent p-1 outline-none placeholder:text-ink-placeholder"
+ />
+ <Combobox.Trigger class="ml-2 rounded p-0.5 text-ink-extra-muted outline-none hover:bg-hover hover:text-ink">
+ <CaretDownIcon class="size-3.5" />
+ </Combobox.Trigger>
+ </div>
+ </Combobox.Control>
+ <Combobox.Portal>
+ <Combobox.Content
+ as={Surface}
+ depth={3}
+ bgToken="menu"
+ class="z-action-menu mt-1 w-[var(--kb-popper-anchor-width)] min-w-72 rounded-xl p-1.5 shadow-menu"
+ >
+ <Show
+ when={availableBots().length > 0}
+ fallback={
+ <div class="px-3 py-5 text-center text-xs text-ink-muted">
+ No bots available to invite
+ </div>
+ }
+ >
+ <Combobox.Listbox class="max-h-64 overflow-y-auto" />
+ </Show>
+ </Combobox.Content>
+ </Combobox.Portal>
+ </Combobox>
+ </div>
+ <button
+ type="button"
+ class="w-full shrink-0 rounded-xs bg-accent px-3 py-1.5 text-sm font-medium text-surface transition-colors hover:bg-accent/90 disabled:opacity-50 md:w-[127px]"
+ disabled={!selectedBot() || addBotMutation.isPending}
+ onClick={() => void inviteBot()}
+ >
+ {addBotMutation.isPending ? 'Inviting…' : 'Invite bot'}
+ </button>
+ </div>
+ );
+}
diff --git a/js/app/packages/channel/Bots/BotProfileFields.tsx b/js/app/packages/channel/Bots/BotProfileFields.tsx
new file mode 100644
index 0000000000..c2a00d2fb9
--- /dev/null
+++ b/js/app/packages/channel/Bots/BotProfileFields.tsx
@@ -0,0 +1,102 @@
+import UploadIcon from '@phosphor/upload-simple.svg';
+import { Button } from '@ui';
+import { Show } from 'solid-js';
+import { BotAvatar } from './BotAvatar';
+import type { BotFormErrors, BotFormValues } from './botForm';
+
+export function BotProfileFields(props: {
+ value: BotFormValues;
+ errors: BotFormErrors;
+ uploadingAvatar: boolean;
+ onUploadAvatar: () => void;
+ onNameChange: (value: string) => void;
+ onHandleChange: (value: string) => void;
+ onDescriptionChange: (value: string) => void;
+}) {
+ return (
+ <>
+ <div class="flex items-center gap-3 border-b border-edge-muted pb-4">
+ <button
+ type="button"
+ aria-label="Upload avatar"
+ class="rounded-full outline-none focus-visible:ring-2 focus-visible:ring-accent"
+ onClick={props.onUploadAvatar}
+ >
+ <BotAvatar
+ bot={{
+ name: props.value.name || 'Bot',
+ avatar_url: props.value.avatarUrl || undefined,
+ }}
+ size="lg"
+ />
+ </button>
+ <div class="min-w-0 flex-1">
+ <div class="text-sm font-medium">
+ {props.value.avatarUrl ? 'Change avatar' : 'Bot avatar'}
+ </div>
+ <div class="mt-0.5 text-xs text-ink-muted">
+ Optional · square images work best
+ </div>
+ </div>
+ <Button
+ type="button"
+ variant="base"
+ size="sm"
+ disabled={props.uploadingAvatar}
+ onClick={props.onUploadAvatar}
+ >
+ <UploadIcon />
+ {props.uploadingAvatar ? 'Uploading…' : 'Upload'}
+ </Button>
+ </div>
+
+ <div class="mt-4 grid grid-cols-2 gap-3 mobile:grid-cols-1">
+ <label class="flex flex-col gap-1.5">
+ <span class="text-xs font-medium">Name</span>
+ <input
+ autofocus
+ value={props.value.name}
+ placeholder="Release bot"
+ class="settings-input w-full"
+ aria-invalid={!!props.errors.name}
+ onInput={(event) => props.onNameChange(event.currentTarget.value)}
+ />
+ <Show when={props.errors.name}>
+ {(error) => <span class="text-xs text-failure">{error()}</span>}
+ </Show>
+ </label>
+ <label class="flex flex-col gap-1.5">
+ <span class="text-xs font-medium">Mention handle</span>
+ <div class="flex items-center rounded-md border border-edge-muted bg-transparent px-2 focus-within:border-accent">
+ <span class="text-sm text-ink-extra-muted">@</span>
+ <input
+ value={props.value.handle}
+ placeholder="release-bot"
+ class="min-w-0 flex-1 bg-transparent px-1.5 py-2 text-sm outline-none"
+ aria-invalid={!!props.errors.handle}
+ onInput={(event) =>
+ props.onHandleChange(event.currentTarget.value)
+ }
+ />
+ </div>
+ <Show when={props.errors.handle}>
+ {(error) => <span class="text-xs text-failure">{error()}</span>}
+ </Show>
+ </label>
+ </div>
+
+ <label class="mt-4 flex flex-col gap-1.5">
+ <span class="text-xs font-medium">Description</span>
+ <textarea
+ value={props.value.description}
+ placeholder="Posts release updates and deployment status"
+ rows={3}
+ class="settings-input h-auto min-h-20 w-full resize-none px-3 py-2.5 leading-5"
+ onInput={(event) =>
+ props.onDescriptionChange(event.currentTarget.value)
+ }
+ />
+ </label>
+ </>
+ );
+}
diff --git a/js/app/packages/channel/Bots/BotWebhooksSection.tsx b/js/app/packages/channel/Bots/BotWebhooksSection.tsx
new file mode 100644
index 0000000000..e88d082f08
--- /dev/null
+++ b/js/app/packages/channel/Bots/BotWebhooksSection.tsx
@@ -0,0 +1,57 @@
+import KeyIcon from '@phosphor/key.svg';
+import { Button } from '@ui';
+import { For, Show } from 'solid-js';
+import { BotFormSection } from './BotFormSection';
+import { CredentialField } from './CredentialField';
+import { channelWebhookUrl } from './webhook';
+
+type BotWebhookChannel = {
+ id: string;
+ name: string;
+};
+
+type BotWebhooksSectionProps = {
+ channels: BotWebhookChannel[];
+ onNewToken: () => void;
+};
+
+export function BotWebhooksSection(props: BotWebhooksSectionProps) {
+ return (
+ <BotFormSection
+ title="Webhooks"
+ description="Copy a channel URL or generate another token."
+ action={
+ <Button
+ type="button"
+ variant="base"
+ size="sm"
+ onClick={props.onNewToken}
+ >
+ <KeyIcon />
+ New token
+ </Button>
+ }
+ >
+ <Show
+ when={props.channels.length > 0}
+ fallback={
+ <p class="text-xs text-ink-muted">
+ Add this bot to a channel to get a webhook URL.
+ </p>
+ }
+ >
+ <div class="flex flex-col gap-4">
+ <For each={props.channels}>
+ {(channel) => (
+ <CredentialField
+ label={channel.name}
+ value={channelWebhookUrl(channel.id)}
+ help="Webhook URL"
+ />
+ )}
+ </For>
+ </div>
+ </Show>
+ </BotFormSection>
+ );
+}
diff --git a/js/app/packages/channel/Bots/ChannelMultiSelect.tsx b/js/app/packages/channel/Bots/ChannelMultiSelect.tsx
new file mode 100644
index 0000000000..96e72b18cd
--- /dev/null
+++ b/js/app/packages/channel/Bots/ChannelMultiSelect.tsx
@@ -0,0 +1,123 @@
+import { useChannelsContext } from '@core/context/channels';
+import {
+ Combobox,
+ type ComboboxRootItemComponentProps,
+} from '@kobalte/core/combobox';
+import CaretDownIcon from '@phosphor/caret-down.svg';
+import CheckIcon from '@phosphor/check.svg';
+import HashIcon from '@phosphor/hash.svg';
+import XIcon from '@phosphor/x.svg';
+import { ChannelTypeEnum } from '@service-storage/client';
+import { Surface } from '@ui';
+import { type Component, createMemo, For, Show } from 'solid-js';
+
+export type BotChannelOption = { id: string; name: string };
+
+const ChannelItem: Component<
+ ComboboxRootItemComponentProps<BotChannelOption>
+> = (props) => (
+ <Combobox.Item
+ item={props.item}
+ class="flex w-full cursor-default items-center gap-2 rounded-lg px-2 py-1.5 text-left text-sm text-ink outline-none data-highlighted:bg-hover"
+ >
+ <HashIcon class="size-3.5 shrink-0 text-ink-muted" />
+ <Combobox.ItemLabel class="min-w-0 flex-1 truncate">
+ {props.item.rawValue.name}
+ </Combobox.ItemLabel>
+ <Combobox.ItemIndicator>
+ <CheckIcon class="size-3.5 text-accent" />
+ </Combobox.ItemIndicator>
+ </Combobox.Item>
+);
+
+export function ChannelMultiSelect(props: {
+ channelIds: string[];
+ onChange: (channelIds: string[]) => void;
+ disabled?: boolean;
+}) {
+ const channelsContext = useChannelsContext();
+ const options = createMemo<BotChannelOption[]>(() =>
+ channelsContext
+ .channels()
+ .filter((channel) => channel.channel_type === ChannelTypeEnum.Private)
+ .map((channel) => ({
+ id: channel.id,
+ name: channel.name?.trim() || 'Unnamed channel',
+ }))
+ .sort((a, b) => a.name.localeCompare(b.name))
+ );
+ const selectedOptions = createMemo(() => {
+ const selected = new Set(props.channelIds);
+ return options().filter((channel) => selected.has(channel.id));
+ });
+
+ return (
+ <Combobox<BotChannelOption>
+ multiple
+ options={options()}
+ value={selectedOptions()}
+ optionValue={(channel) => channel.id}
+ optionLabel={(channel) => channel.name}
+ optionTextValue={(channel) => channel.name}
+ onChange={(channels) =>
+ props.onChange(channels.map((channel) => channel.id))
+ }
+ placeholder="Search channels…"
+ itemComponent={ChannelItem}
+ placement="bottom-start"
+ closeOnSelection={false}
+ allowsEmptyCollection
+ disabled={props.disabled}
+ >
+ <Combobox.Control<BotChannelOption>>
+ {(state) => (
+ <div class="flex min-h-9 w-full flex-wrap items-center gap-1.5 rounded-md border border-edge-muted px-2 py-1 focus-within:border-accent">
+ <For each={state.selectedOptions()}>
+ {(channel) => (
+ <span class="flex min-w-0 max-w-full items-center gap-1 rounded-md bg-ink/[0.055] py-1 pr-1 pl-1.5 text-xs text-ink">
+ <HashIcon class="size-3 shrink-0 text-ink-muted" />
+ <span class="truncate">{channel.name}</span>
+ <button
+ type="button"
+ aria-label={`Remove ${channel.name}`}
+ class="rounded p-0.5 text-ink-extra-muted hover:bg-hover hover:text-ink"
+ onPointerDown={(event) => event.preventDefault()}
+ onClick={(event) => {
+ event.stopPropagation();
+ state.remove(channel);
+ }}
+ >
+ <XIcon class="size-3" />
+ </button>
+ </span>
+ )}
+ </For>
+ <Combobox.Input class="min-w-24 flex-1 bg-transparent px-1 py-1 text-sm outline-none placeholder:text-ink-placeholder" />
+ <Combobox.Trigger class="ml-auto rounded p-0.5 text-ink-extra-muted outline-none hover:bg-hover hover:text-ink">
+ <CaretDownIcon class="size-3.5" />
+ </Combobox.Trigger>
+ </div>
+ )}
+ </Combobox.Control>
+ <Combobox.Portal>
+ <Combobox.Content
+ as={Surface}
+ depth={3}
+ bgToken="menu"
+ class="z-action-menu mt-1 w-[var(--kb-popper-anchor-width)] min-w-64 rounded-xl p-1.5 shadow-menu"
+ >
+ <Show
+ when={options().length > 0}
+ fallback={
+ <div class="px-2 py-5 text-center text-xs text-ink-muted">
+ No available channels
+ </div>
+ }
+ >
+ <Combobox.Listbox class="max-h-56 overflow-y-auto" />
+ </Show>
+ </Combobox.Content>
+ </Combobox.Portal>
+ </Combobox>
+ );
+}
diff --git a/js/app/packages/channel/Bots/CreateBotTokenDialog.tsx b/js/app/packages/channel/Bots/CreateBotTokenDialog.tsx
new file mode 100644
index 0000000000..54a24fdab8
--- /dev/null
+++ b/js/app/packages/channel/Bots/CreateBotTokenDialog.tsx
@@ -0,0 +1,153 @@
+import { toast } from '@core/component/Toast/Toast';
+import KeyIcon from '@phosphor/key.svg';
+import XIcon from '@phosphor/x.svg';
+import { useCreateBotTokenMutation } from '@queries/bots/bots';
+import type { Bot } from '@service-storage/generated/schemas/bot';
+import { Button, Dialog, Panel } from '@ui';
+import { createSignal, Show } from 'solid-js';
+import { BotAvatar } from './BotAvatar';
+import { CredentialField } from './CredentialField';
+
+export function CreateBotTokenDialog(props: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ bot?: Bot;
+}) {
+ const createTokenMutation = useCreateBotTokenMutation();
+ const [label, setLabel] = createSignal('webhook');
+ const [token, setToken] = createSignal<string>();
+
+ const reset = () => {
+ setLabel('webhook');
+ setToken(undefined);
+ };
+
+ const close = () => {
+ if (createTokenMutation.isPending) return;
+ props.onOpenChange(false);
+ reset();
+ };
+
+ const create = () => {
+ const bot = props.bot;
+ if (!bot) return;
+ createTokenMutation.mutate(
+ { botId: bot.id, label: label().trim() || undefined },
+ {
+ onSuccess: ({ bearer_token }) => setToken(bearer_token),
+ onError: () => toast.failure('Failed to create token'),
+ }
+ );
+ };
+
+ return (
+ <Dialog
+ open={props.open}
+ onOpenChange={(open) => (open ? props.onOpenChange(true) : close())}
+ onEscapeKeyDown={(event) =>
+ createTokenMutation.isPending && event.preventDefault()
+ }
+ position="center"
+ class="w-105"
+ >
+ <Panel depth={2} active class="rounded-xl text-ink">
+ <Panel.Header class="px-5">
+ <Dialog.Title class="text-sm font-semibold">
+ New webhook token
+ </Dialog.Title>
+ <div class="ml-auto">
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ label="Close"
+ aria-label="Close"
+ disabled={createTokenMutation.isPending}
+ onClick={close}
+ >
+ <XIcon />
+ </Button>
+ </div>
+ </Panel.Header>
+ <Panel.Body class="p-5">
+ <Show when={props.bot}>
+ {(bot) => (
+ <div class="flex flex-col gap-5">
+ <div class="flex items-center gap-3 rounded-xl border border-edge-muted bg-ink/[0.02] p-3">
+ <BotAvatar bot={bot()} size="lg" />
+ <div class="min-w-0 flex-1">
+ <div class="truncate text-sm font-medium">{bot().name}</div>
+ <div class="truncate text-xs text-ink-muted">
+ @{bot().handle}
+ </div>
+ </div>
+ <KeyIcon class="size-5 text-ink-extra-muted" />
+ </div>
+
+ <Show
+ when={token()}
+ fallback={
+ <>
+ <label class="flex flex-col gap-1.5">
+ <span class="text-xs font-medium text-ink">
+ Token label
+ </span>
+ <input
+ autofocus
+ value={label()}
+ placeholder="webhook"
+ class="settings-input w-full"
+ onInput={(event) =>
+ setLabel(event.currentTarget.value)
+ }
+ onKeyDown={(event) => {
+ if (event.key === 'Enter') create();
+ }}
+ />
+ <span class="text-xs text-ink-muted">
+ Use a label that describes where this token is used.
+ </span>
+ </label>
+ <div class="flex justify-end gap-2 border-t border-edge-muted pt-4">
+ <Button variant="ghost" size="sm" onClick={close}>
+ Cancel
+ </Button>
+ <Button
+ variant="cta"
+ size="sm"
+ disabled={createTokenMutation.isPending}
+ onClick={create}
+ >
+ {createTokenMutation.isPending
+ ? 'Creating…'
+ : 'Create token'}
+ </Button>
+ </div>
+ </>
+ }
+ >
+ {(rawToken) => (
+ <>
+ <CredentialField
+ label="Webhook token"
+ value={rawToken()}
+ help="Shown only once"
+ />
+ <div class="rounded-lg border border-alert/30 bg-alert-bg px-3 py-2.5 text-xs text-alert-ink">
+ Store this token somewhere secure before closing.
+ </div>
+ <div class="flex justify-end border-t border-edge-muted pt-4">
+ <Button variant="cta" size="sm" onClick={close}>
+ Done
+ </Button>
+ </div>
+ </>
+ )}
+ </Show>
+ </div>
+ )}
+ </Show>
+ </Panel.Body>
+ </Panel>
+ </Dialog>
+ );
+}
diff --git a/js/app/packages/channel/Bots/CredentialField.tsx b/js/app/packages/channel/Bots/CredentialField.tsx
new file mode 100644
index 0000000000..8277d22e07
--- /dev/null
+++ b/js/app/packages/channel/Bots/CredentialField.tsx
@@ -0,0 +1,54 @@
+import { toast } from '@core/component/Toast/Toast';
+import CheckIcon from '@phosphor/check.svg';
+import CopyIcon from '@phosphor/copy.svg';
+import { Button } from '@ui';
+import { createSignal, Show } from 'solid-js';
+
+export function CredentialField(props: {
+ label: string;
+ value: string;
+ help?: string;
+}) {
+ const [copied, setCopied] = createSignal(false);
+
+ const copy = async () => {
+ try {
+ await navigator.clipboard.writeText(props.value);
+ setCopied(true);
+ window.setTimeout(() => setCopied(false), 1500);
+ } catch {
+ toast.failure(`Failed to copy ${props.label.toLowerCase()}`);
+ }
+ };
+
+ return (
+ <div class="flex flex-col gap-1.5">
+ <div class="flex items-baseline justify-between gap-3">
+ <span class="text-xs font-medium text-ink">{props.label}</span>
+ <Show when={props.help}>
+ <span class="text-xs text-ink-muted">{props.help}</span>
+ </Show>
+ </div>
+ <div class="flex min-w-0 items-center gap-2 rounded-lg border border-edge-muted bg-ink/[0.025] px-3 py-2">
+ <input
+ readOnly
+ value={props.value}
+ class="min-w-0 flex-1 bg-transparent font-mono text-xs text-ink outline-none"
+ onClick={(event) => event.currentTarget.select()}
+ />
+ <Button
+ type="button"
+ variant={copied() ? 'success' : 'ghost'}
+ size="sm"
+ label={`Copy ${props.label.toLowerCase()}`}
+ onClick={copy}
+ >
+ <Show when={copied()} fallback={<CopyIcon />}>
+ <CheckIcon />
+ Copied
+ </Show>
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/js/app/packages/channel/Bots/botForm.ts b/js/app/packages/channel/Bots/botForm.ts
new file mode 100644
index 0000000000..c2d6a9b615
--- /dev/null
+++ b/js/app/packages/channel/Bots/botForm.ts
@@ -0,0 +1,58 @@
+import type { Bot } from '@service-storage/generated/schemas/bot';
+import { z } from 'zod';
+
+const botFormSchema = z.object({
+ name: z.string().trim().min(1, 'Enter a bot name.').max(128),
+ handle: z
+ .string()
+ .trim()
+ .min(1, 'Enter a mention handle.')
+ .max(64, 'Mention handle must be 64 characters or fewer.')
+ .regex(/^[a-z0-9_-]+$/, "Use lowercase letters, numbers, '-' or '_' only."),
+ description: z.string().trim().max(500),
+ avatarUrl: z.string().trim(),
+});
+
+export type BotFormValues = z.infer<typeof botFormSchema>;
+export type BotFormErrors = Partial<Record<keyof BotFormValues, string>>;
+
+export const EMPTY_BOT_FORM: BotFormValues = {
+ name: '',
+ handle: '',
+ description: '',
+ avatarUrl: '',
+};
+
+export function botToFormValues(bot: Bot): BotFormValues {
+ return {
+ name: bot.name,
+ handle: bot.handle,
+ description: bot.description ?? '',
+ avatarUrl: bot.avatar_url ?? '',
+ };
+}
+
+export function slugBotHandle(value: string) {
+ return value
+ .trim()
+ .toLowerCase()
+ .replace(/[^a-z0-9_-]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 64);
+}
+
+export function validateBotForm(values: BotFormValues) {
+ const result = botFormSchema.safeParse(values);
+ if (result.success) return result;
+
+ const fieldErrors = result.error.flatten().fieldErrors;
+ return {
+ success: false as const,
+ errors: Object.fromEntries(
+ Object.entries(fieldErrors).map(([field, messages]) => [
+ field,
+ messages?.[0],
+ ])
+ ) as BotFormErrors,
+ };
+}
diff --git a/js/app/packages/channel/Bots/botSettingsState.ts b/js/app/packages/channel/Bots/botSettingsState.ts
new file mode 100644
index 0000000000..4d2c2d8d8e
--- /dev/null
+++ b/js/app/packages/channel/Bots/botSettingsState.ts
@@ -0,0 +1,27 @@
+import { createSignal } from 'solid-js';
+
+export type BotSettingsRequest =
+ | { id: number; type: 'create'; initialChannelId?: string }
+ | { id: number; type: 'detail'; botId: string };
+
+const [botSettingsRequest, setBotSettingsRequest] =
+ createSignal<BotSettingsRequest>();
+let nextRequestId = 0;
+
+export { botSettingsRequest };
+
+export function requestBotCreation(initialChannelId?: string) {
+ setBotSettingsRequest({
+ id: ++nextRequestId,
+ type: 'create',
+ initialChannelId,
+ });
+}
+
+export function requestBotDetail(botId: string) {
+ setBotSettingsRequest({ id: ++nextRequestId, type: 'detail', botId });
+}
+
+export function consumeBotSettingsRequest(id: number) {
+ if (botSettingsRequest()?.id === id) setBotSettingsRequest(undefined);
+}
diff --git a/js/app/packages/channel/Bots/createBotAvatarUpload.ts b/js/app/packages/channel/Bots/createBotAvatarUpload.ts
new file mode 100644
index 0000000000..f76c7c5397
--- /dev/null
+++ b/js/app/packages/channel/Bots/createBotAvatarUpload.ts
@@ -0,0 +1,30 @@
+import { toast } from '@core/component/Toast/Toast';
+import { staticFileIdEndpoint } from '@core/constant/servers';
+import { openFilePicker, uploadFile } from '@core/util/upload';
+import { createSignal } from 'solid-js';
+
+export function createBotAvatarUpload(onUploaded: (url: string) => void) {
+ const [uploading, setUploading] = createSignal(false);
+
+ const open = () => {
+ openFilePicker(
+ { acceptedMimeTypes: ['image/*'], multiple: false },
+ async ([file]) => {
+ if (!file) return;
+ setUploading(true);
+ try {
+ const result = await uploadFile(file, 'static');
+ if (result.failed || result.destination !== 'static') {
+ toast.failure('Failed to upload avatar');
+ return;
+ }
+ onUploaded(staticFileIdEndpoint(result.id));
+ } finally {
+ setUploading(false);
+ }
+ }
+ );
+ };
+
+ return { open, uploading };
+}
diff --git a/js/app/packages/channel/Bots/tests/bot-form.test.ts b/js/app/packages/channel/Bots/tests/bot-form.test.ts
new file mode 100644
index 0000000000..fbc213925d
--- /dev/null
+++ b/js/app/packages/channel/Bots/tests/bot-form.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it } from 'vitest';
+import { slugBotHandle, validateBotForm } from '../botForm';
+
+describe('bot form', () => {
+ it('turns a display name into a valid mention handle', () => {
+ expect(slugBotHandle(' Release Updates! ')).toBe('release-updates');
+ expect(slugBotHandle('Build__Bot')).toBe('build__bot');
+ });
+
+ it('normalizes valid form values', () => {
+ const result = validateBotForm({
+ name: ' Release bot ',
+ handle: ' release-bot ',
+ description: ' Posts releases ',
+ avatarUrl: ' https://example.com/avatar.png ',
+ });
+
+ expect(result).toEqual({
+ success: true,
+ data: {
+ name: 'Release bot',
+ handle: 'release-bot',
+ description: 'Posts releases',
+ avatarUrl: 'https://example.com/avatar.png',
+ },
+ });
+ });
+
+ it('returns field-specific errors', () => {
+ const result = validateBotForm({
+ name: '',
+ handle: 'Invalid Handle',
+ description: '',
+ avatarUrl: '',
+ });
+
+ expect(result.success).toBe(false);
+ if (result.success) return;
+ expect(result.errors.name).toBe('Enter a bot name.');
+ expect(result.errors.handle).toBe(
+ "Use lowercase letters, numbers, '-' or '_' only."
+ );
+ });
+});
diff --git a/js/app/packages/channel/Bots/webhook.ts b/js/app/packages/channel/Bots/webhook.ts
new file mode 100644
index 0000000000..a5202cf0b6
--- /dev/null
+++ b/js/app/packages/channel/Bots/webhook.ts
@@ -0,0 +1,16 @@
+import { SERVER_HOSTS } from '@core/constant/servers';
+
+export const WEBHOOK_TOKEN_HEADER = 'x-macro-channel-bot-token';
+
+export function channelWebhookUrl(channelId: string): string {
+ return `${SERVER_HOSTS['document-storage-service']}/channels/${channelId}/webhook`;
+}
+
+export function webhookExample(url: string, token: string): string {
+ return [
+ `curl -X POST '${url}' \\`,
+ ` -H '${WEBHOOK_TOKEN_HEADER}: ${token}' \\`,
+ ` -H 'Content-Type: application/json' \\`,
+ ` -d '{"content":"Hello from your bot"}'`,
+ ].join('\n');
+}
diff --git a/js/app/packages/channel/Participants/ChannelBotRow.tsx b/js/app/packages/channel/Participants/ChannelBotRow.tsx
new file mode 100644
index 0000000000..bad6ed9f71
--- /dev/null
+++ b/js/app/packages/channel/Participants/ChannelBotRow.tsx
@@ -0,0 +1,67 @@
+import { BotAvatar } from '@channel/Bots/BotAvatar';
+import CopyIcon from '@phosphor/copy.svg';
+import XIcon from '@phosphor/x.svg';
+import type { Bot } from '@service-storage/generated/schemas/bot';
+import { Button } from '@ui';
+import { Show } from 'solid-js';
+
+export function ChannelBotRow(props: {
+ bot: Bot;
+ editable: boolean;
+ removing: boolean;
+ onOpen: () => void;
+ onCopyWebhook: () => void;
+ onRemove: () => void;
+}) {
+ return (
+ <div class="group relative flex items-center gap-3 border-b border-edge-muted px-6 py-2.5 last:border-b-0 hover:bg-hover focus-within:bg-hover">
+ <button
+ type="button"
+ class="absolute inset-0 z-0 rounded-md outline-none"
+ aria-label={`Open ${props.bot.name}`}
+ onClick={props.onOpen}
+ />
+ <div class="pointer-events-none relative z-1">
+ <BotAvatar bot={props.bot} size="lg" />
+ </div>
+ <div class="pointer-events-none relative z-1 min-w-0 flex-1">
+ <div class="flex min-w-0 items-baseline gap-1.5">
+ <span class="truncate text-sm font-medium">{props.bot.name}</span>
+ <span class="truncate text-xs text-ink-extra-muted">
+ @{props.bot.handle}
+ </span>
+ </div>
+ <Show when={props.bot.description}>
+ {(description) => (
+ <div class="mt-0.5 truncate text-xs text-ink-muted">
+ {description()}
+ </div>
+ )}
+ </Show>
+ </div>
+ <Button
+ class="relative z-1"
+ variant="base"
+ size="sm"
+ label="Copy webhook URL"
+ onClick={props.onCopyWebhook}
+ >
+ <CopyIcon />
+ Webhook URL
+ </Button>
+ <Show when={props.editable}>
+ <Button
+ class="relative z-1"
+ variant="ghost"
+ size="icon-sm"
+ label={`Remove ${props.bot.name}`}
+ aria-label={`Remove ${props.bot.name}`}
+ disabled={props.removing}
+ onClick={props.onRemove}
+ >
+ <XIcon />
+ </Button>
+ </Show>
+ </div>
+ );
+}
diff --git a/js/app/packages/channel/Participants/ChannelBotsPanel.tsx b/js/app/packages/channel/Participants/ChannelBotsPanel.tsx
new file mode 100644
index 0000000000..78e83801b4
--- /dev/null
+++ b/js/app/packages/channel/Participants/ChannelBotsPanel.tsx
@@ -0,0 +1,119 @@
+import { channelWebhookUrl } from '@channel/Bots/webhook';
+import { LoadingSpinner } from '@core/component/LoadingSpinner';
+import { toast } from '@core/component/Toast/Toast';
+import PlusIcon from '@phosphor/plus.svg';
+import RobotIcon from '@phosphor/robot.svg';
+import {
+ useChannelBotsQuery,
+ useRemoveBotFromChannelMutation,
+} from '@queries/channel/channel-bots';
+import { Button, Panel } from '@ui';
+import { For, Show } from 'solid-js';
+import { BotInviteSelect } from '../Bots/BotInviteSelect';
+import { ChannelBotRow } from './ChannelBotRow';
+
+export function ChannelBotsPanel(props: {
+ channelId: string;
+ editable: boolean;
+ inviteFocusRequest: number;
+ onCreateBot: () => void;
+ onOpenBot: (botId: string) => void;
+}) {
+ const botsQuery = useChannelBotsQuery(() => props.channelId);
+ const removeBotMutation = useRemoveBotFromChannelMutation();
+ const bots = () => botsQuery.data ?? [];
+
+ const copyWebhook = async () => {
+ try {
+ await navigator.clipboard.writeText(channelWebhookUrl(props.channelId));
+ toast.success('Webhook URL copied');
+ } catch {
+ toast.failure('Failed to copy webhook URL');
+ }
+ };
+
+ const removeBot = (botId: string, name: string) => {
+ removeBotMutation.mutate(
+ { channelId: props.channelId, botId },
+ {
+ onSuccess: () => toast.success(`${name} removed from channel`),
+ onError: () => toast.failure('Failed to remove bot'),
+ }
+ );
+ };
+
+ return (
+ <Panel
+ depth={2}
+ class="h-[min(42%,22rem)] min-h-52 shrink-0 overflow-hidden text-ink"
+ >
+ <Panel.Header class="h-auto min-h-10 justify-between gap-3 px-6 py-2">
+ <div>
+ <div class="text-sm font-semibold">Bots</div>
+ <div class="text-xs font-normal text-ink-muted">
+ Webhook-powered channel participants
+ </div>
+ </div>
+ <Show when={props.editable}>
+ <Button variant="cta" size="sm" onClick={props.onCreateBot}>
+ <PlusIcon />
+ New bot
+ </Button>
+ </Show>
+ </Panel.Header>
+ <Panel.Body>
+ <div class="flex h-full flex-col">
+ <Show when={props.editable}>
+ <div class="shrink-0 border-b border-edge-muted px-6 py-3">
+ <BotInviteSelect
+ channelId={props.channelId}
+ channelBotIds={bots().map((bot) => bot.id)}
+ focusRequest={props.inviteFocusRequest}
+ />
+ </div>
+ </Show>
+ <Show
+ when={!botsQuery.isLoading}
+ fallback={
+ <div class="flex min-h-0 flex-1 items-center justify-center">
+ <LoadingSpinner class="size-9 p-2" />
+ </div>
+ }
+ >
+ <Show
+ when={bots().length > 0}
+ fallback={
+ <div class="flex min-h-0 flex-1 flex-col items-center justify-center px-6 text-center">
+ <div class="flex size-9 items-center justify-center rounded-lg bg-accent-bg text-accent">
+ <RobotIcon class="size-5" />
+ </div>
+ <div class="mt-2 text-sm font-medium">
+ No bots in this channel
+ </div>
+ <div class="mt-0.5 text-xs text-ink-muted">
+ Select an existing bot above or create a new one.
+ </div>
+ </div>
+ }
+ >
+ <div class="min-h-0 flex-1 overflow-y-auto">
+ <For each={bots()}>
+ {(bot) => (
+ <ChannelBotRow
+ bot={bot}
+ editable={props.editable}
+ removing={removeBotMutation.isPending}
+ onOpen={() => props.onOpenBot(bot.id)}
+ onCopyWebhook={() => void copyWebhook()}
+ onRemove={() => removeBot(bot.id, bot.name)}
+ />
+ )}
+ </For>
+ </div>
+ </Show>
+ </Show>
+ </div>
+ </Panel.Body>
+ </Panel>
+ );
+}
diff --git a/js/app/packages/channel/Participants/ChannelParticipantsTab.tsx b/js/app/packages/channel/Participants/ChannelParticipantsTab.tsx
index 364bfd7f6a..372a27c127 100644
--- a/js/app/packages/channel/Participants/ChannelParticipantsTab.tsx
+++ b/js/app/packages/channel/Participants/ChannelParticipantsTab.tsx
@@ -12,11 +12,18 @@ import {
import { ChannelType } from '@service-storage/generated/schemas/channelType';
import { Panel } from '@ui';
import { createSignal, Show } from 'solid-js';
+import { ChannelBotsPanel } from './ChannelBotsPanel';
import { ParticipantsAddPanel } from './ParticipantsAddPanel';
import { ParticipantsList } from './ParticipantsList';
import { ParticipantsSearchInput } from './ParticipantsSearchInput';
-export function ChannelParticipantsTab(props: { channelId: string }) {
+export function ChannelParticipantsTab(props: {
+ channelId: string;
+ botManagementEnabled: boolean;
+ inviteBotFocusRequest: number;
+ onCreateBot: () => void;
+ onOpenBot: (botId: string) => void;
+}) {
const { replaceOrInsertSplit } = useSplitLayout();
const userId = useUserId();
const channelType = useChannelType(props.channelId);
@@ -78,8 +85,8 @@ export function ChannelParticipantsTab(props: { channelId: string }) {
return (
<div class="h-full overflow-hidden flex justify-center p-2">
- <div class="max-w-200 size-full">
- <Panel depth={2} class="h-full overflow-hidden text-ink">
+ <div class="max-w-200 size-full flex flex-col gap-2">
+ <Panel depth={2} class="min-h-0 flex-1 overflow-hidden text-ink">
<Panel.Header class="px-6">
<div class="text-sm font-semibold">Participants</div>
</Panel.Header>
@@ -112,6 +119,15 @@ export function ChannelParticipantsTab(props: { channelId: string }) {
</div>
</Panel.Body>
</Panel>
+ <Show when={props.botManagementEnabled}>
+ <ChannelBotsPanel
+ channelId={props.channelId}
+ editable={isEditable()}
+ inviteFocusRequest={props.inviteBotFocusRequest}
+ onCreateBot={props.onCreateBot}
+ onOpenBot={props.onOpenBot}
+ />
+ </Show>
</div>
</div>
);
diff --git a/js/app/packages/core/component/LoadingSpinner.tsx b/js/app/packages/core/component/LoadingSpinner.tsx
index 8ee3beaad8..51e906bde5 100644
--- a/js/app/packages/core/component/LoadingSpinner.tsx
+++ b/js/app/packages/core/component/LoadingSpinner.tsx
@@ -1,9 +1,10 @@
import MacroBrandLoader from '@icon/macro-brand-loader-2.svg';
+import { cn } from '@ui';
import { createSignal, onMount } from 'solid-js';
-export function LoadingSpinner() {
+export function LoadingSpinner(props: { class?: string }) {
return (
- <div class="text-accent size-48 p-14">
+ <div class={cn('text-accent size-48 p-14', props.class)}>
<MacroBrandLoader class="size-full" />
</div>
);
diff --git a/js/app/packages/core/constant/SettingsState.tsx b/js/app/packages/core/constant/SettingsState.tsx
index ce12d3b1fa..887907d6d9 100644
--- a/js/app/packages/core/constant/SettingsState.tsx
+++ b/js/app/packages/core/constant/SettingsState.tsx
@@ -35,6 +35,7 @@ export type SettingsTab =
| 'Shortcuts'
| 'Mobile App'
| 'Agent'
+ | 'Bots'
| 'Team'
| 'CRM'
| 'Connected'
diff --git a/js/app/packages/core/constant/featureFlags.ts b/js/app/packages/core/constant/featureFlags.ts
index 000916619b..ef37cd71c0 100644
--- a/js/app/packages/core/constant/featureFlags.ts
+++ b/js/app/packages/core/constant/featureFlags.ts
@@ -510,3 +510,9 @@ export const UNIFIED_CHANNEL_INPUT = resolveFeatureFlag(
'UNIFIED_CHANNEL_INPUT',
false
);
+
+// Bot management in Settings, channels, and the command menu. Override locally
+// with VITE_BOT_MANAGEMENT.
+export const BOT_MANAGEMENT_FLAG = 'bot-management';
+export const BOT_MANAGEMENT_OVERRIDE =
+ resolveFeatureFlag('BOT_MANAGEMENT', DEV_MODE_ENV) || undefined;
diff --git a/js/app/packages/core/constant/settingsTabsConfig.tsx b/js/app/packages/core/constant/settingsTabsConfig.tsx
index 70610e28b5..55b221625a 100644
--- a/js/app/packages/core/constant/settingsTabsConfig.tsx
+++ b/js/app/packages/core/constant/settingsTabsConfig.tsx
@@ -6,6 +6,7 @@ import CreditCardIcon from '@phosphor/credit-card.svg';
import DeviceMobileIcon from '@phosphor/device-mobile-speaker.svg';
import KeyboardIcon from '@phosphor/keyboard.svg';
import PlugIcon from '@phosphor/plug.svg';
+import RobotIcon from '@phosphor/robot.svg';
import SwatchesIcon from '@phosphor/swatches.svg';
import UserIconPhosphor from '@phosphor/user.svg';
import UsersThreeIcon from '@phosphor/users-three.svg';
@@ -14,6 +15,8 @@ import { useHasPermission } from '../context/user';
import { isNativeMobilePlatform } from '../mobile/isNativeMobilePlatform';
import { isTouchDevice } from '../mobile/isTouchDevice';
import {
+ BOT_MANAGEMENT_FLAG,
+ BOT_MANAGEMENT_OVERRIDE,
DEV_MODE_ENV,
ENABLE_APP_STORE_QR_CODE,
ENABLE_CRM,
@@ -63,6 +66,7 @@ export const SETTINGS_TAB_GROUPS: SettingsTabGroup[] = [
icon: CpuIcon,
},
{ tab: 'Agent', label: 'MCP server', icon: PlugIcon },
+ { tab: 'Bots', label: 'Bots', icon: RobotIcon },
],
},
{
@@ -92,6 +96,7 @@ const SETTINGS_TAB_SLUGS: Record<SettingsTab, string> = {
Shortcuts: 'shortcuts',
'Mobile App': 'mobile-app',
Agent: 'mcp-server',
+ Bots: 'bots',
Team: 'team',
CRM: 'crm',
Connected: 'connections',
@@ -136,6 +141,9 @@ export const useSettingsTabAvailable = () => {
const teamsFlag = useFeatureFlag('enable-teams-settings', {
enabledOverride: ENABLE_TEAMS_OVERRIDE,
});
+ const botManagementFlag = useFeatureFlag(BOT_MANAGEMENT_FLAG, {
+ enabledOverride: BOT_MANAGEMENT_OVERRIDE,
+ });
const hasAdminPanel = useHasPermission(PERMISSION_IDS.WRITE_ADMIN_PANEL);
return (tab: SettingsTab): boolean => {
@@ -159,6 +167,8 @@ export const useSettingsTabAvailable = () => {
return ENABLE_APP_STORE_QR_CODE && !isNativeMobilePlatform();
case 'Agent':
return !isNativeMobilePlatform();
+ case 'Bots':
+ return botManagementFlag().enabled;
case 'Mobile':
return isNativeMobilePlatform() && DEV_MODE_ENV;
case 'Admin':
diff --git a/js/app/packages/queries/bots/bots.ts b/js/app/packages/queries/bots/bots.ts
new file mode 100644
index 0000000000..a8836471c9
--- /dev/null
+++ b/js/app/packages/queries/bots/bots.ts
@@ -0,0 +1,158 @@
+import { throwOnErr } from '@core/util/result';
+import { queryClient } from '@queries/client';
+import { storageServiceClient } from '@service-storage/client';
+import type { Bot } from '@service-storage/generated/schemas/bot';
+import { useMutation, useQuery } from '@tanstack/solid-query';
+import { channelKeys } from '../channel/keys';
+import { botKeys } from './keys';
+
+type CreateBotParams = {
+ avatarUrl?: string;
+ description?: string;
+ handle: string;
+ name: string;
+ teamId?: string;
+};
+
+type CreateBotTokenParams = {
+ botId: string;
+ label?: string;
+ expiresAt?: string;
+};
+
+type UpdateBotParams = Omit<CreateBotParams, 'teamId'> & {
+ botId: string;
+};
+
+type DeleteBotParams = {
+ botId: string;
+ channelIds: string[];
+};
+
+export function useBotsQuery() {
+ return useQuery(() => ({
+ queryKey: botKeys.list.queryKey,
+ queryFn: async (): Promise<Bot[]> =>
+ await throwOnErr(() => storageServiceClient.getBots()),
+ }));
+}
+
+export function useBotQuery(botId: () => string) {
+ return useQuery(() => ({
+ queryKey: botKeys.detail(botId()).queryKey,
+ queryFn: async (): Promise<Bot> =>
+ await throwOnErr(() => storageServiceClient.getBot({ bot_id: botId() })),
+ }));
+}
+
+export function invalidateBots() {
+ return queryClient.invalidateQueries({ queryKey: botKeys.list.queryKey });
+}
+
+export function useCreateBotMutation() {
+ return useMutation(() => ({
+ gcTime: 0,
+ mutationFn: async (vars: CreateBotParams) =>
+ await throwOnErr(() =>
+ storageServiceClient.createBot({
+ avatar_url: vars.avatarUrl,
+ description: vars.description,
+ handle: vars.handle,
+ name: vars.name,
+ team_id: vars.teamId,
+ })
+ ),
+ onSuccess: invalidateBots,
+ onError: (error) => console.error('failed to create bot', error),
+ }));
+}
+
+export function useUpdateBotMutation() {
+ return useMutation(() => ({
+ gcTime: 0,
+ mutationFn: async (vars: UpdateBotParams) =>
+ await throwOnErr(() =>
+ storageServiceClient.patchBot({
+ bot_id: vars.botId,
+ avatar_url: vars.avatarUrl,
+ description: vars.description,
+ handle: vars.handle,
+ name: vars.name,
+ })
+ ),
+ onSuccess: async (bot) => {
+ queryClient.setQueryData(botKeys.detail(bot.id).queryKey, bot);
+ await invalidateBots();
+ },
+ onError: (error) => console.error('failed to update bot', error),
+ }));
+}
+
+export function useDeleteBotMutation() {
+ return useMutation(() => ({
+ gcTime: 0,
+ mutationFn: async (vars: DeleteBotParams) =>
+ await throwOnErr(() =>
+ storageServiceClient.deleteBot({ bot_id: vars.botId })
+ ),
+ onSuccess: async (_data, vars) => {
+ queryClient.removeQueries({
+ queryKey: botKeys.detail(vars.botId).queryKey,
+ });
+ queryClient.removeQueries({
+ queryKey: botKeys.channels(vars.botId).queryKey,
+ });
+ queryClient.removeQueries({
+ queryKey: botKeys.tokens(vars.botId).queryKey,
+ });
+
+ await Promise.all([
+ invalidateBots(),
+ ...vars.channelIds.flatMap((channelId) => [
+ queryClient.invalidateQueries({
+ queryKey: channelKeys.channelBots(channelId).queryKey,
+ }),
+ queryClient.invalidateQueries({
+ queryKey: channelKeys.participants(channelId).queryKey,
+ }),
+ ]),
+ ]);
+ },
+ onError: (error) => console.error('failed to delete bot', error),
+ }));
+}
+
+export function useCreateBotTokenMutation() {
+ return useMutation(() => ({
+ gcTime: 0,
+ mutationFn: async (vars: CreateBotTokenParams) =>
+ await throwOnErr(() =>
+ storageServiceClient.createBotToken({
+ bot_id: vars.botId,
+ expires_at: vars.expiresAt,
+ label: vars.label,
+ })
+ ),
+ onSuccess: (_data, vars) =>
+ queryClient.invalidateQueries({
+ queryKey: botKeys.tokens(vars.botId).queryKey,
+ }),
+ onError: (error) => console.error('failed to create bot token', error),
+ }));
+}
+
+export function useBotChannelsQuery(botId: () => string) {
+ return useQuery(() => ({
+ queryKey: botKeys.channels(botId()).queryKey,
+ queryFn: async () =>
+ await throwOnErr(() =>
+ storageServiceClient.getBotChannels({ bot_id: botId() })
+ ),
+ }));
+}
+
+export function invalidateBotChannels(botId: string) {
+ return queryClient.invalidateQueries({
+ queryKey: botKeys.channels(botId).queryKey,
+ });
+}
diff --git a/js/app/packages/queries/bots/keys.ts b/js/app/packages/queries/bots/keys.ts
new file mode 100644
index 0000000000..a82c44df9e
--- /dev/null
+++ b/js/app/packages/queries/bots/keys.ts
@@ -0,0 +1,8 @@
+import { createQueryKeys } from '@lukemorales/query-key-factory';
+
+export const botKeys = createQueryKeys('bots', {
+ list: null,
+ detail: (botId: string) => ({ queryKey: [botId] }),
+ channels: (botId: string) => ({ queryKey: [botId] }),
+ tokens: (botId: string) => ({ queryKey: [botId] }),
+});
diff --git a/js/app/packages/queries/channel/channel-bots.ts b/js/app/packages/queries/channel/channel-bots.ts
new file mode 100644
index 0000000000..5e31beec22
--- /dev/null
+++ b/js/app/packages/queries/channel/channel-bots.ts
@@ -0,0 +1,182 @@
+import { throwOnErr } from '@core/util/result';
+import { invalidateBotChannels, invalidateBots } from '@queries/bots/bots';
+import { queryClient } from '@queries/client';
+import { storageServiceClient } from '@service-storage/client';
+import type { Bot } from '@service-storage/generated/schemas/bot';
+import type { CreateChannelScopedBotRequest } from '@service-storage/generated/schemas/createChannelScopedBotRequest';
+import { useMutation, useQuery } from '@tanstack/solid-query';
+import { channelKeys } from './keys';
+
+type AddBotToChannelParams = {
+ channelId: string;
+ botId: string;
+};
+
+type AddBotToChannelsParams = {
+ channelIds: string[];
+ botId: string;
+};
+
+type SyncBotChannelsParams = {
+ botId: string;
+ currentChannelIds: string[];
+ nextChannelIds: string[];
+};
+
+type CreateChannelScopedBotParams = CreateChannelScopedBotRequest & {
+ channelId: string;
+};
+
+export function useChannelBotsQuery(channelId: () => string) {
+ return useQuery(() => ({
+ queryKey: channelKeys.channelBots(channelId()).queryKey,
+ queryFn: async (): Promise<Bot[]> =>
+ await throwOnErr(() =>
+ storageServiceClient.getChannelBots({
+ channel_id: channelId(),
+ })
+ ),
+ }));
+}
+
+function invalidateChannelBots(channelId: string) {
+ return queryClient.invalidateQueries({
+ queryKey: channelKeys.channelBots(channelId).queryKey,
+ });
+}
+
+export function useAddBotToChannelMutation() {
+ return useMutation(() => ({
+ gcTime: 0,
+ mutationFn: async (vars: AddBotToChannelParams) =>
+ await throwOnErr(() =>
+ storageServiceClient.addBotToChannel({
+ channel_id: vars.channelId,
+ bot_id: vars.botId,
+ })
+ ),
+ onSuccess: (_data, vars) =>
+ invalidateBotChannelViews(vars.botId, [vars.channelId]),
+ onError: (error) => console.error('failed to add bot to channel', error),
+ }));
+}
+
+async function invalidateBotChannelViews(botId: string, channelIds: string[]) {
+ await Promise.all([
+ invalidateBotChannels(botId),
+ ...[...new Set(channelIds)].flatMap((channelId) => [
+ invalidateChannelBots(channelId),
+ queryClient.invalidateQueries({
+ queryKey: channelKeys.participants(channelId).queryKey,
+ }),
+ ]),
+ ]);
+}
+
+export function useAddBotToChannelsMutation() {
+ return useMutation(() => ({
+ gcTime: 0,
+ mutationFn: async (vars: AddBotToChannelsParams) => {
+ const results = await Promise.allSettled(
+ vars.channelIds.map((channelId) =>
+ throwOnErr(() =>
+ storageServiceClient.addBotToChannel({
+ channel_id: channelId,
+ bot_id: vars.botId,
+ })
+ ).then(() => channelId)
+ )
+ );
+ return {
+ addedChannelIds: results.flatMap((result) =>
+ result.status === 'fulfilled' ? [result.value] : []
+ ),
+ failedCount: results.filter((result) => result.status === 'rejected')
+ .length,
+ };
+ },
+ onSuccess: (_data, vars) =>
+ invalidateBotChannelViews(vars.botId, vars.channelIds),
+ onError: (error) => console.error('failed to add bot to channels', error),
+ }));
+}
+
+export function useSyncBotChannelsMutation() {
+ return useMutation(() => ({
+ gcTime: 0,
+ mutationFn: async (vars: SyncBotChannelsParams) => {
+ const current = new Set(vars.currentChannelIds);
+ const next = new Set(vars.nextChannelIds);
+ const additions = vars.nextChannelIds.filter((id) => !current.has(id));
+ const removals = vars.currentChannelIds.filter((id) => !next.has(id));
+ const results = await Promise.allSettled([
+ ...additions.map((channelId) =>
+ throwOnErr(() =>
+ storageServiceClient.addBotToChannel({
+ channel_id: channelId,
+ bot_id: vars.botId,
+ })
+ )
+ ),
+ ...removals.map((channelId) =>
+ throwOnErr(() =>
+ storageServiceClient.removeBotFromChannel({
+ channel_id: channelId,
+ bot_id: vars.botId,
+ })
+ )
+ ),
+ ]);
+ return {
+ failedCount: results.filter((result) => result.status === 'rejected')
+ .length,
+ };
+ },
+ onSuccess: (_data, vars) =>
+ invalidateBotChannelViews(vars.botId, [
+ ...vars.currentChannelIds,
+ ...vars.nextChannelIds,
+ ]),
+ onError: (error) => console.error('failed to sync bot channels', error),
+ }));
+}
+
+export function useRemoveBotFromChannelMutation() {
+ return useMutation(() => ({
+ gcTime: 0,
+ mutationFn: async (vars: AddBotToChannelParams) =>
+ await throwOnErr(() =>
+ storageServiceClient.removeBotFromChannel({
+ channel_id: vars.channelId,
+ bot_id: vars.botId,
+ })
+ ),
+ onSuccess: (_data, vars) =>
+ invalidateBotChannelViews(vars.botId, [vars.channelId]),
+ onError: (error) =>
+ console.error('failed to remove bot from channel', error),
+ }));
+}
+
+export function useCreateChannelScopedBotMutation() {
+ return useMutation(() => ({
+ gcTime: 0,
+ mutationFn: async (vars: CreateChannelScopedBotParams) => {
+ const { channelId, ...request } = vars;
+ return await throwOnErr(() =>
+ storageServiceClient.createChannelScopedBot({
+ ...request,
+ channel_id: channelId,
+ })
+ );
+ },
+ onSuccess: async (data, vars) => {
+ await Promise.all([
+ invalidateBots(),
+ invalidateBotChannelViews(data.bot.id, [vars.channelId]),
+ ]);
+ },
+ onError: (error) =>
+ console.error('failed to create channel-scoped bot', error),
+ }));
+}
diff --git a/js/app/packages/queries/channel/keys.ts b/js/app/packages/queries/channel/keys.ts
index dd50b2ac79..2fdf88c306 100644
--- a/js/app/packages/queries/channel/keys.ts
+++ b/js/app/packages/queries/channel/keys.ts
@@ -19,6 +19,9 @@ export const channelKeys = createQueryKeys('channel', {
participants: (channelID: string) => ({
queryKey: [channelID],
}),
+ channelBots: (channelID: string) => ({
+ queryKey: [channelID],
+ }),
threadReplies: (channelID: string, messageID: string) => ({
queryKey: [channelID, messageID],
}),
diff --git a/js/app/packages/service-clients/service-storage/client.ts b/js/app/packages/service-clients/service-storage/client.ts
index a4835b63b6..95d417480a 100644
--- a/js/app/packages/service-clients/service-storage/client.ts
+++ b/js/app/packages/service-clients/service-storage/client.ts
@@ -60,7 +60,9 @@ import type { ApiChannelMessagesPage } from './generated/schemas/apiChannelMessa
import type { ApiChannelParticipant } from './generated/schemas/apiChannelParticipant';
import type { ApiResolvedChannelMessage } from './generated/schemas/apiResolvedChannelMessage';
import type { ApiThreadReply } from './generated/schemas/apiThreadReply';
+import type { Bot } from './generated/schemas/bot';
import type { BotChannel } from './generated/schemas/botChannel';
+import type { BotToken } from './generated/schemas/botToken';
import type { ChannelMessageFilters } from './generated/schemas/channelMessageFilters';
import { ChannelType } from './generated/schemas/channelType';
import {
@@ -69,6 +71,8 @@ import {
} from './generated/schemas/cloudStorageItemType';
import type { CreateChannelRequest } from './generated/schemas/createChannelRequest';
import type { CreateChannelResponse } from './generated/schemas/createChannelResponse';
+import type { CreateChannelScopedBotRequest } from './generated/schemas/createChannelScopedBotRequest';
+import type { CreateChannelScopedBotResponse } from './generated/schemas/createChannelScopedBotResponse';
import type { CreateCommentResponse } from './generated/schemas/createCommentResponse';
import type { CreateCrmCommentRequest } from './generated/schemas/createCrmCommentRequest';
import type { CreateDocument200 as CreateDocumentResponse } from './generated/schemas/createDocument200';
@@ -257,6 +261,32 @@ export type TaskSimilaritySearchResponse = {
type WithBotId = { bot_id: string };
type WithChannelId = { channel_id: string };
+
+type CreateBotRequest = {
+ team_id?: string;
+ name: string;
+ handle: string;
+ description?: string;
+ avatar_url?: string;
+};
+
+type PatchBotRequest = {
+ name?: string;
+ handle?: string;
+ description?: string;
+ avatar_url?: string;
+};
+
+type CreateBotTokenRequest = {
+ label?: string;
+ expires_at?: string;
+};
+
+type CreateBotTokenResponse = {
+ token: BotToken;
+ bearer_token: string;
+};
+
type WithMessageId = { message_id: string };
type WithMentionId = { mention_id: string };
type WithEntity = { entity_type: string; entity_id: string };
@@ -483,6 +513,71 @@ export const storageServiceClient = {
).map((result) => result);
},
+ async getBots() {
+ return (
+ await dssFetch<Bot[]>(`/bots`, {
+ method: 'GET',
+ })
+ ).map((result) => result);
+ },
+
+ async createBot(args: CreateBotRequest) {
+ return (
+ await dssFetch<Bot>(`/bots`, {
+ method: 'POST',
+ body: JSON.stringify(args),
+ })
+ ).map((result) => result);
+ },
+
+ async getBot(args: WithBotId) {
+ return (
+ await dssFetch<Bot>(`/bots/${args.bot_id}`, {
+ method: 'GET',
+ })
+ ).map((result) => result);
+ },
+
+ async patchBot(args: WithBotId & PatchBotRequest) {
+ const { bot_id, ...request } = args;
+ return (
+ await dssFetch<Bot>(`/bots/${bot_id}`, {
+ method: 'PATCH',
+ body: JSON.stringify(request),
+ })
+ ).map((result) => result);
+ },
+
+ async deleteBot(args: WithBotId) {
+ return await dssFetch(`/bots/${args.bot_id}`, {
+ method: 'DELETE',
+ });
+ },
+
+ async createBotToken(args: WithBotId & CreateBotTokenRequest) {
+ const { bot_id, ...request } = args;
+ return (
+ await dssFetch<CreateBotTokenResponse>(`/bots/${bot_id}/tokens`, {
+ method: 'POST',
+ body: JSON.stringify(request),
+ })
+ ).map((result) => result);
+ },
+
+ async getBotTokens(args: WithBotId) {
+ return (
+ await dssFetch<BotToken[]>(`/bots/${args.bot_id}/tokens`, {
+ method: 'GET',
+ })
+ ).map((result) => result);
+ },
+
+ async revokeBotToken(args: WithBotId & { token_id: string }) {
+ return await dssFetch(`/bots/${args.bot_id}/tokens/${args.token_id}`, {
+ method: 'DELETE',
+ });
+ },
+
async getBotChannels(args: WithBotId) {
const { bot_id } = args;
return (
@@ -492,6 +587,21 @@ export const storageServiceClient = {
).map((result) => result);
},
+ async getChannelBots(args: WithChannelId) {
+ return (
+ await dssFetch<Bot[]>(`/channels/${args.channel_id}/bots`, {
+ method: 'GET',
+ })
+ ).map((result) => result);
+ },
+
+ async addBotToChannel(args: WithChannelId & WithBotId) {
+ return await dssFetch(`/channels/${args.channel_id}/bots`, {
+ method: 'POST',
+ body: JSON.stringify({ bot_id: args.bot_id }),
+ });
+ },
+
async removeBotFromChannel(args: WithBotId & WithChannelId) {
const { bot_id, channel_id } = args;
return await dssFetch(`/bots/${bot_id}/channels/${channel_id}`, {
@@ -499,6 +609,21 @@ export const storageServiceClient = {
});
},
+ async createChannelScopedBot(
+ args: WithChannelId & CreateChannelScopedBotRequest
+ ) {
+ const { channel_id, ...request } = args;
+ return (
+ await dssFetch<CreateChannelScopedBotResponse>(
+ `/channels/${channel_id}/bots/scoped`,
+ {
+ method: 'POST',
+ body: JSON.stringify(request),
+ }
+ )
+ ).map((result) => result);
+ },
+
async getOrCreateDirectMessage(args: GetOrCreateDmRequest) {
const { recipient_id } = args;
return (