Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
feat(bots): delete bots from bot settings (#335)
Leo779d43c5d8ff
diff --git a/.changeset/bold-bots-delete.md b/.changeset/bold-bots-delete.mdnew file mode 100644index 000000000..b24ec76d3--- /dev/null+++ b/.changeset/bold-bots-delete.md@@ -0,0 +1,5 @@+---+"akeru-bot": minor+---++Delete a bot from its settings page on web, or from chat settings on mobile. Deleting removes the bot from the roster, detaches its chats, stops its work, channels, and voice call, cancels work it sent or received, and removes its routines and skill assignments. Group chats keep their group and fall back to the boss when the deleted bot was answering. A group boss cannot be deleted until another bot takes over, and a bot cannot be deleted when its removal would leave a group with fewer than two active bots.diff --git a/apps/mobile/src/features/threads/ThreadComposer.commandMenu.test.tsx b/apps/mobile/src/features/threads/ThreadComposer.commandMenu.test.tsxindex 553d1e114..8bb4d69b7 100644--- a/apps/mobile/src/features/threads/ThreadComposer.commandMenu.test.tsx+++ b/apps/mobile/src/features/threads/ThreadComposer.commandMenu.test.tsx@@ -96,7 +96,7 @@ vi.mock("../../state/use-composer-path-search", () => ({useComposerPathSearch: () => ({ entries: [], isPending: false }),}));vi.mock("../../state/bots", () => ({- botEnvironment: { update: Symbol("update") },+ botEnvironment: { update: Symbol("update"), delete: Symbol("delete") },environmentBotsAtom: () => Symbol("bots"),environmentGroupsAtom: () => Symbol("groups"),}));diff --git a/apps/mobile/src/features/threads/ThreadComposer.dictation.test.tsx b/apps/mobile/src/features/threads/ThreadComposer.dictation.test.tsxindex 75c5da678..275256b4f 100644--- a/apps/mobile/src/features/threads/ThreadComposer.dictation.test.tsx+++ b/apps/mobile/src/features/threads/ThreadComposer.dictation.test.tsx@@ -110,7 +110,7 @@ vi.mock("../../state/use-composer-path-search", () => ({useComposerPathSearch: () => ({ entries: [], isPending: false }),}));vi.mock("../../state/bots", () => ({- botEnvironment: { update: Symbol("update") },+ botEnvironment: { update: Symbol("update"), delete: Symbol("delete") },environmentBotsAtom: () => Symbol("bots"),environmentGroupsAtom: () => Symbol("groups"),}));diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsxindex 3805fd60c..84114748b 100644--- a/apps/mobile/src/features/threads/ThreadComposer.tsx+++ b/apps/mobile/src/features/threads/ThreadComposer.tsx@@ -76,6 +76,7 @@ import { resolveThreadIdentity } from "./threadIdentity";import { serverEnvironment } from "../../state/server";import { useEnvironmentQuery } from "../../state/query";import { useAtomCommand } from "../../state/use-atom-command";+import { squashAtomCommandFailure } from "@akeru/client-runtime/state/runtime";import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover";import { matchesSlashSkillQuery } from "./composerSlashSkillSearch";import { composerMentionItemToken, isThreadMentionQuery } from "./composerMentionItems";@@ -331,6 +332,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer? composerIdentity.title: (bot?.name ?? providerBotName(composerProviderDriver));const updateBot = useAtomCommand(botEnvironment.update, { reportFailure: false });+ const deleteBot = useAtomCommand(botEnvironment.delete, { reportFailure: false });const settingsRoutePresentedRef = useRef(false);const wasExpandedBeforePreviewRef = useRef(false);const inFlightThreadIdsRef = useRef(new Set<string>());@@ -711,6 +713,16 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer},[bot, currentModelOption?.providerDriver, props.environmentId, updateBot],);+ const deleteThreadBot = useCallback(async () => {+ if (!bot) return t("The command failed.");+ const result = await deleteBot({+ environmentId: props.environmentId,+ input: { botId: bot.id },+ });+ if (result._tag !== "Failure") return null;+ const error = squashAtomCommandFailure(result);+ return error instanceof Error ? error.message : t("The command failed.");+ }, [bot, deleteBot, props.environmentId, t]);const settingsOwnerId = scopedThreadKey(props.environmentId, props.selectedThread.id);const settingsRouteSession = useMemo<ExistingThreadSettingsRouteSession>(() => ({@@ -741,6 +753,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerbotUsageCap: bot.usageCap,botUsageCapProviderDriver: currentModelOption?.providerDriver,onUpdateBotUsageCap: updateBotUsageCap,+ onDeleteBot: deleteThreadBot,}: {}),}),@@ -748,6 +761,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposercurrentModelSelection,currentRuntimeMode,bot,+ deleteThreadBot,props.environmentId,props.onUpdateModelSelection,props.onUpdateRuntimeMode,diff --git a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsxindex 699c338ef..041374399 100644--- a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx+++ b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx@@ -321,6 +321,9 @@ type ThreadSettingsSessionProps = {readonly botId: string;readonly botName?: string;};+ /** Deletes the chat's bot. Resolves false when the server refuses. */+ /** Resolves to null on success, or the reason the delete failed. */+ readonly onDeleteBot?: () => Promise<string | null>;};export type ExistingThreadSettingsRouteSession = ThreadSettingsSessionProps & {@@ -392,6 +395,7 @@ type ThreadSettingsSessionValue = {readonly toggleProvider: (providerKey: string) => void;readonly memoryThreadRef: ThreadSettingsSessionProps["memoryThreadRef"];readonly routinesRef: ThreadSettingsSessionProps["routinesRef"];+ readonly onDeleteBot: ThreadSettingsSessionProps["onDeleteBot"];/** False when the shown model's provider can neither hand off work nor receive it. */readonly canDelegate: boolean;};@@ -549,6 +553,7 @@ function ThreadSettingsSessionProvider(toggleProvider,memoryThreadRef: props.memoryThreadRef,routinesRef: props.routinesRef,+ onDeleteBot: props.onDeleteBot,canDelegate,}),[@@ -573,6 +578,7 @@ function ThreadSettingsSessionProvider(props.runtimeMode,props.memoryThreadRef,props.routinesRef,+ props.onDeleteBot,searchQuery,showLegacyToggle,toggleProvider,@@ -863,6 +869,8 @@ function ThreadSettingsOptionsItem(props: {</Text>)}+ <DeleteBotSection />+{Platform.OS !== "ios" && session.hasLegacyModels ? (<><Text className="px-5 pb-2 pt-7 text-sm font-t3-medium text-foreground-muted">@@ -882,6 +890,63 @@ function ThreadSettingsOptionsItem(props: {);}+/** Destructive bot removal, shown only for chats that belong to a bot. */+function DeleteBotSection() {+ const { t } = useMobileI18n();+ const session = useThreadSettingsSession();+ const presentation = useThreadSettingsPickerPresentation();+ const [deleting, setDeleting] = useState(false);+ const onDeleteBot = session.onDeleteBot;+ const botName = session.routinesRef?.botName;+ if (!onDeleteBot || !botName) return null;++ const deleteBot = async () => {+ setDeleting(true);+ const failure = await onDeleteBot();+ setDeleting(false);+ if (failure !== null) {+ Alert.alert(t("Could not delete {name}", { name: botName }), failure);+ return;+ }+ presentation.onClose();+ };+ const confirmDelete = () =>+ Alert.alert(+ t("Delete {name}? Its chats stay in your history. This cannot be undone.", {+ name: botName,+ }),+ undefined,+ [+ { text: t("Cancel"), style: "cancel" },+ { text: t("Delete"), style: "destructive", onPress: () => void deleteBot() },+ ],+ );++ return (+ <>+ <Text className="px-5 pb-2 pt-7 text-sm font-t3-medium text-foreground-muted">+ {t("Danger")}+ </Text>+ <View className="mx-4 overflow-hidden rounded-2xl bg-card">+ <Pressable+ accessibilityRole="button"+ accessibilityState={{ disabled: deleting }}+ disabled={deleting}+ onPress={confirmDelete}+ className="min-h-11 flex-row items-center bg-card px-4 py-2 active:bg-subtle"+ >+ <Text className="text-sm font-t3-medium text-danger">+ {deleting ? t("Deleting…") : t("Delete bot")}+ </Text>+ </Pressable>+ </View>+ <Text className="px-5 pt-2 text-xs leading-4 text-foreground-muted">+ {t("Remove {name} from the roster. Its chats stay in your history.", { name: botName })}+ </Text>+ </>+ );+}+/** One native scroll owner for the model catalog and its related settings. */function ThreadSettingsMainContent(props: {readonly onOpenSubmenu: (submenu: ThreadSettingsSubmenuPage) => void;diff --git a/apps/server/src/channels/ChannelRuntime.ts b/apps/server/src/channels/ChannelRuntime.tsindex 68d804f62..3556379ed 100644--- a/apps/server/src/channels/ChannelRuntime.ts+++ b/apps/server/src/channels/ChannelRuntime.ts@@ -1199,7 +1199,7 @@ const stopArchivedBotChannels = <E, R>(events: Stream.Stream<OrchestrationEvent, E, R>,) =>Stream.runForEach(events, (event) =>- event.type === "bot.archived"+ event.type === "bot.archived" || event.type === "bot.deleted"? stopChannelsForBot(ctx, event.payload.botId): event.type === "thread.deleted" || event.type === "thread.archived"? clearChannelThreadStatuses(ctx, event.payload.threadId)diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.tsindex cbb94ba6a..66d1c1d51 100644--- a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts+++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.ts@@ -79,6 +79,7 @@ function commandToAggregateRef(command: OrchestrationCommand): {case "bot.update":case "bot.archive":case "bot.restore":+ case "bot.delete":return {aggregateKind: "bot",aggregateId: command.botId,diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.tsindex 9c838cdac..d1944c3b1 100644--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts@@ -582,6 +582,9 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti});return;}+ case "bot.deleted":+ yield* projectionBotRepository.deleteById({ botId: event.payload.botId });+ return;default:return;}@@ -2151,6 +2154,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti"bot.updated","bot.archived","bot.restored",+ "bot.deleted",]),apply: applyBotsProjection,},diff --git a/apps/server/src/orchestration/Schemas.ts b/apps/server/src/orchestration/Schemas.tsindex 479fb255a..e370f6cd9 100644--- a/apps/server/src/orchestration/Schemas.ts+++ b/apps/server/src/orchestration/Schemas.ts@@ -6,6 +6,7 @@ import {BotUpdatedPayload as ContractsBotUpdatedPayloadSchema,BotArchivedPayload as ContractsBotArchivedPayloadSchema,BotRestoredPayload as ContractsBotRestoredPayloadSchema,+ BotDeletedPayload as ContractsBotDeletedPayloadSchema,GroupCreatedPayload as ContractsGroupCreatedPayloadSchema,GroupRenamedPayload as ContractsGroupRenamedPayloadSchema,GroupDeletedPayload as ContractsGroupDeletedPayloadSchema,@@ -57,6 +58,7 @@ export const BotCreatedPayload = ContractsBotCreatedPayloadSchema;export const BotUpdatedPayload = ContractsBotUpdatedPayloadSchema;export const BotArchivedPayload = ContractsBotArchivedPayloadSchema;export const BotRestoredPayload = ContractsBotRestoredPayloadSchema;+export const BotDeletedPayload = ContractsBotDeletedPayloadSchema;export const GroupCreatedPayload = ContractsGroupCreatedPayloadSchema;export const GroupRenamedPayload = ContractsGroupRenamedPayloadSchema;export const GroupDeletedPayload = ContractsGroupDeletedPayloadSchema;diff --git a/apps/server/src/orchestration/decider.botDelete.test.ts b/apps/server/src/orchestration/decider.botDelete.test.tsnew file mode 100644index 000000000..def2a33fe--- /dev/null+++ b/apps/server/src/orchestration/decider.botDelete.test.ts@@ -0,0 +1,586 @@+import {+ BotId,+ CommandId,+ DelegationId,+ EventId,+ GroupId,+ ProjectId,+ ProviderInstanceId,+ RoutineId,+ SkillAssignmentId,+ SkillId,+ ThreadId,+ TurnId,+ type AkeruDelegationRecord,+ type OrchestrationBot,+ type OrchestrationGroup,+ type OrchestrationReadModel,+ type OrchestrationSession,+ type OrchestrationThread,+ isGroupBotMember,+} from "@akeru/contracts";+import * as NodeServices from "@effect/platform-node/NodeServices";+import { expect, it } from "@effect/vitest";+import * as Effect from "effect/Effect";++import { decideOrchestrationCommand } from "./decider.ts";+import { createEmptyReadModel, projectEvent } from "./projector.ts";++const NOW = "2026-09-29T12:00:00.000Z";+const BOT_ID = BotId.make("bot-main");+const OTHER_BOT_ID = BotId.make("bot-other");+const THIRD_BOT_ID = BotId.make("bot-third");+const GROUP_ID = GroupId.make("group-team");++function makeBot(input: {+ readonly id: OrchestrationBot["id"];+ readonly archivedAt?: OrchestrationBot["archivedAt"];+}): OrchestrationBot {+ return {+ id: input.id,+ name: input.id,+ title: "Agent",+ label: null,+ description: null,+ disabledMcpServerIds: [],+ avatar: { kind: "dither", seed: input.id },+ engine: null,+ sandbox: "local",+ runtimeMode: "full-access",+ usageCap: null,+ imageProvider: null,+ voiceEnabled: false,+ channelBindings: [],+ groupId: null,+ archivedAt: input.archivedAt ?? null,+ createdAt: NOW,+ updatedAt: NOW,+ };+}++function makeBotThread(botId: OrchestrationBot["id"]): OrchestrationThread {+ return {+ id: ThreadId.make(`thread-${botId}`),+ projectId: ProjectId.make("project-1"),+ botId,+ groupId: null,+ respondingBotId: null,+ title: "Bot chat",+ modelSelection: { instanceId: ProviderInstanceId.make("default"), model: "default-model" },+ 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 makeGroup(+ input: {+ readonly bossBotId?: OrchestrationGroup["bossBotId"];+ readonly members?: OrchestrationGroup["members"];+ } = {},+): OrchestrationGroup {+ return {+ id: GROUP_ID,+ name: "Team",+ bossBotId: input.bossBotId ?? BOT_ID,+ members: input.members ?? [+ { kind: "bot", botId: BOT_ID, role: "boss" },+ { kind: "bot", botId: OTHER_BOT_ID, role: "specialist" },+ ],+ createdAt: NOW,+ updatedAt: NOW,+ };+}++function makeReadModel(input: {+ readonly bots?: ReadonlyArray<OrchestrationBot>;+ readonly groups?: ReadonlyArray<OrchestrationGroup>;+ readonly threads?: ReadonlyArray<OrchestrationThread>;+ readonly delegations?: ReadonlyArray<AkeruDelegationRecord>;+}): OrchestrationReadModel {+ return {+ ...createEmptyReadModel(NOW),+ bots: input.bots ?? [],+ groups: input.groups ?? [],+ threads: input.threads ?? [],+ delegations: input.delegations ?? [],+ };+}++function makeSession(+ threadId: OrchestrationThread["id"],+ status: OrchestrationSession["status"],+): OrchestrationSession {+ return {+ threadId,+ status,+ providerName: "codex",+ runtimeMode: "full-access",+ activeTurnId: status === "running" ? TurnId.make(`turn-${threadId}`) : null,+ lastError: null,+ updatedAt: NOW,+ };+}++function makeDelegation(+ input: Pick<AkeruDelegationRecord, "delegationId" | "parentBotId" | "childBotId" | "phase">,+): AkeruDelegationRecord {+ return {+ ...input,+ parentDelegationId: null,+ parentThreadId: ThreadId.make(`thread-${input.parentBotId}`),+ parentTurnId: TurnId.make(`turn-${input.parentBotId}`),+ ancestorBotIds: [input.parentBotId],+ depth: 1,+ task: "Compare three flights.",+ expectedResult: "A short comparison.",+ deadline: null,+ access: {+ allowedToolIds: [],+ memoryScopes: [],+ sandbox: null,+ runtimeMode: "full-access",+ hasUserComputer: false,+ enabledMcpServerIds: [],+ disabledMcpServerIds: [],+ approvalCeiling: "send",+ },+ billedBotId: input.childBotId,+ keep: false,+ anchorMessageId: null,+ retryOfDelegationId: null,+ trigger: "bot",+ createdAt: NOW,+ updatedAt: NOW,+ };+}++it.layer(NodeServices.layer)("bot delete decider", (it) => {+ it.effect("deletes a bot and detaches its chats", () =>+ Effect.gen(function* () {+ const readModel = makeReadModel({+ bots: [makeBot({ id: BOT_ID })],+ threads: [makeBotThread(BOT_ID)],+ });+ const result = yield* decideOrchestrationCommand({+ command: {+ type: "bot.delete",+ commandId: CommandId.make("cmd-bot-delete"),+ botId: BOT_ID,+ },+ readModel,+ });+ const events = Array.isArray(result) ? result : [result];++ expect(events.map((event) => event.type)).toEqual([+ "thread.ownership-updated",+ "bot.deleted",+ ]);+ const ownership = events[0];+ if (ownership?.type !== "thread.ownership-updated") {+ throw new Error("Expected thread.ownership-updated");+ }+ expect(ownership.payload.botId).toBeNull();+ expect(ownership.payload.groupId).toBeNull();++ let next = readModel;+ let sequence = readModel.snapshotSequence;+ for (const event of events) {+ sequence += 1;+ next = yield* projectEvent(next, {+ ...event,+ sequence,+ eventId: EventId.make(`evt-${sequence}`),+ });+ }+ expect(next.bots).toHaveLength(0);+ expect(next.threads[0]?.botId).toBeNull();+ }),+ );++ it.effect("stops the bot's sessions, child chats, and in-flight delegations", () =>+ Effect.gen(function* () {+ const botThread = {+ ...makeBotThread(BOT_ID),+ session: makeSession(ThreadId.make(`thread-${BOT_ID}`), "running"),+ };+ const idleThread = {+ ...makeBotThread(BOT_ID),+ id: ThreadId.make("thread-idle"),+ session: makeSession(ThreadId.make("thread-idle"), "stopped"),+ };+ const childThread = {+ ...makeBotThread(OTHER_BOT_ID),+ id: ThreadId.make("thread-child"),+ parentThreadId: botThread.id,+ session: makeSession(ThreadId.make("thread-child"), "running"),+ };+ const unrelatedThread = {+ ...makeBotThread(THIRD_BOT_ID),+ session: makeSession(ThreadId.make(`thread-${THIRD_BOT_ID}`), "running"),+ };+ const sent = makeDelegation({+ delegationId: DelegationId.make("delegation-sent"),+ parentBotId: BOT_ID,+ childBotId: OTHER_BOT_ID,+ phase: {+ _tag: "Running",+ childThreadId: childThread.id,+ childTurnId: TurnId.make("turn-child"),+ startedAt: NOW,+ progress: null,+ },+ });+ const received = makeDelegation({+ delegationId: DelegationId.make("delegation-received"),+ parentBotId: OTHER_BOT_ID,+ childBotId: BOT_ID,+ phase: { _tag: "Queued" },+ });+ const finished = makeDelegation({+ delegationId: DelegationId.make("delegation-finished"),+ parentBotId: BOT_ID,+ childBotId: OTHER_BOT_ID,+ phase: {+ _tag: "Canceled",+ childThreadId: null,+ childTurnId: null,+ startedAt: null,+ completedAt: NOW,+ canceledBy: "user",+ },+ });+ const unrelated = makeDelegation({+ delegationId: DelegationId.make("delegation-unrelated"),+ parentBotId: OTHER_BOT_ID,+ childBotId: THIRD_BOT_ID,+ phase: { _tag: "Queued" },+ });+ const readModel = makeReadModel({+ bots: [+ makeBot({ id: BOT_ID }),+ makeBot({ id: OTHER_BOT_ID }),+ makeBot({ id: THIRD_BOT_ID }),+ ],+ threads: [botThread, idleThread, childThread, unrelatedThread],+ delegations: [sent, received, finished, unrelated],+ });+ const result = yield* decideOrchestrationCommand({+ command: {+ type: "bot.delete",+ commandId: CommandId.make("cmd-bot-delete-working"),+ botId: BOT_ID,+ },+ readModel,+ });+ const events = Array.isArray(result) ? result : [result];++ expect(events.map((event) => event.type)).toEqual([+ "delegation.updated",+ "delegation.updated",+ "thread.session-stop-requested",+ "thread.session-stop-requested",+ "thread.ownership-updated",+ "thread.ownership-updated",+ "bot.deleted",+ ]);+ expect(+ events.flatMap((event) =>+ event.type === "thread.session-stop-requested" ? [event.payload.threadId] : [],+ ),+ ).toEqual([botThread.id, childThread.id]);++ let next = readModel;+ let sequence = readModel.snapshotSequence;+ for (const event of events) {+ sequence += 1;+ next = yield* projectEvent(next, {+ ...event,+ sequence,+ eventId: EventId.make(`evt-${sequence}`),+ });+ }+ const phases = Object.fromEntries(+ next.delegations.map((delegation) => [delegation.delegationId, delegation.phase]),+ );+ expect(phases[sent.delegationId]).toMatchObject({+ _tag: "Canceled",+ childThreadId: childThread.id,+ childTurnId: TurnId.make("turn-child"),+ });+ expect(phases[received.delegationId]?._tag).toBe("Canceled");+ expect(phases[finished.delegationId]).toEqual(finished.phase);+ expect(phases[unrelated.delegationId]?._tag).toBe("Queued");+ }),+ );++ it.effect("clears a deleted group responder without detaching the chat", () =>+ Effect.gen(function* () {+ const groupThread = {+ ...makeBotThread(BOT_ID),+ id: ThreadId.make("thread-group"),+ botId: null,+ groupId: GROUP_ID,+ respondingBotId: BOT_ID,+ session: makeSession(ThreadId.make("thread-group"), "ready"),+ };+ const readModel = makeReadModel({+ bots: [+ makeBot({ id: BOT_ID }),+ makeBot({ id: OTHER_BOT_ID }),+ makeBot({ id: THIRD_BOT_ID }),+ ],+ groups: [+ makeGroup({+ bossBotId: OTHER_BOT_ID,+ members: [+ { kind: "bot", botId: OTHER_BOT_ID, role: "boss" },+ { kind: "bot", botId: THIRD_BOT_ID, role: "specialist" },+ { kind: "bot", botId: BOT_ID, role: "specialist" },+ ],+ }),+ ],+ threads: [groupThread],+ });+ const result = yield* decideOrchestrationCommand({+ command: {+ type: "bot.delete",+ commandId: CommandId.make("cmd-delete-responder"),+ botId: BOT_ID,+ },+ readModel,+ });+ const events = Array.isArray(result) ? result : [result];++ expect(events.map((event) => event.type)).toEqual([+ "thread.session-stop-requested",+ "group.member-unassigned",+ "thread.ownership-updated",+ "bot.deleted",+ ]);++ let next = readModel;+ let sequence = readModel.snapshotSequence;+ for (const event of events) {+ sequence += 1;+ next = yield* projectEvent(next, {+ ...event,+ sequence,+ eventId: EventId.make(`evt-${sequence}`),+ });+ }+ const thread = next.threads.find((entry) => entry.id === groupThread.id);+ expect(thread?.groupId).toBe(GROUP_ID);+ expect(thread?.botId).toBeNull();+ expect(thread?.respondingBotId).toBeNull();+ }),+ );++ it.effect("rejects deleting a group boss", () =>+ Effect.gen(function* () {+ const error = yield* decideOrchestrationCommand({+ command: {+ type: "bot.delete",+ commandId: CommandId.make("cmd-delete-boss"),+ botId: BOT_ID,+ },+ readModel: makeReadModel({+ bots: [makeBot({ id: BOT_ID }), makeBot({ id: OTHER_BOT_ID })],+ groups: [makeGroup()],+ }),+ }).pipe(Effect.flip);++ if (error._tag !== "OrchestrationCommandInvariantError") {+ throw new Error("Expected boss delete invariant error");+ }+ expect(error.detail).toContain("Set a new boss before deleting it");+ }),+ );++ it.effect("rejects deleting a bot when its group would have fewer than two active bots", () =>+ Effect.gen(function* () {+ const error = yield* decideOrchestrationCommand({+ command: {+ type: "bot.delete",+ commandId: CommandId.make("cmd-delete-specialist"),+ botId: OTHER_BOT_ID,+ },+ readModel: makeReadModel({+ bots: [makeBot({ id: BOT_ID }), makeBot({ id: OTHER_BOT_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("unassigns group membership when deleting a member bot", () =>+ Effect.gen(function* () {+ const readModel = makeReadModel({+ bots: [+ makeBot({ id: BOT_ID }),+ makeBot({ id: OTHER_BOT_ID }),+ makeBot({ id: THIRD_BOT_ID }),+ ],+ groups: [+ makeGroup({+ members: [+ { kind: "bot", botId: BOT_ID, role: "boss" },+ { kind: "bot", botId: OTHER_BOT_ID, role: "specialist" },+ { kind: "bot", botId: THIRD_BOT_ID, role: "specialist" },+ ],+ }),+ ],+ });+ const result = yield* decideOrchestrationCommand({+ command: {+ type: "bot.delete",+ commandId: CommandId.make("cmd-delete-member"),+ botId: THIRD_BOT_ID,+ },+ readModel,+ });+ const events = Array.isArray(result) ? result : [result];++ expect(events.map((event) => event.type)).toEqual(["group.member-unassigned", "bot.deleted"]);++ let next = readModel;+ let sequence = readModel.snapshotSequence;+ for (const event of events) {+ sequence += 1;+ next = yield* projectEvent(next, {+ ...event,+ sequence,+ eventId: EventId.make(`evt-${sequence}`),+ });+ }+ expect(next.bots).toHaveLength(2);+ const memberIds = next.groups[0]?.members+ .filter(isGroupBotMember)+ .map((member) => member.botId);+ expect(memberIds).toEqual([BOT_ID, OTHER_BOT_ID]);+ }),+ );++ it.effect("deletes an archived bot", () =>+ Effect.gen(function* () {+ const result = yield* decideOrchestrationCommand({+ command: {+ type: "bot.delete",+ commandId: CommandId.make("cmd-delete-archived"),+ botId: BOT_ID,+ },+ readModel: makeReadModel({+ bots: [makeBot({ id: BOT_ID, archivedAt: NOW })],+ }),+ });+ const events = Array.isArray(result) ? result : [result];++ expect(events.map((event) => event.type)).toEqual(["bot.deleted"]);+ }),+ );++ it.effect("deletes the bot's routines and skill assignments", () =>+ Effect.gen(function* () {+ const withRoutine = yield* projectEvent(createEmptyReadModel(NOW), {+ sequence: 1,+ eventId: EventId.make("evt-routine-approved"),+ aggregateKind: "routine",+ aggregateId: RoutineId.make("routine-1"),+ type: "routine.approved",+ occurredAt: NOW,+ commandId: CommandId.make("cmd-routine-create"),+ causationEventId: null,+ correlationId: CommandId.make("cmd-routine-create"),+ metadata: {},+ payload: {+ routine: {+ id: RoutineId.make("routine-1"),+ botId: BOT_ID,+ delegateToBotId: null,+ targetThreadId: ThreadId.make("thread-1"),+ job: "Daily brief",+ procedure: "Summarize this chat.",+ schedule: { kind: "daily", time: "09:00" },+ timezone: "America/New_York",+ skillAssignmentIds: [],+ connectorDependencies: [],+ projectId: ProjectId.make("project-1"),+ sandbox: "local",+ approvalPolicy: "approval-required",+ procedureVersion: 1,+ approvalVersion: 1,+ enabled: true,+ lifecycle: "approved",+ nextRunAt: NOW,+ lastRunAt: null,+ latestResult: null,+ latestFailure: null,+ createdAt: NOW,+ updatedAt: NOW,+ deletedAt: null,+ },+ },+ });+ const readModel = {+ ...(yield* projectEvent(withRoutine, {+ sequence: 2,+ eventId: EventId.make("evt-skill-assigned"),+ aggregateKind: "skill-assignment",+ aggregateId: SkillAssignmentId.make("assignment-1"),+ type: "skill-assignment.assigned",+ occurredAt: NOW,+ commandId: CommandId.make("cmd-skill-assign"),+ causationEventId: null,+ correlationId: CommandId.make("cmd-skill-assign"),+ metadata: {},+ payload: {+ assignment: {+ id: SkillAssignmentId.make("assignment-1"),+ botId: BOT_ID,+ skillId: SkillId.make("skill-1"),+ name: "search",+ description: null,+ createdAt: NOW,+ updatedAt: NOW,+ },+ },+ })),+ bots: [makeBot({ id: BOT_ID })],+ } satisfies OrchestrationReadModel;++ const result = yield* decideOrchestrationCommand({+ command: {+ type: "bot.delete",+ commandId: CommandId.make("cmd-delete-with-routine"),+ botId: BOT_ID,+ },+ readModel,+ });+ const events = Array.isArray(result) ? result : [result];++ expect(events.map((event) => event.type)).toEqual([+ "routine.deleted",+ "skill-assignment.unassigned",+ "bot.deleted",+ ]);+ }),+ );+});diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.tsindex 9aa66578a..2f99001cc 100644--- a/apps/server/src/orchestration/decider.ts+++ b/apps/server/src/orchestration/decider.ts@@ -816,6 +816,219 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"};}+ case "bot.delete": {+ const bot = yield* requireBot({ 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 deleting 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;+ const events: Array<Omit<OrchestrationEvent, "sequence">> = [];+ // Canceling interrupts each child turn, so work the bot sent or received stops with it.+ for (const delegation of readModel.delegations) {+ if (+ TERMINAL_DELEGATION_PHASES.has(delegation.phase._tag) ||+ (delegation.parentBotId !== bot.id &&+ delegation.childBotId !== bot.id &&+ !delegation.ancestorBotIds.includes(bot.id))+ ) {+ continue;+ }+ const canceledAt =+ Date.parse(occurredAt) >= Date.parse(delegation.updatedAt)+ ? occurredAt+ : delegation.updatedAt;+ events.push({+ ...(yield* withEventBase({+ aggregateKind: "delegation",+ aggregateId: delegation.delegationId,+ occurredAt: canceledAt,+ commandId: command.commandId,+ })),+ type: "delegation.updated",+ payload: {+ delegation: {+ ...delegation,+ phase: {+ _tag: "Canceled",+ childThreadId: delegationChildThreadId(delegation.phase),+ childTurnId: delegationChildTurnId(delegation.phase),+ startedAt: delegation.phase._tag === "Queued" ? null : delegation.phase.startedAt,+ completedAt: canceledAt,+ canceledBy: "user",+ },+ updatedAt: canceledAt,+ },+ },+ });+ }+ // Chats the bot owns or is answering in a group, plus their child chats, lose their agent.+ const liveThreads = readModel.threads.filter((thread) => thread.deletedAt === null);+ const stoppedThreadIds = new Set(+ liveThreads+ .filter((thread) => thread.botId === bot.id || thread.respondingBotId === bot.id)+ .map((thread) => thread.id),+ );+ for (let grew = true; grew; ) {+ grew = false;+ for (const thread of liveThreads) {+ if (+ !stoppedThreadIds.has(thread.id) &&+ thread.parentThreadId != null &&+ stoppedThreadIds.has(thread.parentThreadId)+ ) {+ stoppedThreadIds.add(thread.id);+ grew = true;+ }+ }+ }+ for (const thread of liveThreads) {+ if (+ !stoppedThreadIds.has(thread.id) ||+ !thread.session ||+ thread.session.status === "stopped"+ ) {+ continue;+ }+ events.push({+ ...(yield* withEventBase({+ aggregateKind: "thread",+ aggregateId: thread.id,+ occurredAt,+ commandId: command.commandId,+ })),+ type: "thread.session-stop-requested",+ payload: {+ threadId: thread.id,+ createdAt: occurredAt,+ },+ });+ }+ for (const group of readModel.groups) {+ if (!group.members.some((member) => isGroupBotMember(member) && member.botId === bot.id)) {+ continue;+ }+ events.push({+ ...(yield* withEventBase({+ aggregateKind: "group",+ aggregateId: group.id,+ occurredAt,+ commandId: command.commandId,+ })),+ type: "group.member-unassigned",+ payload: {+ groupId: group.id,+ botId: bot.id,+ updatedAt: occurredAt,+ },+ });+ }+ for (const thread of liveThreads) {+ const owned = thread.botId === bot.id;+ if (!owned && thread.respondingBotId !== bot.id) {+ continue;+ }+ // An owned chat is detached. A group chat keeps its owners and only drops the responder.+ events.push({+ ...(yield* withEventBase({+ aggregateKind: "thread",+ aggregateId: thread.id,+ occurredAt,+ commandId: command.commandId,+ })),+ type: "thread.ownership-updated",+ payload: {+ threadId: thread.id,+ botId: owned ? null : (thread.botId ?? null),+ groupId: owned ? null : (thread.groupId ?? null),+ updatedAt: occurredAt,+ },+ });+ }+ for (const routine of readModel.routines ?? []) {+ if (routine.botId !== bot.id || routine.lifecycle === "deleted") {+ continue;+ }+ events.push({+ ...(yield* withEventBase({+ aggregateKind: "routine",+ aggregateId: routine.id,+ occurredAt,+ commandId: command.commandId,+ })),+ type: "routine.deleted",+ payload: {+ routine: {+ ...routine,+ enabled: false,+ lifecycle: "deleted",+ nextRunAt: null,+ updatedAt: occurredAt,+ deletedAt: occurredAt,+ },+ },+ });+ }+ for (const assignment of readModel.skillAssignments ?? []) {+ if (assignment.botId !== bot.id) {+ continue;+ }+ events.push({+ ...(yield* withEventBase({+ aggregateKind: "skill-assignment",+ aggregateId: assignment.id,+ occurredAt,+ commandId: command.commandId,+ })),+ type: "skill-assignment.unassigned",+ payload: {+ assignmentId: assignment.id,+ botId: bot.id,+ removedAt: occurredAt,+ },+ });+ }+ events.push({+ ...(yield* withEventBase({+ aggregateKind: "bot",+ aggregateId: command.botId,+ occurredAt,+ commandId: command.commandId,+ })),+ type: "bot.deleted",+ payload: {+ botId: command.botId,+ deletedAt: occurredAt,+ },+ });+ return events;+ }+case "group.create": {yield* requireGroupAbsent({ readModel, command, groupId: command.groupId });if (command.bossBotId === undefined) {diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.tsindex 5242c4baf..c8d966529 100644--- a/apps/server/src/orchestration/projector.ts+++ b/apps/server/src/orchestration/projector.ts@@ -36,6 +36,7 @@ import { toProjectorDecodeError, type OrchestrationProjectorDecodeError } from "import {BotArchivedPayload,BotCreatedPayload,+ BotDeletedPayload,BotRestoredPayload,BotUpdatedPayload,GroupBossSetPayload,@@ -481,6 +482,14 @@ export function projectEvent(})),);+ case "bot.deleted":+ return decodeForEvent(BotDeletedPayload, event.payload, event.type, "payload").pipe(+ Effect.map((payload) => ({+ ...nextBase,+ bots: nextBase.bots.filter((entry) => entry.id !== payload.botId),+ })),+ );+case "group.created":return decodeForEvent(GroupCreatedPayload, event.payload, event.type, "payload").pipe(Effect.map((payload) => {diff --git a/apps/server/src/persistence/Layers/ProjectionBots.ts b/apps/server/src/persistence/Layers/ProjectionBots.tsindex 8975dcb09..f200b4018 100644--- a/apps/server/src/persistence/Layers/ProjectionBots.ts+++ b/apps/server/src/persistence/Layers/ProjectionBots.ts@@ -109,6 +109,11 @@ const makeProjectionBotRepository = Effect.gen(function* () {`,});+ const deleteBotRow = SqlSchema.void({+ Request: GetProjectionBotInput,+ execute: ({ botId }) => sql`DELETE FROM projection_bots WHERE bot_id = ${botId}`,+ });+const upsert: ProjectionBotRepositoryShape["upsert"] = (row) =>upsertBotRow(row).pipe(Effect.mapError(toPersistenceSqlError("ProjectionBotRepository.upsert:query")),@@ -123,8 +128,12 @@ const makeProjectionBotRepository = Effect.gen(function* () {Effect.map((rows) => rows.map(toProjectionBot)),Effect.mapError(toPersistenceSqlError("ProjectionBotRepository.listAll:query")),);+ const deleteById: ProjectionBotRepositoryShape["deleteById"] = (input) =>+ deleteBotRow(input).pipe(+ Effect.mapError(toPersistenceSqlError("ProjectionBotRepository.deleteById:query")),+ );- return { upsert, getById, listAll } satisfies ProjectionBotRepositoryShape;+ return { upsert, getById, listAll, deleteById } satisfies ProjectionBotRepositoryShape;});export const ProjectionBotRepositoryLive = Layer.effect(diff --git a/apps/server/src/persistence/Services/ProjectionBots.ts b/apps/server/src/persistence/Services/ProjectionBots.tsindex 6e8e91622..e30331111 100644--- a/apps/server/src/persistence/Services/ProjectionBots.ts+++ b/apps/server/src/persistence/Services/ProjectionBots.ts@@ -53,6 +53,9 @@ export interface ProjectionBotRepositoryShape {input: GetProjectionBotInput,) => Effect.Effect<Option.Option<ProjectionBot>, ProjectionRepositoryError>;readonly listAll: () => Effect.Effect<ReadonlyArray<ProjectionBot>, ProjectionRepositoryError>;+ readonly deleteById: (+ input: GetProjectionBotInput,+ ) => Effect.Effect<void, ProjectionRepositoryError>;}export class ProjectionBotRepository extends Context.Service<diff --git a/apps/server/src/portability.ts b/apps/server/src/portability.tsindex d6b496ecd..a066b9ff7 100644--- a/apps/server/src/portability.ts+++ b/apps/server/src/portability.ts@@ -1299,6 +1299,7 @@ function itemForCommand(case "bot.update":case "bot.archive":case "bot.restore":+ case "bot.delete":return `bot:${command.botId}`;case "group.create":case "group.rename":diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.tsindex 12d6b50d1..1f37a713e 100644--- a/apps/server/src/server.test.ts+++ b/apps/server/src/server.test.ts@@ -927,6 +927,7 @@ const buildAppUnderTest = (options?: {upsert: () => Effect.void,getById: () => Effect.succeed(Option.none()),listAll: () => Effect.succeed([]),+ deleteById: () => Effect.void,...options?.layers?.projectionBots,} satisfies ProjectionBots.ProjectionBotRepositoryShape),Layer.mock(BotUsageLedger)({diff --git a/apps/server/src/telemetry/AnalyticsService.test.ts b/apps/server/src/telemetry/AnalyticsService.test.tsindex bb029d32b..a73c3a50d 100644--- a/apps/server/src/telemetry/AnalyticsService.test.ts+++ b/apps/server/src/telemetry/AnalyticsService.test.ts@@ -360,6 +360,96 @@ it.layer(NodeServices.layer)("anonymous analytics", (it) => {}),);+ it.effect("counts bots_total from each bot's latest lifecycle event", () =>+ Effect.gen(function* () {+ const captured: unknown[] = [];+ const serverConfigLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {+ prefix: "akeru-analytics-bots-total-",+ });+ const configLayer = ConfigProvider.layer(+ ConfigProvider.fromUnknown({+ T3CODE_TELEMETRY_ENABLED: true,+ T3CODE_POSTHOG_KEY: "phc_test",+ T3CODE_POSTHOG_HOST: "http://localhost",+ }),+ );+ const analyticsLayer = makeLayers(serverConfigLayer).pipe(Layer.provide(configLayer));+ const batchServerLayer = HttpServer.serve(+ Effect.gen(function* () {+ const request = yield* HttpServerRequest.HttpServerRequest;+ captured.push(yield* request.json);+ return HttpServerResponse.jsonUnsafe({});+ }),+ );++ yield* Effect.gen(function* () {+ yield* Layer.launch(batchServerLayer).pipe(Effect.forkScoped);+ const config = yield* ServerConfig.ServerConfig;+ const fs = yield* FileSystem.FileSystem;+ const sql = yield* SqlClient.SqlClient;+ const analytics = yield* AnalyticsService.AnalyticsService;+ const currentStart = AnalyticsService.bucketStartAt(+ DateTime.toEpochMillis(yield* DateTime.now),+ );+ const firstStart = DateTime.formatIso(+ DateTime.subtract(DateTime.makeUnsafe(currentStart), { hours: 6 }),+ );+ const eventAt = DateTime.formatIso(+ DateTime.add(DateTime.makeUnsafe(firstStart), { minutes: 1 }),+ );++ yield* fs.writeFileString(+ config.analyticsStatePath,+ encodeJson({+ version: 1,+ installationId: "0f64da24-2c54-4d2a-9d68-f117c4e78e02",+ cursorBucketStart: firstStart,+ deliveryDay: currentStart.slice(0, 10),+ deliveredToday: 0,+ firstActiveInstallReported: true,+ pending: [],+ }),+ );++ const insertEvent = (+ eventId: string,+ streamId: string,+ streamVersion: number,+ eventType: string,+ ) =>+ sql`+ INSERT INTO orchestration_events (+ event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at,+ command_id, causation_event_id, correlation_id, actor_kind, payload_json, metadata_json+ ) VALUES (+ ${eventId}, 'bot', ${streamId}, ${streamVersion}, ${eventType},+ ${eventAt}, NULL, NULL, NULL, 'client', '{}', '{}'+ )+ `;++ yield* insertEvent("event-bot-a-created", "bot-a", 0, "bot.created");+ yield* insertEvent("event-bot-a-archived", "bot-a", 1, "bot.archived");+ yield* insertEvent("event-bot-a-deleted", "bot-a", 2, "bot.deleted");+ yield* insertEvent("event-bot-b-created", "bot-b", 0, "bot.created");+ yield* insertEvent("event-bot-c-created", "bot-c", 0, "bot.created");+ yield* insertEvent("event-bot-c-archived", "bot-c", 1, "bot.archived");+ yield* insertEvent("event-bot-c-restored", "bot-c", 2, "bot.restored");++ yield* analytics.flush;++ const requests = captured as ReadonlyArray<{+ readonly batch: ReadonlyArray<{+ readonly properties: { readonly bots_total: number; readonly bots_deleted: number };+ }>;+ }>;+ assert.equal(requests[0]?.batch.length, 1);+ assert.equal(requests[0]?.batch[0]?.properties.bots_total, 2);+ // Archiving and then deleting bot-a removes it once.+ assert.equal(requests[0]?.batch[0]?.properties.bots_deleted, 2);+ }).pipe(Effect.provide(analyticsLayer));+ }),+ );+for (const [name, environment] of [["development", { NODE_ENV: "development", T3CODE_POSTHOG_KEY: "phc_test" }],["test", { NODE_ENV: "test", T3CODE_POSTHOG_KEY: "phc_test" }],diff --git a/apps/server/src/telemetry/AnalyticsService.ts b/apps/server/src/telemetry/AnalyticsService.tsindex 6f6624c16..d42ba9c71 100644--- a/apps/server/src/telemetry/AnalyticsService.ts+++ b/apps/server/src/telemetry/AnalyticsService.ts@@ -108,8 +108,7 @@ interface BucketAggregateRow {readonly botsDeleted: number;readonly botsRestored: number;readonly botsTotalCreated: number;- readonly botsTotalDeleted: number;- readonly botsTotalRestored: number;+ readonly botsTotalGone: number;readonly userMessages: number;readonly botReplies: number;readonly failedTurns: number;@@ -285,17 +284,33 @@ export const make = Effect.gen(function* () {sql<BucketAggregateRow>`SELECTCOALESCE(SUM(CASE WHEN e.event_type = 'bot.created' THEN 1 ELSE 0 END), 0) AS "botsCreated",- COALESCE(SUM(CASE WHEN e.event_type = 'bot.archived' THEN 1 ELSE 0 END), 0) AS "botsDeleted",+ COALESCE(SUM(CASE WHEN e.event_type = 'bot.archived'+ OR (e.event_type = 'bot.deleted' AND COALESCE((+ SELECT prior.event_type FROM orchestration_events prior+ WHERE prior.aggregate_kind = 'bot'+ AND prior.stream_id = e.stream_id+ AND prior.event_type IN ('bot.archived', 'bot.restored')+ AND prior.sequence < e.sequence+ ORDER BY prior.sequence DESC LIMIT 1+ ), '') <> 'bot.archived') THEN 1 ELSE 0 END), 0) AS "botsDeleted",COALESCE(SUM(CASE WHEN e.event_type = 'bot.restored' THEN 1 ELSE 0 END), 0) AS "botsRestored",(SELECT COUNT(*) FROM orchestration_eventsWHERE event_type = 'bot.created' AND occurred_at < ${end}AND COALESCE(json_extract(metadata_json, '$.importedHistory'), 0) <> 1) AS "botsTotalCreated",- (SELECT COUNT(*) FROM orchestration_events- WHERE event_type = 'bot.archived' AND occurred_at < ${end}- AND COALESCE(json_extract(metadata_json, '$.importedHistory'), 0) <> 1) AS "botsTotalDeleted",- (SELECT COUNT(*) FROM orchestration_events- WHERE event_type = 'bot.restored' AND occurred_at < ${end}- AND COALESCE(json_extract(metadata_json, '$.importedHistory'), 0) <> 1) AS "botsTotalRestored",+ (SELECT COUNT(*) FROM orchestration_events gone+ WHERE gone.aggregate_kind = 'bot'+ AND gone.event_type IN ('bot.archived', 'bot.deleted')+ AND gone.occurred_at < ${end}+ AND COALESCE(json_extract(gone.metadata_json, '$.importedHistory'), 0) <> 1+ AND NOT EXISTS (+ SELECT 1 FROM orchestration_events newer+ WHERE newer.aggregate_kind = 'bot'+ AND newer.stream_id = gone.stream_id+ AND newer.event_type IN ('bot.archived', 'bot.restored', 'bot.deleted')+ AND newer.occurred_at < ${end}+ AND COALESCE(json_extract(newer.metadata_json, '$.importedHistory'), 0) <> 1+ AND newer.sequence > gone.sequence+ )) AS "botsTotalGone",COALESCE(SUM(CASE WHEN e.event_type = 'thread.message-sent'AND json_extract(e.payload_json, '$.role') = 'user' THEN 1 ELSE 0 END), 0) AS "userMessages",COALESCE(SUM(CASE WHEN e.event_type = 'thread.message-sent'@@ -415,9 +430,7 @@ export const make = Effect.gen(function* () {new_installations: 0,bots_created: clampCounter(row.botsCreated),bots_deleted: clampCounter(row.botsDeleted),- bots_total: clampCounter(- row.botsTotalCreated - row.botsTotalDeleted + row.botsTotalRestored,- ),+ bots_total: clampCounter(row.botsTotalCreated - row.botsTotalGone),user_messages: clampCounter(row.userMessages),bot_replies: clampCounter(row.botReplies),failed_turns: clampCounter(row.failedTurns),diff --git a/apps/server/src/voiceCall/VoiceCallManager.providers.test.ts b/apps/server/src/voiceCall/VoiceCallManager.providers.test.tsindex 5e5edaf2a..65dc003a2 100644--- a/apps/server/src/voiceCall/VoiceCallManager.providers.test.ts+++ b/apps/server/src/voiceCall/VoiceCallManager.providers.test.ts@@ -41,6 +41,7 @@ const repository = {updatedAt: "2026-08-27T00:00:00.000Z",}),),+ deleteById: () => Effect.void,} satisfies ProjectionBotRepositoryShape;const defaults: VoiceAdapters = {test: async () => undefined,diff --git a/apps/server/src/voiceCall/VoiceCallManager.test.ts b/apps/server/src/voiceCall/VoiceCallManager.test.tsindex 0c6c8431a..9b8c59f2f 100644--- a/apps/server/src/voiceCall/VoiceCallManager.test.ts+++ b/apps/server/src/voiceCall/VoiceCallManager.test.ts@@ -1,4 +1,10 @@-import { BotId, VoiceCallError } from "@akeru/contracts";+import {+ BotId,+ CommandId,+ EventId,+ VoiceCallError,+ type OrchestrationEvent,+} from "@akeru/contracts";import * as NodeServices from "@effect/platform-node/NodeServices";import { assert, it } from "@effect/vitest";import { vi } from "vite-plus/test";@@ -6,6 +12,7 @@ import * as Effect from "effect/Effect";import * as Fiber from "effect/Fiber";import * as Layer from "effect/Layer";import * as Option from "effect/Option";+import * as Stream from "effect/Stream";import { ServerConfig } from "../config.ts";import { ServerSettingsService } from "../serverSettings.ts";@@ -13,7 +20,13 @@ import {ProjectionBotRepository,type ProjectionBotRepositoryShape,} from "../persistence/Services/ProjectionBots.ts";-import { defaultSession, parseCodexCliAuth, VoiceCallManager, layer } from "./VoiceCallManager.ts";+import {+ defaultSession,+ hangupDeletedBotCalls,+ parseCodexCliAuth,+ VoiceCallManager,+ layer,+} from "./VoiceCallManager.ts";it("accepts a Codex CLI auth file without auth_mode", () => {assert.deepEqual(@@ -102,6 +115,7 @@ const repository = {getById: ({ botId: requested }) =>Effect.succeed(requested === botId ? Option.some(bot) : Option.none()),listAll: () => Effect.succeed([bot]),+ deleteById: () => Effect.void,} satisfies ProjectionBotRepositoryShape;const TestLayer = layer({@@ -217,6 +231,37 @@ it.layer(TestLayer)("VoiceCallManager", (it) => {}),);+ it.effect("ends the call when its bot is deleted", () =>+ Effect.gen(function* () {+ const manager = yield* VoiceCallManager;+ const call = yield* manager.start({ botId, sdp: "offer-sdp" }, "client-1");+ const botDeleted = (deletedBotId: BotId, sequence: number): OrchestrationEvent => ({+ sequence,+ eventId: EventId.make(`evt-bot-deleted-${sequence}`),+ aggregateKind: "bot",+ aggregateId: deletedBotId,+ type: "bot.deleted",+ occurredAt: now,+ commandId: CommandId.make(`cmd-bot-delete-${sequence}`),+ causationEventId: null,+ correlationId: CommandId.make(`cmd-bot-delete-${sequence}`),+ metadata: {},+ payload: { botId: deletedBotId, deletedAt: now },+ });++ yield* hangupDeletedBotCalls(manager, Stream.make(botDeleted(BotId.make("other-bot"), 1)));+ assert.equal((yield* manager.get).status, "live");++ yield* hangupDeletedBotCalls(manager, Stream.make(botDeleted(botId, 2)));+ assert.deepEqual(yield* manager.get, { status: "idle" });+ const stale = yield* Effect.result(manager.hangup(call.call.callId, "client-1"));+ assert.equal(stale._tag, "Failure");++ const next = yield* manager.start({ botId, sdp: "offer-sdp" }, "client-2");+ yield* manager.hangup(next.call.callId, "client-2");+ }),+ );+it.effect("refuses hangup from a different connection owner", () =>Effect.gen(function* () {const manager = yield* VoiceCallManager;diff --git a/apps/server/src/voiceCall/VoiceCallManager.ts b/apps/server/src/voiceCall/VoiceCallManager.tsindex c65c3c7bc..379374076 100644--- a/apps/server/src/voiceCall/VoiceCallManager.ts+++ b/apps/server/src/voiceCall/VoiceCallManager.ts@@ -21,6 +21,7 @@ import {VOICE_API_PROVIDERS,VoiceTranscribeInput as TranscribeSchema,VoiceSynthesizeInput as SynthesizeSchema,+ type OrchestrationEvent,} from "@akeru/contracts";import * as Context from "effect/Context";import * as DateTime from "effect/DateTime";@@ -28,6 +29,7 @@ import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as Option from "effect/Option";import * as Semaphore from "effect/Semaphore";+import * as Stream from "effect/Stream";import * as Schema from "effect/Schema";import * as ServerConfig from "../config.ts";@@ -261,6 +263,8 @@ export class VoiceCallManager extends Context.Service<ownerId: string,) => Effect.Effect<VoiceCallSnapshot, VoiceCallError>;readonly hangupOwner: (ownerId: string) => Effect.Effect<void>;+ /** Ends the active call when it belongs to `botId`, freeing the single call slot. */+ readonly hangupBot: (botId: BotId) => Effect.Effect<void>;}>()("akeru-bot/voiceCall/VoiceCallManager") {}@@ -762,6 +766,15 @@ const make = (options?: VoiceCallManagerOptions) =>}),);+ const hangupBot = (botId: BotId) =>+ lock.withPermits(1)(+ Effect.sync(() => {+ if (active?.botId !== botId) return;+ active.abortController.abort();+ active = null;+ }),+ );+yield* Effect.addFinalizer(() =>Effect.sync(() => {for (const operation of operations.values()) operation.controller.abort();@@ -784,8 +797,18 @@ const make = (options?: VoiceCallManagerOptions) =>start,hangup,hangupOwner,+ hangupBot,});});+/** Ends a deleted bot's call as its `bot.deleted` event arrives. */+export const hangupDeletedBotCalls = <E, R>(+ voiceCalls: VoiceCallManager["Service"],+ events: Stream.Stream<OrchestrationEvent, E, R>,+) =>+ Stream.runForEach(events, (event) =>+ event.type === "bot.deleted" ? voiceCalls.hangupBot(event.payload.botId) : Effect.void,+ );+export const layer = (options?: VoiceCallManagerOptions) =>Layer.effect(VoiceCallManager, make(options));diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex c261325a9..379c50a6e 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -1116,7 +1116,15 @@ const makeWsRpcLayer = (case "bot.updated":case "bot.archived":case "bot.restored":- return botUpsert(event.payload.botId, event.sequence);+ return botUpsertOrRemove(event.payload.botId, event.sequence);+ case "bot.deleted":+ return Effect.succeed(+ Option.some({+ kind: "bot-removed" as const,+ sequence: event.sequence,+ botId: event.payload.botId,+ }),+ );case "group.created":case "group.renamed":case "group.member-assigned":@@ -1272,41 +1280,47 @@ const makeWsRpcLayer = (),);- const botUpsert = (+ const botUpsertOrRemove = (botId: BotId,sequence: number,): Effect.Effect<Option.Option<OrchestrationShellStreamEvent>, never, never> =>retryShellProjectionRead("bot", botId, projectionBots.getById({ botId })).pipe(Effect.map(Option.flatMap((bot) =>- Option.map(- bot,- (nextBot): OrchestrationShellStreamEvent => ({- kind: "bot-upserted",- sequence,- bot: {- id: nextBot.botId,- name: nextBot.name,- title: nextBot.title,- label: nextBot.label,- description: nextBot.description,- disabledMcpServerIds: nextBot.disabledMcpServerIds,- avatar: nextBot.avatar,- engine: nextBot.engine,- sandbox: nextBot.sandbox,- runtimeMode: nextBot.runtimeMode,- usageCap: nextBot.usageCap,- imageProvider: nextBot.imageProvider,- personalityTone: nextBot.personalityTone ?? BALANCED_BOT_PERSONALITY_TONE,- voiceEnabled: nextBot.voiceEnabled,- channelBindings: channelBindingsForRuntime(nextBot.channelBindings ?? []),- groupId: nextBot.groupId,- archivedAt: nextBot.archivedAt,- createdAt: nextBot.createdAt,- updatedAt: nextBot.updatedAt,- },- }),- ),+ Option.match(bot, {+ onNone: () =>+ Option.some<OrchestrationShellStreamEvent>({+ kind: "bot-removed",+ sequence,+ botId,+ }),+ onSome: (nextBot) =>+ Option.some<OrchestrationShellStreamEvent>({+ kind: "bot-upserted",+ sequence,+ bot: {+ id: nextBot.botId,+ name: nextBot.name,+ title: nextBot.title,+ label: nextBot.label,+ description: nextBot.description,+ disabledMcpServerIds: nextBot.disabledMcpServerIds,+ avatar: nextBot.avatar,+ engine: nextBot.engine,+ sandbox: nextBot.sandbox,+ runtimeMode: nextBot.runtimeMode,+ usageCap: nextBot.usageCap,+ imageProvider: nextBot.imageProvider,+ personalityTone: nextBot.personalityTone ?? BALANCED_BOT_PERSONALITY_TONE,+ voiceEnabled: nextBot.voiceEnabled,+ channelBindings: channelBindingsForRuntime(nextBot.channelBindings ?? []),+ groupId: nextBot.groupId,+ archivedAt: nextBot.archivedAt,+ createdAt: nextBot.createdAt,+ updatedAt: nextBot.updatedAt,+ },+ }),+ }),),),);@@ -4018,6 +4032,11 @@ export const websocketRpcRouteLayer = Layer.unwrap(Effect.gen(function* () {const previewAutomationBroker = yield* PreviewAutomationBroker.PreviewAutomationBroker;const voiceCalls = yield* VoiceCallManager.VoiceCallManager;+ const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;+ // Deleting a bot frees the single call slot it may hold.+ yield* Effect.forkScoped(+ VoiceCallManager.hangupDeletedBotCalls(voiceCalls, orchestrationEngine.streamDomainEvents),+ );const serverSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate;const providerRefreshes: ProviderSubscribeRefreshes = {inFlight: new Set(),diff --git a/apps/web/src/components/roster/BotSettingsPage.tsx b/apps/web/src/components/roster/BotSettingsPage.tsxindex c96c2731e..629b7297d 100644--- a/apps/web/src/components/roster/BotSettingsPage.tsx+++ b/apps/web/src/components/roster/BotSettingsPage.tsx@@ -12,7 +12,7 @@ import {import { driverSupportsDelegation } from "@akeru/shared/delegationProviders";import { Brain02Icon, Edit02Icon, Link02Icon } from "@hugeicons/core-free-icons";import { useBlocker, useCanGoBack, useNavigate } from "@tanstack/react-router";-import { useCallback, useEffect, useState } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import { isElectron } from "../../env";import { useI18n } from "../../i18n";@@ -24,6 +24,7 @@ import { botEnvironment } from "../../state/bots";import { environmentMcpServersAtom } from "../../state/mcpServers";import { useEnvironmentQuery } from "../../state/query";import { serverEnvironment } from "../../state/server";+import { squashAtomCommandFailure } from "@akeru/client-runtime/state/runtime";import { useAtomCommand } from "../../state/use-atom-command";import { SettingsPageContainer, SettingsRow, SettingsSection } from "../settings/settingsLayout";import { SidebarInset } from "../ui/sidebar";@@ -133,7 +134,12 @@ export function BotSettingsPage({ botId }: { readonly botId: string }) {</WorkspaceBreadcrumb></WorkspacePageHeader>{bot ? (- <BotSettingsForm key={bot.id} bot={bot} onSave={onSaveBot} />+ <BotSettingsForm+ key={bot.id}+ bot={bot}+ onSave={onSaveBot}+ onDeleted={navigateBackWithinApp}+ />) : (<div className="flex flex-1 items-center justify-center p-8 text-sm text-muted-foreground">{t("This bot is no longer available.")}@@ -147,13 +153,16 @@ export function BotSettingsPage({ botId }: { readonly botId: string }) {function BotSettingsForm({bot,onSave,+ onDeleted,}: {readonly bot: Bot;readonly onSave: (input: BotProfileUpdate) => Promise<boolean>;+ readonly onDeleted: () => void;}) {const { t } = useI18n();const environmentId = usePrimaryEnvironmentId();const mcpServers = useAtomValue(environmentMcpServersAtom(environmentId ?? NO_ENVIRONMENT));+ const deleteBot = useAtomCommand(botEnvironment.delete, { reportFailure: false });const imageSettings = useEnvironmentSettings(environmentId ?? NO_ENVIRONMENT,(settings) => settings.imageGeneration,@@ -177,9 +186,11 @@ function BotSettingsForm({const [avatarOpen, setAvatarOpen] = useState(false);const [memoryOpen, setMemoryOpen] = useState(false);const [channelsOpen, setChannelsOpen] = useState(false);+ const [deleting, setDeleting] = useState(false);+ const deletedRef = useRef(false);const shouldBlockNavigation = useCallback(async () => {- if (!draft.dirty) return false;+ if (deletedRef.current || !draft.dirty) return false;const confirmation = requestConfirmDialog(t("Discard unsaved bot settings?"), {variant: "destructive",});@@ -199,6 +210,40 @@ function BotSettingsForm({(binding) => binding.status === "connected",).length;+ const onDeleteBot = useCallback(() => {+ if (!environmentId) return;+ const confirmation = requestConfirmDialog(+ t("Delete {name}? Its chats stay in your history. This cannot be undone.", {+ name: bot.name,+ }),+ { variant: "destructive" },+ );+ if (!confirmation) return;+ setDeleting(true);+ void confirmation.then(async (confirmed) => {+ if (!confirmed) {+ setDeleting(false);+ return;+ }+ const result = await deleteBot({+ environmentId,+ input: { botId: BotId.make(bot.id) },+ });+ setDeleting(false);+ if (result._tag === "Failure") {+ const error = squashAtomCommandFailure(result);+ toastManager.add({+ type: "error",+ title: t("Could not delete {name}", { name: bot.name }),+ description: error instanceof Error ? error.message : t("The command failed."),+ });+ return;+ }+ deletedRef.current = true;+ onDeleted();+ });+ }, [bot, environmentId, deleteBot, onDeleted, t]);+return (<><SettingsPageContainer>@@ -574,6 +619,25 @@ function BotSettingsForm({draft.activeEntry ? driverSupportsDelegation(draft.activeEntry.driverKind) : true}/>++ <SettingsSection title={t("Danger")}>+ <SettingsRow+ title={t("Delete bot")}+ description={t("Remove {name} from the roster. Its chats stay in your history.", {+ name: bot.name,+ })}+ control={+ <Button+ variant="destructive"+ size="sm"+ disabled={deleting || !environmentId}+ onClick={onDeleteBot}+ >+ {deleting ? t("Deleting…") : t("Delete")}+ </Button>+ }+ />+ </SettingsSection></SettingsPageContainer><divdiff --git a/docs/user/bots.md b/docs/user/bots.mdindex f480f9cc4..99376da90 100644--- a/docs/user/bots.md+++ b/docs/user/bots.md@@ -226,3 +226,16 @@ to end the call.Open the bot's settings and choose a provider under **Workspace > Image generation**, or keep**Use global default**. This does not change the bot's chat model. See[Image generation](image-generation.md).++## Delete a bot++Open the bot's settings page and select **Delete** under **Danger**, then confirm. On mobile, open+the chat's settings and select **Delete bot** under **Danger**. Deleting removes the bot from the+roster. Its chats stay in your history.++Deleting stops anything the bot is doing. Running replies stop, work it handed to other bots or+received from them is canceled, and a voice call with the bot ends. In a group chat the bot was+answering, the boss picks up the next message.++A bot that leads a group as boss cannot be deleted. Set a new boss for the group first. A bot also+cannot be deleted when its removal would leave a group with fewer than two active bots.diff --git a/packages/client-runtime/src/i18n/__snapshots__/coverage.test.ts.snap b/packages/client-runtime/src/i18n/__snapshots__/coverage.test.ts.snapindex 111ae1156..476832de8 100644--- a/packages/client-runtime/src/i18n/__snapshots__/coverage.test.ts.snap+++ b/packages/client-runtime/src/i18n/__snapshots__/coverage.test.ts.snap@@ -2,7 +2,7 @@exports[`discovered interface message coverage > covers static calls and finite label sources without translating identifiers 1`] = `{- "directMessageCount": 1843,+ "directMessageCount": 1848,"expressions": {"apps/mobile/src/components/DictationControls.tsx": ["announcements[status]);",diff --git a/packages/client-runtime/src/i18n/index.ts b/packages/client-runtime/src/i18n/index.tsindex 890c8dcf9..a5e158df7 100644--- a/packages/client-runtime/src/i18n/index.ts+++ b/packages/client-runtime/src/i18n/index.ts@@ -1183,6 +1183,13 @@ export const englishCatalog = {"Let this bot take subscription voice calls. Voice must also be enabled in Settings.","Disable voice calls for {name}": "Disable voice calls for {name}","Enable voice calls for {name}": "Enable voice calls for {name}",+ Danger: "Danger",+ "Delete bot": "Delete bot",+ "Remove {name} from the roster. Its chats stay in your history.":+ "Remove {name} from the roster. Its chats stay in your history.",+ "Delete {name}? Its chats stay in your history. This cannot be undone.":+ "Delete {name}? Its chats stay in your history. This cannot be undone.",+ "Could not delete {name}": "Could not delete {name}",Model: "Model","The provider and model this bot runs on.": "The provider and model this bot runs on.","No model yet": "No model yet",diff --git a/packages/client-runtime/src/i18n/zh-CN.ts b/packages/client-runtime/src/i18n/zh-CN.tsindex 0ddec9528..ca8a5f9a4 100644--- a/packages/client-runtime/src/i18n/zh-CN.ts+++ b/packages/client-runtime/src/i18n/zh-CN.ts@@ -1133,6 +1133,13 @@ export const zhCNCatalog: TranslationCatalog = {"允许此机器人接听订阅语音通话。还需要在设置中启用语音。","Disable voice calls for {name}": "停用 {name} 的语音通话","Enable voice calls for {name}": "启用 {name} 的语音通话",+ Danger: "危险操作",+ "Delete bot": "删除机器人",+ "Remove {name} from the roster. Its chats stay in your history.":+ "从名单中移除 {name}。其聊天记录会保留在历史中。",+ "Delete {name}? Its chats stay in your history. This cannot be undone.":+ "删除 {name}?其聊天记录会保留在历史中。此操作无法撤销。",+ "Could not delete {name}": "无法删除 {name}",Model: "模型","The provider and model this bot runs on.": "此机器人使用的提供商和模型。","No model yet": "尚未选择模型",diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.tsindex e6317607e..a1e273e05 100644--- a/packages/client-runtime/src/operations/commands.ts+++ b/packages/client-runtime/src/operations/commands.ts@@ -35,6 +35,7 @@ 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 DeleteBotInput = CommandInput<"bot.delete">;export type ConnectChannelInput = CommandInput<"channel.connect">;export type SaveChannelConnectionInput = CommandInput<"channel.connection.save">;export type DeleteChannelConnectionInput = CommandInput<"channel.connection.delete">;@@ -262,6 +263,16 @@ export const restoreBot: (input: RestoreBotInput) => CommandEffect = Effect.fn(});});+export const deleteBot: (input: DeleteBotInput) => CommandEffect = Effect.fn(+ "EnvironmentCommands.deleteBot",+)(function* (input) {+ return yield* dispatch({+ ...input,+ type: "bot.delete",+ commandId: yield* commandId(input),+ });+});+export const createGroup: (input: CreateGroupInput) => CommandEffect = Effect.fn("EnvironmentCommands.createGroup",)(function* (input) {diff --git a/packages/client-runtime/src/state/bots.ts b/packages/client-runtime/src/state/bots.tsindex e9bdee304..fc38d9b61 100644--- a/packages/client-runtime/src/state/bots.ts+++ b/packages/client-runtime/src/state/bots.ts@@ -9,6 +9,7 @@ import {type CreateBotInput,type ConnectChannelInput,type SaveChannelConnectionInput,+ type DeleteBotInput,type DeleteChannelConnectionInput,type AttachChannelInput,type DisconnectChannelInput,@@ -31,6 +32,7 @@ import {createBot,connectChannel,saveChannelConnection,+ deleteBot,deleteChannelConnection,attachChannel,disconnectChannel,@@ -57,6 +59,7 @@ export type {CreateBotInput,ConnectChannelInput,SaveChannelConnectionInput,+ DeleteBotInput,DeleteChannelConnectionInput,AttachChannelInput,DisconnectChannelInput,@@ -115,6 +118,12 @@ export function createBotEnvironmentAtoms<R, E>(scheduler,concurrency: botConcurrency,}),+ delete: createEnvironmentCommand(runtime, {+ label: "environment-data:commands:bot:delete",+ execute: (input: DeleteBotInput) => deleteBot(input),+ scheduler,+ concurrency: botConcurrency,+ }),channels: {saveConnection: createEnvironmentCommand(runtime, {label: "environment-data:commands:channel:connection:save",diff --git a/packages/client-runtime/src/state/shellReducer.test.ts b/packages/client-runtime/src/state/shellReducer.test.tsindex 0674de605..02ddcb7c2 100644--- a/packages/client-runtime/src/state/shellReducer.test.ts+++ b/packages/client-runtime/src/state/shellReducer.test.ts@@ -374,6 +374,23 @@ describe("applyShellStreamEvent", () => {});});+ describe("bot-removed", () => {+ it("removes a bot by id", () => {+ const snapshotWithBot: OrchestrationShellSnapshot = {+ ...baseSnapshot,+ bots: [stubBot],+ };+ const next = applyShellStreamEvent(snapshotWithBot, {+ kind: "bot-removed",+ sequence: 6,+ botId: stubBot.id,+ });++ expect(next.bots).toHaveLength(0);+ expect(next.snapshotSequence).toBe(6);+ });+ });+describe("group-upserted", () => {it("adds and updates a group", () => {const added = applyShellStreamEvent(baseSnapshot, {diff --git a/packages/client-runtime/src/state/shellReducer.ts b/packages/client-runtime/src/state/shellReducer.tsindex 0ae65ee64..8493d3c80 100644--- a/packages/client-runtime/src/state/shellReducer.ts+++ b/packages/client-runtime/src/state/shellReducer.ts@@ -41,6 +41,12 @@ export function applyShellStreamEvent(: Arr.append(snapshot.bots, event.bot);return { ...snapshot, bots, snapshotSequence: event.sequence };}+ case "bot-removed":+ return {+ ...snapshot,+ bots: Arr.filter(snapshot.bots, (bot) => bot.id !== event.botId),+ snapshotSequence: event.sequence,+ };case "group-upserted": {const groups = snapshot.groups.some((group) => group.id === event.group.id)? Arr.map(snapshot.groups, (group) => (group.id === event.group.id ? event.group : group))diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.tsindex 4a9f591c2..e4b9fc340 100644--- a/packages/contracts/src/orchestration.ts+++ b/packages/contracts/src/orchestration.ts@@ -998,6 +998,11 @@ export const OrchestrationShellStreamEvent = Schema.Union([sequence: NonNegativeInt,bot: OrchestrationBot,}),+ Schema.Struct({+ kind: Schema.Literal("bot-removed"),+ sequence: NonNegativeInt,+ botId: BotId,+ }),Schema.Struct({kind: Schema.Literal("group-upserted"),sequence: NonNegativeInt,@@ -1267,6 +1272,12 @@ const BotRestoreCommand = Schema.Struct({botId: BotId,});+const BotDeleteCommand = Schema.Struct({+ type: Schema.Literal("bot.delete"),+ commandId: CommandId,+ botId: BotId,+});+const ChannelConnectCommand = Schema.Union([Schema.Struct({type: Schema.Literal("channel.connect"),@@ -1913,6 +1924,7 @@ const DispatchableClientOrchestrationCommand = Schema.Union([BotUpdateCommand,BotArchiveCommand,BotRestoreCommand,+ BotDeleteCommand,GroupCreateCommand,GroupRenameCommand,GroupDeleteCommand,@@ -1966,6 +1978,7 @@ export const ClientOrchestrationCommand = Schema.Union([ClientBotUpdateCommand,BotArchiveCommand,BotRestoreCommand,+ BotDeleteCommand,ChannelConnectCommand,ChannelConnectionSaveCommand,ChannelConnectionDeleteCommand,@@ -2165,6 +2178,7 @@ export const OrchestrationEventType = Schema.Literals(["bot.updated","bot.archived","bot.restored",+ "bot.deleted","group.created","group.renamed","group.deleted",@@ -2332,6 +2346,11 @@ export const BotRestoredPayload = Schema.Struct({updatedAt: IsoDateTime,});+export const BotDeletedPayload = Schema.Struct({+ botId: BotId,+ deletedAt: IsoDateTime,+});+export const GroupCreatedPayload = Schema.Struct({groupId: GroupId,name: TrimmedNonEmptyString,@@ -2742,6 +2761,11 @@ export const OrchestrationEvent = Schema.Union([type: Schema.Literal("bot.restored"),payload: BotRestoredPayload,}),+ Schema.Struct({+ ...EventBaseFields,+ type: Schema.Literal("bot.deleted"),+ payload: BotDeletedPayload,+ }),Schema.Struct({...EventBaseFields,type: Schema.Literal("group.created"),