Open-source AI coworkers that each get a computer of their own: a browser, files and tools, with every action decided before it happens and recorded after. Bring any AG-UI agent.
The sidebar is Bots and Skills (#765)
Guido Vizosoa4dce8c47c72
diff --git a/.env.example b/.env.exampleindex 478ddab2..819fadd2 100644--- a/.env.example+++ b/.env.example@@ -379,7 +379,7 @@ MANAGED_AGENT_TOKEN=# The second Bot in the box runs on http://localhost:4201/ag-ui, on a framework rather than# proof of concept, and is reached the same way: point MANAGED_AGENT_AG_UI_URL at it, or add it as a-# Bot of its own in the tenant package or at /agents.+# Bot of its own in the tenant package or at /bots.# Which model the Bots use. BOT_MODEL is the framework Bot's: it defaults to gpt-5.5 and switches# to the Responses API by itself for a model that needs it — a 5.6 tier does, because 5.6 rejectsdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4c5d2bfe..74435ded 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,34 @@ Newest first. `Unreleased` is what is on `main` and not yet tagged.such record for up to ten minutes after the upgrade, and calls they make to a Shared app in thatwindow are refused.+### One Bots list, and one page per Bot++Agents, Team Bots and Bots were three lists of the same Bots. `/bots` is now the only one — pinned,+yours, shared with you, and the ones you hid — with **New Bot** at the top. A Bot's page holds+everything about it: its routines, its skills and what it may reach, who it is shared with, and its+name, role and connection. Where updates reach you and your answers to shared Bots moved to+Settings. `/agents` and `/team-bots` still work and open the new places. A Team Bot an administrator+assigns to a group is pinned at the top of its members' Bots list instead of sitting in their+sidebar.++The sidebar no longer lists each Bot that needs you. A badge on Bots counts the questions, approvals+and stalled hand-offs waiting across all of them, and Bots lists those Bots first, under Needs you.+Browser notifications when a Bot starts needing you are unchanged.++The sidebar is now Bots and Skills. Each Bot's page holds what that Bot is waiting on you for, its+suggested next steps, its responsibilities, where it reaches you, its memory sources and background+research, and its approval rules. `/approvals`, `/memory`, `/reachability` and `/responsibilities`+still work and open the new places. Messages from Bots, Slack and Teams that named those pages now+point at the Bot's page.++A group conversation is started like any other: put two or more Bots in the To: field of a new+conversation, in the order they should answer. The separate group button and `/group/new` screen+are gone; `/group/new` opens the new-conversation screen.++Settings now also holds whether your Bots ask before acting, rules for every Bot, your memories, your+devices and recent deliveries, and GitHub event sources. Team approval settings and shared account+requests moved to Admin → Approvals.+### An app's account can belong to the teamAn administrator can make a Composio app Shared: one account, connected once, that every Bot granteddiff --git a/README.md b/README.mdindex 6072d167..440f9b4e 100644--- a/README.md+++ b/README.md@@ -46,7 +46,7 @@ your own machine.An agent platform that runs inside your own infrastructure. Docker Compose brings up every part of it, the data sits in your PostgreSQL, and the model is yours to choose: no model ships in the box, and an administrator supplies the credential, which is encrypted at rest and never logged.-A deployment starts with two coworkers, and they are configuration rather than code: **General Assistant** for everyday work and **Knowledge** for company questions. A **Risk Analyst** joins them once its endpoint is configured, and ten more wait in `examples/fintech/catalog/`, each doing one job — reading an expense claim against the policy as written, turning a meeting note into the follow-ups actually in it, drafting release notes from what shipped, triaging a ticket, answering a new starter from the handbook, writing a brief that names what it could not find, writing up an interview, handing an on-call shift over, assembling what is known before a renewal, and grouping customer feedback into themes it can cite. Copy one into `examples/fintech/agents/` to add it, write your own there or in `agents.yaml`, or make one from `/agents` in the UI.+A deployment starts with two coworkers, and they are configuration rather than code: **General Assistant** for everyday work and **Knowledge** for company questions. A **Risk Analyst** joins them once its endpoint is configured, and ten more wait in `examples/fintech/catalog/`, each doing one job — reading an expense claim against the policy as written, turning a meeting note into the follow-ups actually in it, drafting release notes from what shipped, triaging a ticket, answering a new starter from the handbook, writing a brief that names what it could not find, writing up an interview, handing an on-call shift over, assembling what is known before a renewal, and grouping customer feedback into themes it can cite. Copy one into `examples/fintech/agents/` to add it, write your own there or in `agents.yaml`, or make one from `/bots` in the UI.Anything a Bot does to a computer, a file, an MCP server or a component goes through one gateway that decides and records it. That is the difference between an agent that can use your tools and an agent you can let near them.@@ -175,29 +175,32 @@ Leave `EMBEDDED_POSTGRES` off and set `DATABASE_URL` to point at a database you- Open `/bot` and ask: `Open news.ycombinator.com and tell me the top story.`- Ask the Bot to fill out <https://httpbin.org/forms/post>, then inspect `/admin/audit`.- Open `/admin/boundaries`, add a deny rule or preset, and retry the same browser action.-- Create a coworker from `/agents`, give it a standing role, and start a channel with it.+- Create a Bot from `/bots`, give it a standing role, and start a channel with it.## Main surfaces| Route | Purpose || --------------------------- | ------------------------------------------------------------------ || `/` | Start and browse channels. |-| `/agents` | Create, edit, duplicate, pin, hide, delete, and launch coworkers. |+| `/channel/new` | Start a conversation; two or more Bots in To: start a group. || `/channel/:id` | Converse with one coworker, watch its screen, and see what it ran. |-| `/group/new` | Start one conversation with two or more Bots. || `/bot` | Direct chat with a Bot; `?agent=<id>` selects one. |-| `/bots` | What each of your Bots is doing, what it needs from you, and whether it is paused. |-| `/team-bots` | Bots your teammates published, and the ones you share. |-| `/responsibilities` | Give a Bot a lasting goal, follow its progress, and decide when it should work. |-| `/reachability` | Continue a conversation in Slack, Microsoft Teams, by text message, or on your phone. |-| `/memory` | Review what your Bots remember, and choose which connected apps can contribute facts. |-| `/approvals` | Choose what your Bots may do, and review actions waiting for you. |+| `/bots` | Every Bot you can reach; create one, and open its page to change it. |+| `/bots/:id` | One Bot: what it waits on you for, what it is doing, and how it is set up. |+| `/bots/:id/responsibilities` | Give the Bot a lasting goal, follow its progress, and decide when it should work. |+| `/bots/:id/reach` | Continue a conversation with the Bot in Slack, Microsoft Teams, or by text message. |+| `/bots/:id/memory` | Which connected apps feed the Bot facts, and its background research. |+| `/bots/:id/approvals` | What the Bot may do without asking you first. || `/skills` | Create and enable personal skills. || `/routines` | See the routines that are standing, and stop one. || `/settings` | User preferences. || `/settings/connected-accounts` | Connect your apps so your Bots can work with them. || `/settings/passwords` | Logins you saved when signing a Bot in to a website. |+| `/settings/notifications` | Where updates go, your devices, and recent deliveries. |+| `/settings/approvals` | Whether your Bots ask before acting, and rules for every Bot. |+| `/settings/memory` | What your Bots remember about you, and facts you tell them. || `/admin/credentials` | Store write-only encrypted credentials. |+| `/admin/approvals` | Team approval settings, team rules, and shared account requests. || `/admin/computers` | View, stop, and reset Bot computers. || `/admin/boundaries` | Configure browser/file/MCP action policy. || `/admin/components` | Publish components and govern which Bots may use them. |@@ -235,7 +238,7 @@ Leave `EMBEDDED_POSTGRES` off and set `DATABASE_URL` to point at a database youAny AG-UI endpoint can be a Bot.-From `/agents`, create a coworker with:+From `/bots`, create a Bot with:- name, title, and role description;- private or public visibility;diff --git a/app/src/components/admin/admin-sidebar.tsx b/app/src/components/admin/admin-sidebar.tsxindex ed20820a..0217dc37 100644--- a/app/src/components/admin/admin-sidebar.tsx+++ b/app/src/components/admin/admin-sidebar.tsx@@ -1,6 +1,7 @@import {IconArrowLeft,IconBuildingBank,+ IconChecks,IconCode,IconDeviceDesktop,IconFileText,@@ -56,6 +57,11 @@ const GROUPS: {icon: IconShieldCheck,linkOptions: { to: "/admin/boundaries" },},+ {+ title: "Approvals",+ icon: IconChecks,+ linkOptions: { to: "/admin/approvals" },+ },{title: "Computers",icon: IconDeviceDesktop,diff --git a/app/src/components/agents/agent-card.tsx b/app/src/components/agents/agent-card.tsxindex e14bbf3e..74f2a821 100644--- a/app/src/components/agents/agent-card.tsx+++ b/app/src/components/agents/agent-card.tsx@@ -55,7 +55,7 @@ export function AgentCard({size="xs"aria-label={`View details for ${agent.name}`}className="-ml-2 text-muted-foreground after:absolute after:inset-0"- render={<Link to="/agents" search={{ agent: agent.id }} />}+ render={<Link params={{ agentId: agent.id }} to="/bots/$agentId" />}>Details</Button>diff --git a/app/src/components/agents/agent-dialog.tsx b/app/src/components/agents/agent-dialog.tsxdeleted file mode 100644index 9b4f76b1..00000000--- a/app/src/components/agents/agent-dialog.tsx+++ /dev/null@@ -1,864 +0,0 @@-import {- IconAdjustments,- IconArrowsExchange,- IconClock,- IconPencil,- IconPlugConnected,- IconPuzzle,- IconUser,-} from "@tabler/icons-react";-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";-import { useNavigate } from "@tanstack/react-router";-import { useState } from "react";-import type { ZodType } from "zod";-import { AbstractAvatar } from "@/components/agents/abstract-avatar";-import { CallbackTokenPanel } from "@/components/agents/callback-token-panel";-import { HandoffPanel } from "@/components/agents/handoff-panel";-import { RoutinesList } from "@/components/routines/routines-list";-import { Button } from "@/components/ui/button";-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from "@/components/ui/dialog";-import {- Empty,- EmptyDescription,- EmptyHeader,- EmptyTitle,-} from "@/components/ui/empty";-import { Input } from "@/components/ui/input";-import {- Item,- ItemActions,- ItemContent,- ItemDescription,- ItemTitle,-} from "@/components/ui/item";-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from "@/components/ui/select";-import {- Sidebar,- SidebarContent,- SidebarGroup,- SidebarGroupContent,- SidebarHeader,- SidebarMenu,- SidebarMenuButton,- SidebarMenuItem,- SidebarProvider,-} from "@/components/ui/sidebar";-import { Skeleton } from "@/components/ui/skeleton";-import { Textarea } from "@/components/ui/textarea";-import {- type AgentFormValues,- agentFormSchema,- agentInputFrom,-} from "@/lib/agents/form";-import {- deleteAgentMutationOptions,- duplicateAgentMutationOptions,- setAgentHiddenMutationOptions,- setAgentPinnedMutationOptions,- updateAgentMutationOptions,-} from "@/lib/agents/mutations";-import { type AgentProfile, agentQueryOptions } from "@/lib/agents/queries";-import { isComposing } from "@/lib/composing";-import { agentPluginsQueryOptions } from "@/lib/plugins/queries";-import { readToolName } from "@/lib/plugins/tool-name";--/**- * A coworker, in a dialog with its own sidebar.- *- * The agents screen used to slide this in as a side panel; a profile carries enough distinct- * concerns — who it is, where it runs, what it may hand work to, and what can be done to it — that- * a single scrolling column buried the later ones. Each concern is a section here, and the sidebar- * is the map.- */-export function AgentDialog({- agentId,- open,- onClose,-}: {- /** Which coworker to show. Null renders nothing but keeps the dialog mounted for its exit. */- agentId: string | null;- open: boolean;- onClose: () => void;-}) {- return (- <Dialog onOpenChange={(next) => !next && onClose()} open={open}>- {/* p-0/overflow-hidden hands the popup's rounding to the sidebar; wider than the default- dialog because it holds a two-pane layout, which is the stated reason to deviate. */}- {/* Tall enough that General's rows and its Delete sit on screen together; the popup's own- max-h-[85svh] still caps it on a short display, where the main pane scrolls. */}- <DialogContent className="overflow-hidden p-0 md:max-h-[680px] md:max-w-[700px] lg:max-w-[800px]">- {/* Keyed by coworker so the section and edit state never carry over from another one. */}- {agentId ? <AgentDialogBody agentId={agentId} key={agentId} /> : null}- </DialogContent>- </Dialog>- );-}--const SECTIONS = [- { id: "general", name: "General", icon: IconUser },- { id: "access", name: "Access", icon: IconPuzzle },- { id: "connection", name: "Connection", icon: IconPlugConnected },- { id: "handoff", name: "Handoff", icon: IconArrowsExchange },- { id: "routines", name: "Routines", icon: IconClock },- { id: "manage", name: "Manage", icon: IconAdjustments },-] as const;--type SectionId = (typeof SECTIONS)[number]["id"];--function AgentDialogBody({ agentId }: { agentId: string }) {- const [section, setSection] = useState<SectionId>("general");- const agent = useQuery(agentQueryOptions(agentId));-- if (agent.isPending) {- return (- <div className="flex h-[640px] max-h-[80svh] flex-col gap-4 p-6">- <Skeleton className="h-6 w-44" />- <Skeleton className="h-4 w-full" />- <Skeleton className="h-4 w-2/3" />- </div>- );- }- if (agent.error || !agent.data) {- return (- <p className="p-6 text-sm text-destructive" role="alert">- Could not load this coworker.- </p>- );- }- const profile = agent.data;- const active = SECTIONS.find((candidate) => candidate.id === section);-- return (- <>- <DialogTitle className="sr-only">{profile.name}</DialogTitle>- {/* min-h-full overrides the provider's own min-h-svh, which is sized for a page. */}- <SidebarProvider className="min-h-full items-start">- <Sidebar className="hidden md:flex" collapsible="none">- {/* Who this dialog is about, said once here rather than repeated per section. */}- <SidebarHeader className="flex-row items-center gap-3 p-4">- <AbstractAvatar- name={profile.name}- seed={profile.avatarSeed}- size={36}- />- <div className="flex min-w-0 flex-col">- <span className="truncate text-sm font-medium">- {profile.name}- </span>- <span className="truncate text-xs text-muted-foreground">- {profile.title}- </span>- </div>- </SidebarHeader>- <SidebarContent className="mt-2">- <SidebarGroup>- <SidebarGroupContent>- <SidebarMenu className="gap-px">- {SECTIONS.map((item) => (- <SidebarMenuItem key={item.id}>- <SidebarMenuButton- isActive={item.id === section}- onClick={() => setSection(item.id)}- >- <item.icon />- <span>{item.name}</span>- </SidebarMenuButton>- </SidebarMenuItem>- ))}- </SidebarMenu>- </SidebarGroupContent>- </SidebarGroup>- </SidebarContent>- </Sidebar>- <main className="flex h-[640px] max-h-[80svh] flex-1 flex-col overflow-hidden">- {/*- * The sidebar hides below md, and without this strip that left the sections unreachable- * on a phone: the dialog opened on General and nothing could leave it. A scrollable row- * of the same sections, shown only where the sidebar is not. The identity the sidebar- * header carries rides along, with room kept for the popup's close button.- */}- <div className="flex shrink-0 flex-col gap-2 border-b border-border p-3 pr-12 md:hidden">- <div className="flex items-center gap-2">- <AbstractAvatar- name={profile.name}- seed={profile.avatarSeed}- size={28}- />- <span className="truncate text-sm font-medium">- {profile.name}- </span>- </div>- <div className="flex gap-1 overflow-x-auto">- {SECTIONS.map((item) => (- <Button- className="shrink-0"- key={item.id}- onClick={() => setSection(item.id)}- size="sm"- variant={item.id === section ? "secondary" : "ghost"}- >- <item.icon />- {item.name}- </Button>- ))}- </div>- </div>- <header className="flex h-14 shrink-0 items-center gap-2 px-6">- <h2 className="text-sm font-medium">{active?.name}</h2>- </header>- <div className="flex flex-1 flex-col gap-6 overflow-y-auto px-6 pb-6">- {section === "general" ? (- <GeneralSection agentId={agentId} profile={profile} />- ) : section === "access" ? (- <AccessSection agentId={agentId} />- ) : section === "connection" ? (- <ConnectionSection agentId={agentId} profile={profile} />- ) : section === "handoff" ? (- <HandoffPanel agentId={agentId} />- ) : section === "routines" ? (- <RoutinesList agentId={agentId} embedded />- ) : (- <ManageSection agentId={agentId} profile={profile} />- )}- </div>- </main>- </SidebarProvider>- </>- );-}--function GeneralSection({- agentId,- profile,-}: {- agentId: string;- profile: AgentProfile;-}) {- const queryClient = useQueryClient();- const navigate = useNavigate();- const updateAgent = useMutation(updateAgentMutationOptions(queryClient));-- /*- * One field at a time, over the whole update endpoint: the API takes the full profile, so the- * unchanged fields ride along as they are on screen. The empty key means "keep the current one".- */- const save = (patch: Partial<AgentFormValues>) =>- updateAgent.mutateAsync({- agentId,- input: agentInputFrom({- name: profile.name,- title: profile.title,- roleDescription: profile.roleDescription,- visibility: profile.visibility,- /*- * Not a built-in coworker's endpoint. That is the managed Bot's own address, which nobody- * typed, and the route checks any endpoint it is sent as one somebody did: on a deployment- * whose Bot is on localhost it refused every edit. Empty leaves the stored one where it is.- */- endpoint: profile.builtIn ? "" : (profile.endpoint ?? ""),- authValue: "",- ...patch,- }),- });-- return (- <>- {/* Each stands on its own — muted, not bg-card, which is invisible against a popup — and- each edits in place: the field somebody wants to change is the only one that opens. */}- <div className="flex flex-col gap-2">- <EditableTextItem- canManage={profile.canManage}- label="Name"- onSave={(name) => save({ name })}- schema={agentFormSchema.shape.name}- value={profile.name}- />- <EditableTextItem- canManage={profile.canManage}- label="Title"- onSave={(title) => save({ title })}- schema={agentFormSchema.shape.title}- value={profile.title}- />- <EditableTextItem- canManage={profile.canManage}- label="Role"- multiline- onSave={(roleDescription) => save({ roleDescription })}- schema={agentFormSchema.shape.roleDescription}- value={profile.roleDescription}- />- <VisibilityItem- canManage={profile.canManage}- onSave={(visibility) => save({ visibility })}- value={profile.visibility}- />- {profile.systemOwned ? (- <Item variant="muted">- <ItemContent>- <ItemTitle>System owned</ItemTitle>- <ItemDescription>- Ships with this deployment rather than belonging to a person.- </ItemDescription>- </ItemContent>- </Item>- ) : null}- </div>-- <Item variant="muted">- <ItemContent>- <ItemTitle>Start channel</ItemTitle>- <ItemDescription>- Open a new channel with this coworker.- </ItemDescription>- </ItemContent>- <ItemActions>- <Button- onClick={() =>- void navigate({- search: { agent: agentId },- to: "/channel/new",- })- }- size="sm"- >- Start- </Button>- </ItemActions>- </Item>- </>- );-}--/**- * One fact about the coworker, edited in place.- *- * Only the field somebody wants to change opens: Edit swaps this item — and this item alone — for- * its input, validated against the same limits the server enforces, and Save writes just it back.- */-function EditableTextItem({- label,- value,- canManage,- multiline = false,- schema,- onSave,-}: {- label: string;- value: string;- canManage: boolean;- /** A textarea rather than an input, for the field that is a paragraph. */- multiline?: boolean;- /** The field's slice of the shared form contract, so errors match the server's limits. */- schema: ZodType<string>;- onSave: (draft: string) => Promise<unknown>;-}) {- const [editing, setEditing] = useState(false);- const [draft, setDraft] = useState(value);- const [saving, setSaving] = useState(false);- const [error, setError] = useState<string | null>(null);-- const close = () => {- setEditing(false);- setError(null);- };- const submit = async () => {- const parsed = schema.safeParse(draft);- if (!parsed.success) {- setError(parsed.error.issues[0]?.message ?? "That value does not fit.");- return;- }- setSaving(true);- try {- await onSave(parsed.data);- close();- } catch (failure) {- setError(failure instanceof Error ? failure.message : "Could not save.");- } finally {- setSaving(false);- }- };-- if (!editing) {- return (- <Item variant="muted">- <ItemContent>- <ItemTitle>{label}</ItemTitle>- </ItemContent>- <ItemActions className="min-w-0">- <span- className={`text-right text-sm text-muted-foreground ${- multiline ? "line-clamp-2 whitespace-pre-wrap" : "truncate"- }`}- >- {value}- </span>- {canManage ? (- <Button- aria-label={`Edit ${label.toLowerCase()}`}- onClick={() => {- setDraft(value);- setEditing(true);- }}- size="icon-sm"- variant="ghost"- >- <IconPencil />- </Button>- ) : null}- </ItemActions>- </Item>- );- }-- return (- <Item variant="muted">- <ItemContent>- <ItemTitle>{label}</ItemTitle>- {multiline ? (- <Textarea- autoFocus- onChange={(event) => setDraft(event.target.value)}- rows={4}- value={draft}- />- ) : (- <Input- autoFocus- onChange={(event) => setDraft(event.target.value)}- onKeyDown={(event) => {- // Not the Enter that confirms a composed character: that one would save the value- // before the person has finished typing it.- if (event.key === "Enter" && !isComposing(event)) {- event.preventDefault();- void submit();- }- }}- value={draft}- />- )}- {error ? (- <p className="text-sm text-destructive" role="alert">- {error}- </p>- ) : null}- <div className="mt-1 flex gap-2">- <Button disabled={saving} onClick={() => void submit()} size="sm">- {saving ? "Saving…" : "Save"}- </Button>- <Button disabled={saving} onClick={close} size="sm" variant="outline">- Cancel- </Button>- </div>- </ItemContent>- </Item>- );-}--/**- * Visibility is two named choices, so it edits as a select that writes on pick — no open state and- * no Save, because there is no draft worth holding: the pick is the whole of the change.- */-function VisibilityItem({- value,- canManage,- onSave,-}: {- value: AgentProfile["visibility"];- canManage: boolean;- onSave: (visibility: AgentProfile["visibility"]) => Promise<unknown>;-}) {- const [saving, setSaving] = useState(false);- const [error, setError] = useState<string | null>(null);-- return (- <Item variant="muted">- <ItemContent>- <ItemTitle>Visibility</ItemTitle>- <ItemDescription>- {value === "private"- ? "Only you can see it and start channels with it."- : "Everyone in the deployment can find and use it."}- </ItemDescription>- {error ? (- <p className="text-sm text-destructive" role="alert">- {error}- </p>- ) : null}- </ItemContent>- <ItemActions>- {canManage ? (- <Select- disabled={saving}- // The label map, so the closed trigger says "Private" rather than the raw value.- items={{ private: "Private", public: "Public" }}- onValueChange={async (next) => {- if (next === value) return;- setError(null);- setSaving(true);- try {- await onSave(next as AgentProfile["visibility"]);- } catch (failure) {- setError(- failure instanceof Error- ? failure.message- : "Could not save.",- );- } finally {- setSaving(false);- }- }}- value={value}- >- <SelectTrigger className="w-28">- <SelectValue />- </SelectTrigger>- <SelectContent>- <SelectItem value="private">Private</SelectItem>- <SelectItem value="public">Public</SelectItem>- </SelectContent>- </Select>- ) : (- <span className="text-sm text-muted-foreground">- {value === "private" ? "Private" : "Public"}- </span>- )}- </ItemActions>- </Item>- );-}--/** "google-drive" as "Google Drive": the connector key, said the way a person would. */-function connectorName(key: string): string {- return key- .split(/[-_]/)- .filter(Boolean)- .map((word) => word[0]?.toUpperCase() + word.slice(1))- .join(" ");-}--/**- * What this coworker may reach when it works: its granted connectors, one row each, and its skills.- *- * Read from the same snapshot the runtime offers the Bot, so this shows what a run would actually- * hold rather than a second opinion. Read-only on purpose — granting is an administrator's, made on- * the Plugins screens, and a row of switches here would be a second place for the same decision.- */-function AccessSection({ agentId }: { agentId: string }) {- const plugins = useQuery(agentPluginsQueryOptions(agentId));-- if (plugins.isPending) return null;- if (plugins.error || !plugins.data) {- return (- <p className="text-sm text-destructive" role="alert">- What this coworker may reach could not be loaded.- </p>- );- }-- /* One row per connector, carrying what a person recognises: the tools' names, not their count. */- const connectors = new Map<string, string[]>();- for (const tool of plugins.data.tools) {- const key = tool.ref.split("/")[0] ?? tool.ref;- let label = readToolName(tool.toolName).label;- /*- * Vendors prefix every tool with their own name — "Notion create pages" — which next to a row- * already titled Notion reads as a stutter. Stripped only as a leading word, and re-cased, so- * "Notion search" becomes "Search" while "Search notion pages" is left alone.- */- const prefix = `${key.toLowerCase()} `;- if (label.toLowerCase().startsWith(prefix)) {- const rest = label.slice(prefix.length);- label = rest ? rest[0]?.toUpperCase() + rest.slice(1) : label;- }- const labels = connectors.get(key) ?? [];- labels.push(label);- connectors.set(key, labels);- }- const skills = plugins.data.skills;-- if (connectors.size === 0 && skills.length === 0) {- return (- <Empty className="h-[180px] border border-dashed">- <EmptyHeader>- <EmptyTitle className="text-muted-foreground">- Nothing granted yet- </EmptyTitle>- <EmptyDescription>- An administrator grants connectors and skills from the Plugins- screens. Until then this coworker can converse, and nothing more.- </EmptyDescription>- </EmptyHeader>- </Empty>- );- }-- return (- <>- <p className="text-sm text-muted-foreground">- What this coworker may reach when it works. Granted by an administrator- on the Plugins screens; anything not listed is refused when called.- </p>- <div className="flex flex-col gap-2">- {[...connectors.entries()].map(([key, labels]) => (- <Item key={key} variant="muted">- <ItemContent>- <ItemTitle>{connectorName(key)}</ItemTitle>- <ItemDescription>- {labels.slice(0, 4).join(", ")}- {labels.length > 4 ? ` and ${labels.length - 4} more` : ""}- </ItemDescription>- </ItemContent>- <ItemActions>- <span className="text-sm text-muted-foreground tabular-nums">- {labels.length} {labels.length === 1 ? "tool" : "tools"}- </span>- </ItemActions>- </Item>- ))}- {skills.map((skill) => (- <Item key={skill.slug} variant="muted">- <ItemContent>- <ItemTitle>{skill.title}</ItemTitle>- <ItemDescription>{skill.summary}</ItemDescription>- </ItemContent>- <ItemActions>- <span className="text-sm text-muted-foreground">Skill</span>- </ItemActions>- </Item>- ))}- </div>- </>- );-}--function ConnectionSection({- agentId,- profile,-}: {- agentId: string;- profile: AgentProfile;-}) {- /*- * A built-in coworker is done the moment it exists: it runs on the deployment's own Bot, whose- * process already holds the deployment's tool credential, so its tool calls authenticate with no- * setup. Showing it the endpoint and the callback-token panel told the person the opposite —- * an internal address they never typed, and a credential they were never supposed to need.- */- if (!profile.endpoint || profile.builtIn) {- return (- <p className="text-sm text-muted-foreground">- Runs on this deployment's own Bot. Nothing to connect and nothing to- authenticate: its tool calls are covered by the deployment's own- credential.- </p>- );- }- return (- <>- <section className="grid gap-2">- <h2 className="text-xs font-medium uppercase tracking-wide text-muted-foreground">- Endpoint- </h2>- <p className="break-all font-mono text-sm">{profile.endpoint}</p>- </section>- {profile.canManage ? (- <CallbackTokenPanel- agentId={agentId}- hasToken={profile.hasCallbackToken}- />- ) : null}- </>- );-}--function ManageSection({- agentId,- profile,-}: {- agentId: string;- profile: AgentProfile;-}) {- const queryClient = useQueryClient();- const navigate = useNavigate();- const [confirmingDelete, setConfirmingDelete] = useState(false);- const setPinned = useMutation(setAgentPinnedMutationOptions(queryClient));- const setHidden = useMutation(setAgentHiddenMutationOptions(queryClient));- const duplicateAgent = useMutation(- duplicateAgentMutationOptions(queryClient),- );- const deleteAgent = useMutation(deleteAgentMutationOptions(queryClient));- const actionError =- setPinned.error ?? setHidden.error ?? duplicateAgent.error;-- return (- <>- {/* The same gap the General items keep, so the two screens read as one list style. */}- <div className="flex flex-col gap-2">- <Item variant="muted">- <ItemContent>- <ItemTitle>{profile.pinned ? "Pinned" : "Pin"}</ItemTitle>- <ItemDescription>- {profile.pinned- ? "At the top of your agents list. This changes nothing for anyone else."- : "Keep it at the top of your agents list. This changes nothing for anyone else."}- </ItemDescription>- </ItemContent>- <ItemActions>- <Button- disabled={setPinned.isPending}- onClick={() =>- setPinned.mutate({ agentId, pinned: !profile.pinned })- }- size="sm"- variant="outline"- >- {setPinned.isPending- ? profile.pinned- ? "Unpinning…"- : "Pinning…"- : profile.pinned- ? "Unpin"- : "Pin"}- </Button>- </ItemActions>- </Item>-- <Item variant="muted">- <ItemContent>- <ItemTitle>{profile.hidden ? "Hidden" : "Hide"}</ItemTitle>- <ItemDescription>- {profile.hidden- ? "Hidden from your agents list. This changes nothing for anyone else."- : "Take it off your agents list. This changes nothing for anyone else."}- </ItemDescription>- </ItemContent>- <ItemActions>- <Button- disabled={setHidden.isPending}- onClick={async () => {- await setHidden.mutateAsync({- agentId,- hidden: !profile.hidden,- });- if (!profile.hidden)- await navigate({ search: {}, to: "/agents" });- }}- size="sm"- variant="outline"- >- {setHidden.isPending- ? profile.hidden- ? "Unhiding…"- : "Hiding…"- : profile.hidden- ? "Unhide"- : "Hide"}- </Button>- </ItemActions>- </Item>-- <Item variant="muted">- <ItemContent>- <ItemTitle>Duplicate</ItemTitle>- <ItemDescription>- A copy of your own, with no key and no channels.- </ItemDescription>- </ItemContent>- <ItemActions>- <Button- disabled={duplicateAgent.isPending}- onClick={async () => {- const copy = await duplicateAgent.mutateAsync(agentId);- await navigate({ search: { agent: copy.id }, to: "/agents" });- }}- size="sm"- variant="outline"- >- {duplicateAgent.isPending ? "Duplicating…" : "Duplicate"}- </Button>- </ItemActions>- </Item>-- {profile.canManage ? (- <Item variant="muted">- <ItemContent>- <ItemTitle>Delete</ItemTitle>- <ItemDescription>This cannot be undone.</ItemDescription>- </ItemContent>- <ItemActions>- <Button- onClick={() => setConfirmingDelete(true)}- size="sm"- variant="destructive"- >- Delete- </Button>- </ItemActions>- </Item>- ) : null}- </div>-- {actionError ? (- <p className="text-sm text-destructive" role="alert">- {actionError.message}- </p>- ) : null}-- {/* Stacked over the agent dialog: destroying something deserves its own moment, and the- question keeps the name in it so the wrong tab cannot delete the wrong coworker. */}- <Dialog- onOpenChange={(next) => !next && setConfirmingDelete(false)}- open={confirmingDelete}- >- <DialogContent- className="max-w-sm"- overlayClassName="bg-black/20 supports-backdrop-filter:backdrop-blur-sm"- >- <DialogHeader>- <DialogTitle>Delete {profile.name}?</DialogTitle>- <DialogDescription>This cannot be undone.</DialogDescription>- </DialogHeader>- {deleteAgent.error ? (- <p className="mt-4 text-sm text-destructive" role="alert">- {deleteAgent.error.message}- </p>- ) : null}- <DialogFooter className="mt-4">- <Button- onClick={() => setConfirmingDelete(false)}- size="sm"- variant="outline"- >- Cancel- </Button>- <Button- disabled={deleteAgent.isPending}- onClick={async () => {- await deleteAgent.mutateAsync(agentId);- await navigate({ search: {}, to: "/agents" });- }}- size="sm"- variant="destructive"- >- {deleteAgent.isPending ? "Deleting…" : "Delete"}- </Button>- </DialogFooter>- </DialogContent>- </Dialog>- </>- );-}diff --git a/app/src/components/agents/agent-profile.tsx b/app/src/components/agents/agent-profile.tsxindex 311aa1d9..5065173c 100644--- a/app/src/components/agents/agent-profile.tsx+++ b/app/src/components/agents/agent-profile.tsx@@ -1,8 +1,7 @@import { useQuery } from "@tanstack/react-query";-import { useNavigate } from "@tanstack/react-router";-import { type ReactNode, useState } from "react";+import { Link, useNavigate } from "@tanstack/react-router";+import type { ReactNode } from "react";import { AbstractAvatar } from "@/components/agents/abstract-avatar";-import { AgentDialog } from "@/components/agents/agent-dialog";import { Button } from "@/components/ui/button";import { Skeleton } from "@/components/ui/skeleton";import { agentQueryOptions } from "@/lib/agents/queries";@@ -49,7 +48,6 @@ function ProfileSkeleton() {*/export function AgentProfile({ agentId }: { agentId: string }) {/** The full dialog, opened over the chat rather than navigating away from it. */- const [managing, setManaging] = useState(false);const navigate = useNavigate();const agent = useQuery(agentQueryOptions(agentId));@@ -109,18 +107,14 @@ export function AgentProfile({ agentId }: { agentId: string }) {</Button><ButtonclassName="w-full text-sm!"- onClick={() => setManaging(true)}+ render={(props) => (+ <Link {...props} params={{ agentId }} to="/bots/$agentId" />+ )}variant="outline">- Manage coworker+ Open {profile.name}</Button></div>-- <AgentDialog- agentId={agentId}- onClose={() => setManaging(false)}- open={managing}- /></div>);}diff --git a/app/src/components/agents/handoff-panel.tsx b/app/src/components/agents/handoff-panel.tsxindex d16e764b..841ca870 100644--- a/app/src/components/agents/handoff-panel.tsx+++ b/app/src/components/agents/handoff-panel.tsx@@ -1,11 +1,11 @@-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { useMutation, useQuery } from "@tanstack/react-query";+import { Fragment } from "react";import { AbstractAvatar } from "@/components/agents/abstract-avatar";import {- Empty,- EmptyDescription,- EmptyHeader,- EmptyTitle,-} from "@/components/ui/empty";+ PageEmpty,+ PageRows,+ PageSection,+} from "@/components/layout/page-shell";import {Item,ItemActions,@@ -14,6 +14,7 @@ import {ItemMedia,ItemTitle,} from "@/components/ui/item";+import { Separator } from "@/components/ui/separator";import { Switch } from "@/components/ui/switch";import { handoffRoster } from "@/lib/agents/handoff-roster";import { setHandoffGrantMutationOptions } from "@/lib/agents/mutations";@@ -21,6 +22,7 @@ import {agentHandoffQueryOptions,agentListQueryOptions,} from "@/lib/agents/queries";+import { queryClient } from "@/query-client";/*** Which Bots this one may hand work to.@@ -32,11 +34,11 @@ import {* DIRECTIONAL, and said so on the screen, because the pair is the one thing about this that is easy* to get backwards: this is who this Bot may ask, not who may ask it.*- * One Item per candidate, with a Switch: the grant is one boolean that takes effect when switched,- * which is exactly the row kind a Switch means everywhere else in this app.+ * One row per candidate, with a Switch: the grant is one boolean that takes effect when switched,+ * which is exactly the row kind a Switch means everywhere else in this app. A whole page section of+ * its own, and nothing at all when there is nothing to say to somebody who cannot change it.*/export function HandoffPanel({ agentId }: { agentId: string }) {- const queryClient = useQueryClient();const handoff = useQuery(agentHandoffQueryOptions(agentId));const agents = useQuery(agentListQueryOptions());/*@@ -65,122 +67,95 @@ export function HandoffPanel({ agentId }: { agentId: string }) {if (!canGrant && reachable.length === 0) return null;return (- <section className="grid gap-2">- <header className="flex items-baseline justify-between gap-2">- <h2 className="font-medium text-muted-foreground text-xs uppercase tracking-wide">- Bots it may ask- </h2>- {/* The current answer at a glance, so the list below is detail rather than homework. */}- {grantable && total > 0 ? (- <span className="text-muted-foreground text-xs tabular-nums">+ <PageSection+ action={+ /* The current answer at a glance, so the list below is detail rather than homework. */+ grantable && total > 0 ? (+ <span className="text-muted-foreground text-sm tabular-nums">{granted} of {total}</span>- ) : null}- </header>-- <p className="text-muted-foreground text-sm">- Who this Bot may ask, not who may ask it. What the asked Bot says comes- back into the conversation that asked, relayed and attributed.- </p>-+ ) : null+ }+ description="Who this Bot may ask, not who may ask it. What the asked Bot says comes back into the conversation that asked, relayed and attributed."+ title="Bots it may ask"+ >+ {/* Facts about the deployment rather than rows to act on, so said as sentences. */}{enabled ? null : (- <Item variant="muted">- <ItemContent>- <ItemTitle>Switched off for this deployment</ItemTitle>- {/*- * Unclamped: `ItemDescription` clips to two lines, which is right for a roster row- * whose description is a subtitle and wrong for an item that exists to explain. The- * sentence that gets cut is the one saying what to do about it.- */}- <ItemDescription className="line-clamp-none">- These grants are kept but none takes effect until handing work- between Bots is switched back on.- </ItemDescription>- </ItemContent>- </Item>+ <PageEmpty>+ Switched off for this deployment. These grants are kept but none takes+ effect until handing work between Bots is switched back on.+ </PageEmpty>)}{grantable ? null : (- <Item variant="muted">- <ItemContent>- <ItemTitle>This coworker cannot hand work on</ItemTitle>- {/* Unclamped for the same reason as above: three lines, and the third is the useful one. */}- <ItemDescription className="line-clamp-none">- This deployment has nowhere to record which Bots it may hand work- to, so there is nothing to grant it. It can still be asked by Bots- that can.- </ItemDescription>- </ItemContent>- </Item>+ <PageEmpty>+ This coworker cannot hand work on. This deployment has nowhere to+ record which Bots it may hand work to, so there is nothing to grant+ it. It can still be asked by Bots that can.+ </PageEmpty>)}{setGrant.error ? (- <p className="text-destructive text-sm" role="alert">+ <p className="mt-4 text-destructive text-sm" role="alert">{setGrant.error.message}</p>) : null}{grantable && total === 0 ? (- <Empty className="h-[180px] border border-dashed">- <EmptyHeader>- <EmptyTitle className="text-muted-foreground">- No other Bot here yet- </EmptyTitle>- <EmptyDescription>- When this deployment has more Bots, this is where this one is- allowed to ask them.- </EmptyDescription>- </EmptyHeader>- </Empty>+ <PageEmpty>+ No other Bot here yet. When this deployment has more Bots, this is+ where this one is allowed to ask them.+ </PageEmpty>) : null}{candidates.length > 0 ? (- <div className="flex flex-col gap-2">- {candidates.map((candidate) => (- <Item key={candidate.id} size="sm" variant="muted">- <ItemMedia>- <AbstractAvatar- name={candidate.name}- seed={candidate.avatarSeed}- size={28}- />- </ItemMedia>- <ItemContent>- <ItemTitle>{candidate.name}</ItemTitle>- {/*- * Said on the row, because otherwise it is a coworker that is not on your roster- * appearing in a list with no explanation. It is here only because this Bot may- * already ask it, and that is the sentence a person needs to decide what to do.- */}- <ItemDescription>- {candidate.hidden- ? `${candidate.title} · hidden from your roster`- : candidate.title}- </ItemDescription>- </ItemContent>- <ItemActions>- <Switch- aria-label={`Let this Bot ask ${candidate.name}`}- checked={reachable.includes(candidate.id)}- disabled={!canGrant || setGrant.isPending}- onCheckedChange={(next: boolean) =>- setGrant.mutate({- agentId,- ref: candidate.id,- granted: next,- })- }- />- </ItemActions>- </Item>+ <PageRows>+ {candidates.map((candidate, index) => (+ <Fragment key={candidate.id}>+ {index > 0 ? <Separator /> : null}+ <Item size="sm">+ <ItemMedia>+ <AbstractAvatar+ name={candidate.name}+ seed={candidate.avatarSeed}+ size={28}+ />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>{candidate.name}</ItemTitle>+ {/*+ * Said on the row, because otherwise it is a coworker that is not on your roster+ * appearing in a list with no explanation. It is here only because this Bot may+ * already ask it, and that is the sentence a person needs to decide what to do.+ */}+ <ItemDescription>+ {candidate.hidden+ ? `${candidate.title} · hidden from your roster`+ : candidate.title}+ </ItemDescription>+ </ItemContent>+ <ItemActions>+ <Switch+ aria-label={`Let this Bot ask ${candidate.name}`}+ checked={reachable.includes(candidate.id)}+ disabled={!canGrant || setGrant.isPending}+ onCheckedChange={(next: boolean) =>+ setGrant.mutate({+ agentId,+ ref: candidate.id,+ granted: next,+ })+ }+ />+ </ItemActions>+ </Item>+ </Fragment>))}- </div>+ </PageRows>) : null}{canGrant ? null : (- <p className="text-muted-foreground text-xs">- An administrator decides which Bots may be asked.- </p>+ <PageEmpty>An administrator decides which Bots may be asked.</PageEmpty>)}- </section>+ </PageSection>);}diff --git a/app/src/components/agents/proposed-bot.tsx b/app/src/components/agents/proposed-bot.tsxindex d1a96551..34786c6e 100644--- a/app/src/components/agents/proposed-bot.tsx+++ b/app/src/components/agents/proposed-bot.tsx@@ -230,8 +230,8 @@ function TalkToIt({return (<LinkclassName="mt-2 inline-block text-sm underline underline-offset-4"- search={{ agent: agentId }}- to="/agents"+ params={{ agentId }}+ to="/bots/$agentId">Open {name?.trim() || "the coworker"}</Link>diff --git a/app/src/components/app-sidebar/app-sidebar.tsx b/app/src/components/app-sidebar/app-sidebar.tsxindex ce876e90..0194e38a 100644--- a/app/src/components/app-sidebar/app-sidebar.tsx+++ b/app/src/components/app-sidebar/app-sidebar.tsx@@ -1,18 +1,11 @@import {IconBolt,IconBox,- IconBrain,- IconChecks,- IconDeviceMobile,IconLogout,IconPlus,- IconRobot,IconSearch,IconSettings,IconShieldLock,- IconTargetArrow,- IconUsers,- IconUsersGroup,} from "@tabler/icons-react";import {useInfiniteQuery,@@ -61,13 +54,11 @@ import { useChannelEvents } from "@/lib/channels/use-channel-events";import { appConfig } from "@/lib/generated/application-config";import { EASE_OUT, ENTRANCE_SECONDS } from "@/lib/motion";import { relativeTime } from "@/lib/relative-time";-import { agentListQueryOptions } from "@/lib/agents/queries";-import { ChannelAvatar } from "@/components/channels/avatar";import {type MessageListEmphasis,useMessageListEmphasis,} from "@/lib/settings/message-list";-import { BotAttentionList } from "../bot-profile/attention";+import { BotsNavBadge } from "../bot-profile/attention";import { Button } from "../ui/button";import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "../ui/empty";import { Channel } from "./channel";@@ -231,10 +222,6 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {const navigate = useNavigate();const signOut = useMutation(signOutMutationOptions(queryClient));const channels = useInfiniteQuery(channelListQueryOptions());- // Read off the roster the app already holds, so the sidebar makes no request of its own for it.- const assignedTeamBots =- useQuery(agentListQueryOptions()).data?.filter((bot) => bot.assignedToMe) ??- [];// One socket for the app, opened where the roster is kept live.useChannelEvents();const [search, setSearch] = useState("");@@ -283,22 +270,6 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {><IconPlus /></Button>- <Button- aria-label="New group conversation"- size="icon"- variant="ghost"- render={(props) => (- <Link- {...props}- to="/group/new"- activeProps={{- className: "bg-foreground/5",- }}- />- )}- >- <IconUsersGroup />- </Button></SidebarMenuItem></SidebarMenu></SidebarHeader>@@ -319,8 +290,6 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {</InputGroup></SidebarMenuItem><div className="w-full h-2" />- {/* Bots that need you, or that you paused. See bot-profile/attention.tsx. */}- <BotAttentionList />{/** TWO DIFFERENT NOTHINGS, AND SAYING THE WRONG ONE IS ALARMING. A roster nobody has* used yet needs telling how to start. A roster that simply does not match what is in@@ -390,13 +359,15 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {)}><div className="size-[28px] flex items-center justify-center">- <IconRobot />+ <IconBolt /></div><span className="text-sm">Bots</span>+ {/* What waits on you across every Bot; Bots lists them first. */}+ <BotsNavBadge /></SidebarMenuButton></SidebarMenuItem><SidebarMenuItem>- {/* Beside Agents rather than inside Admin: writing a skill is something anybody does. */}+ {/* Beside Bots rather than inside Admin: writing a skill is something anybody does. */}<SidebarMenuButtonclassName="hover:bg-foreground/5 h-10"render={(props) => (@@ -415,133 +386,6 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {<span className="text-sm trackint-tight">Skills</span></SidebarMenuButton></SidebarMenuItem>- <SidebarMenuItem>- <SidebarMenuButton- className="hover:bg-foreground/5 h-10"- render={(props) => (- <Link- {...props}- to="/agents"- activeProps={{- className: "bg-foreground/5",- }}- />- )}- >- <div className="size-[28px] flex items-center justify-center">- <IconBolt />- </div>- <span className="text-sm trackint-tight">Agents</span>- </SidebarMenuButton>- </SidebarMenuItem>- <SidebarMenuItem>- <SidebarMenuButton- className="hover:bg-foreground/5 h-10"- render={(props) => (- <Link- {...props}- to="/team-bots"- activeProps={{ className: "bg-foreground/5" }}- />- )}- >- <div className="size-[28px] flex items-center justify-center">- <IconUsers />- </div>- <span className="text-sm">Team Bots</span>- </SidebarMenuButton>- </SidebarMenuItem>- {/* Team Bots an administrator assigned to this person: always here, never hidden. */}- {assignedTeamBots.map((bot) => (- <SidebarMenuItem key={bot.id}>- <SidebarMenuButton- className="hover:bg-foreground/5 h-10"- render={(props) => (- <Link- {...props}- search={{ agent: bot.id }}- to="/channel/new"- />- )}- >- <div className="size-[28px] flex items-center justify-center">- <ChannelAvatar participantIds={[bot.id]} size={22} />- </div>- <span className="text-sm">{bot.name}</span>- </SidebarMenuButton>- </SidebarMenuItem>- ))}- <SidebarMenuItem>- <SidebarMenuButton- className="hover:bg-foreground/5 h-10"- render={(props) => (- <Link- {...props}- to="/reachability"- activeProps={{ className: "bg-foreground/5" }}- />- )}- >- <div className="size-[28px] flex items-center justify-center">- <IconDeviceMobile />- </div>- <span className="text-sm">Reachability</span>- </SidebarMenuButton>- </SidebarMenuItem>- {/* Routines live on each coworker's own dialog now, not as a nav destination: the- question "what does this Bot do on a schedule" is asked while looking at the Bot.- The /routines route still answers a direct link. */}- <SidebarMenuItem>- <SidebarMenuButton- className="hover:bg-foreground/5 h-10"- render={(props) => (- <Link- {...props}- to="/responsibilities"- activeProps={{ className: "bg-foreground/5" }}- />- )}- >- <div className="size-[28px] flex items-center justify-center">- <IconTargetArrow />- </div>- <span className="text-sm">Responsibilities</span>- </SidebarMenuButton>- </SidebarMenuItem>- <SidebarMenuItem>- <SidebarMenuButton- className="hover:bg-foreground/5 h-10"- render={(props) => (- <Link- {...props}- to="/memory"- activeProps={{ className: "bg-foreground/5" }}- />- )}- >- <div className="size-[28px] flex items-center justify-center">- <IconBrain />- </div>- <span className="text-sm">Memory</span>- </SidebarMenuButton>- </SidebarMenuItem>- <SidebarMenuItem>- <SidebarMenuButton- className="hover:bg-foreground/5 h-10"- render={(props) => (- <Link- {...props}- to="/approvals"- activeProps={{ className: "bg-foreground/5" }}- />- )}- >- <div className="size-[28px] flex items-center justify-center">- <IconChecks />- </div>- <span className="text-sm">Approvals</span>- </SidebarMenuButton>- </SidebarMenuItem><SidebarMenuItem><DropdownMenu><DropdownMenuTriggerdiff --git a/app/src/components/approvals/bot-rules.tsx b/app/src/components/approvals/bot-rules.tsxnew file mode 100644index 00000000..09d12d89--- /dev/null+++ b/app/src/components/approvals/bot-rules.tsx@@ -0,0 +1,115 @@+import { useMutation, useQuery } from "@tanstack/react-query";+import { Link } from "@tanstack/react-router";+import { Fragment } from "react";+import {+ PageEmpty,+ PageRows,+ PageSection,+} from "@/components/layout/page-shell";+import { Separator } from "@/components/ui/separator";+import {+ approvalInboxOptions,+ createApprovalRuleMutationOptions,+ revokeApprovalRuleMutationOptions,+ ruleCoversBot,+ updateApprovalRuleMutationOptions,+} from "@/lib/approvals";+import { queryClient } from "@/query-client";+import { RuleForm, RuleRow } from "./rules";++/**+ * The person's approval rules for one Bot, and the team rules that reach it, locked, as one card of+ * rows ending in the row that adds one. Rules for every Bot are in Settings → Approvals. A rule's+ * `botId` is the Bot's id, or a pattern covering it.+ */+export function BotApprovalRules({ agentId }: { agentId: string }) {+ const inbox = useQuery(approvalInboxOptions());+ const addRule = useMutation(createApprovalRuleMutationOptions(queryClient));+ const changeRule = useMutation(+ updateApprovalRuleMutationOptions(queryClient),+ );+ const revoke = useMutation(revokeApprovalRuleMutationOptions(queryClient));+ const error = inbox.error ?? changeRule.error ?? revoke.error;+ if (inbox.isPending && !error) return null;+ const rulesOff = inbox.data?.team?.customRulesEnabled === false;+ // Rules naming this Bot, including a pattern that covers it; rules for every Bot are in Settings.+ const mine = (inbox.data?.rules ?? []).filter(+ (rule) => rule.botId !== "*" && ruleCoversBot(rule.botId, agentId),+ );+ const team = (inbox.data?.teamRules ?? []).filter(+ (rule) => rule.botId === "*" || rule.botId === agentId,+ );+ const canAdd = Boolean(inbox.data?.preferences) && !rulesOff;+ const saved = team.length + mine.length;++ return (+ <PageSection+ description={+ <>+ The strictest matching rule wins, so an "ask" rule beats an "allow"+ one. Rules for every Bot are in{" "}+ <Link+ className="underline underline-offset-4"+ to="/settings/approvals"+ >+ Settings → Approvals+ </Link>+ .+ {rulesOff+ ? " Your team has switched personal rules off, so they are kept but do not apply."+ : ""}+ </>+ }+ title="Rules"+ >+ {error ? (+ <p className="mt-4 text-destructive text-sm" role="alert">+ {error.message}+ </p>+ ) : null}+ {saved === 0 ? <PageEmpty>No rules for this Bot.</PageEmpty> : null}+ {saved > 0 || canAdd ? (+ <PageRows>+ {team.map((rule, index) => (+ <Fragment key={rule.id}>+ {index > 0 ? <Separator /> : null}+ <RuleRow+ disabled+ locked+ onChange={() => {}}+ onRevoke={() => {}}+ rule={rule}+ team+ />+ </Fragment>+ ))}+ {mine.map((rule, index) => (+ <Fragment key={rule.id}>+ {team.length + index > 0 ? <Separator /> : null}+ <RuleRow+ disabled={revoke.isPending || changeRule.isPending}+ locked={rulesOff}+ onChange={(behaviour) =>+ changeRule.mutate({ id: rule.id, behaviour })+ }+ onRevoke={() => revoke.mutate(rule.id)}+ rule={rule}+ />+ </Fragment>+ ))}+ {canAdd ? (+ <>+ {saved > 0 ? <Separator /> : null}+ <RuleForm+ botField={false}+ forBot={agentId}+ label="Add a rule"+ save={addRule}+ />+ </>+ ) : null}+ </PageRows>+ ) : null}+ </PageSection>+ );+}diff --git a/app/src/components/approvals/inbox.tsx b/app/src/components/approvals/inbox.tsxdeleted file mode 100644index b6503eeb..00000000--- a/app/src/components/approvals/inbox.tsx+++ /dev/null@@ -1,596 +0,0 @@-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";-import { useState } from "react";-import { SharedUseRequests } from "@/components/approvals/shared-use-requests";-import { Button } from "@/components/ui/button";-import { Switch } from "@/components/ui/switch";-import { Textarea } from "@/components/ui/textarea";-import {- type ApprovalDecision,- type ApprovalRuleInput,- type ApprovalRuleRow,- answerPersonQuestion,- approvalInboxOptions,- BEHAVIOUR_LABELS,- createApprovalRule,- createTeamApprovalRule,- decideApproval,- type HostCommandPolicy,- type RuleBehaviour,- revokeApprovalRule,- revokeTeamApprovalRule,- setApprovalEnabled,- setApprovalPreferences,- setTeamApprovalSettings,- updateApprovalRule,- updateTeamApprovalRule,-} from "@/lib/approvals";-import { currentUserQueryOptions } from "@/lib/auth/queries";--const HOST_LABELS: Record<HostCommandPolicy, string> = {- ask: "Ask every time",- allow: "Always allow",- never: "Never",-};-const selectClass =- "h-9 rounded-md border bg-background px-2 text-sm disabled:opacity-50";--export function ApprovalInbox() {- const cache = useQueryClient();- const inbox = useQuery(approvalInboxOptions());- const refresh = () => cache.invalidateQueries({ queryKey: ["approvals"] });- const decision = useMutation({- mutationFn: ({ id, choice }: { id: string; choice: ApprovalDecision }) =>- decideApproval(id, choice),- onSuccess: refresh,- });- const preference = useMutation({- mutationFn: setApprovalEnabled,- onSuccess: refresh,- });- const revoke = useMutation({- mutationFn: revokeApprovalRule,- onSuccess: refresh,- });- const [answers, setAnswers] = useState<Record<string, string>>({});- const answer = useMutation({- mutationFn: ({ id, response }: { id: string; response: string }) =>- answerPersonQuestion(id, response),- onSuccess: refresh,- });- const { data: me } = useQuery(currentUserQueryOptions());- const isAdmin = me?.role === "admin";- const preferences = useMutation({- mutationFn: setApprovalPreferences,- onSuccess: refresh,- });- const addRule = useMutation({- mutationFn: createApprovalRule,- onSuccess: refresh,- });- const team = useMutation({- mutationFn: setTeamApprovalSettings,- onSuccess: refresh,- });- const addTeamRule = useMutation({- mutationFn: createTeamApprovalRule,- onSuccess: refresh,- });- const changeRule = useMutation({- mutationFn: ({ id, behaviour }: { id: string; behaviour: RuleBehaviour }) =>- updateApprovalRule(id, { behaviour }),- onSuccess: refresh,- });- const changeTeamRule = useMutation({- mutationFn: ({ id, behaviour }: { id: string; behaviour: RuleBehaviour }) =>- updateTeamApprovalRule(id, { behaviour }),- onSuccess: refresh,- });- const revokeTeam = useMutation({- mutationFn: revokeTeamApprovalRule,- onSuccess: refresh,- });- const error =- inbox.error ??- decision.error ??- preference.error ??- revoke.error ??- answer.error ??- preferences.error ??- addRule.error ??- team.error ??- addTeamRule.error ??- revokeTeam.error ??- changeRule.error ??- changeTeamRule.error;- const enforced = inbox.data?.team?.enforceAutoReview ?? false;- const rulesOff = inbox.data?.team?.customRulesEnabled === false;- const pending =- inbox.data?.requests.filter((request) => request.status === "pending") ??- [];- return (- <div className="space-y-6">- {error ? (- <p role="alert" className="text-sm text-destructive">- {error.message}- </p>- ) : null}- <label- htmlFor="ask-before-changes"- className="flex items-center justify-between gap-4 rounded-lg border p-4"- >- <span>- <span className="block font-medium">Ask before making changes</span>- <span className="text-sm text-muted-foreground">- Review a Bot's changes to websites, connected apps, and files.- </span>- </span>- <Switch- id="ask-before-changes"- aria-label="Ask before making changes"- checked={inbox.data?.enabled ?? false}- disabled={inbox.isLoading || preference.isPending}- onCheckedChange={(enabled) => preference.mutate(enabled)}- />- </label>- {inbox.data?.preferences ? (- <>- <label- htmlFor="auto-review"- className="flex items-center justify-between gap-4 rounded-lg border p-4"- >- <span>- <span id="auto-review-title" className="block font-medium">- Auto-review- </span>- <span- id="auto-review-description"- className="text-sm text-muted-foreground"- >- {enforced ? "Required by your team. " : ""}- Before an action that could affect your accounts or share- information, a model checks it against what you asked for, your- rules and the safety requirements. If it cannot decide, it asks- you.- </span>- </span>- <Switch- id="auto-review"- // Named by its title alone and described by the sentence under it, so the name does- // not depend on how a label wrapping a composite control is resolved.- aria-labelledby="auto-review-title"- aria-describedby="auto-review-description"- checked={enforced || inbox.data.preferences.autoReview}- disabled={enforced || preferences.isPending}- onCheckedChange={(autoReview) =>- preferences.mutate({ autoReview })- }- />- </label>- <label- htmlFor="host-commands"- className="flex items-center justify-between gap-4 rounded-lg border p-4"- >- <span>- <span className="block font-medium">- Commands on your computer- </span>- <span className="text-sm text-muted-foreground">- {inbox.data.hostCommands &&- inbox.data.hostCommands !== inbox.data.preferences.hostCommands- ? `Your team limits this to "${HOST_LABELS[inbox.data.hostCommands]}". `- : ""}- The OpenBot desktop app still shows each command before it runs- on your computer.- </span>- </span>- <select- id="host-commands"- aria-label="Commands on your computer"- className={selectClass}- value={inbox.data.preferences.hostCommands}- disabled={preferences.isPending}- onChange={(event) =>- preferences.mutate({- hostCommands: event.target.value as HostCommandPolicy,- })- }- >- {(Object.keys(HOST_LABELS) as HostCommandPolicy[]).map((key) => (- <option key={key} value={key}>- {HOST_LABELS[key]}- </option>- ))}- </select>- </label>- </>- ) : null}- <div className="space-y-3">- <h2 className="font-medium">Waiting for you</h2>- {inbox.data?.questions.map((question) => (- <article- key={question.id}- className="space-y-3 rounded-lg border p-4"- >- <h3 className="font-medium">- {question.botId} asks: {question.question}- </h3>- {question.why ? (- <p className="text-sm text-muted-foreground">{question.why}</p>- ) : null}- <Textarea- aria-label="Your answer"- placeholder="Your answer"- value={answers[question.id] ?? ""}- onChange={(event) =>- setAnswers((prior) => ({- ...prior,- [question.id]: event.target.value,- }))- }- />- <Button- disabled={answer.isPending || !answers[question.id]?.trim()}- onClick={() =>- answer.mutate({- id: question.id,- response: answers[question.id] ?? "",- })- }- >- Send answer- </Button>- </article>- ))}- {inbox.isLoading ? (- <p className="text-sm text-muted-foreground">Loading approvals…</p>- ) : pending.length === 0 ? (- <p className="text-sm text-muted-foreground">- No actions need your approval.- </p>- ) : (- pending.map((request) => (- <article- className="space-y-3 rounded-lg border p-4"- key={request.id}- >- <div>- <h3 className="font-medium">- {request.action.botId} wants to{" "}- {request.action.toolRef- .replace(/^computer_|^host\//, "")- .replaceAll("_", " ")}- </h3>- <p className="text-sm text-muted-foreground">- {request.action.scope}- </p>- {request.action.policy ? (- <p className="text-sm">- {request.action.policy.behaviour === "hand_off"- ? "Handed to you: "- : ""}- {request.action.policy.reason}- </p>- ) : null}- </div>- <pre className="max-h-52 overflow-auto whitespace-pre-wrap rounded bg-muted p-3 text-xs">- {JSON.stringify(request.action.args, null, 2)}- </pre>- {request.action.policy?.behaviour === "hand_off" ? (- <div className="flex flex-wrap gap-2">- <Button- disabled={decision.isPending}- onClick={() =>- decision.mutate({ id: request.id, choice: "handled" })- }- >- I did it myself- </Button>- <Button- variant="outline"- disabled={decision.isPending}- onClick={() =>- decision.mutate({ id: request.id, choice: "deny" })- }- >- Don't do it- </Button>- </div>- ) : (- <div className="flex flex-wrap gap-2">- <Button- disabled={decision.isPending}- onClick={() =>- decision.mutate({ id: request.id, choice: "allow_once" })- }- >- Allow once- </Button>- <Button- variant="outline"- disabled={decision.isPending}- onClick={() =>- decision.mutate({- id: request.id,- choice: "allow_always",- })- }- >- Always allow here- </Button>- <Button- variant="outline"- disabled={decision.isPending}- onClick={() =>- decision.mutate({ id: request.id, choice: "deny" })- }- >- Deny- </Button>- </div>- )}- </article>- ))- )}- </div>- <SharedUseRequests />- <div className="space-y-3">- <h2 className="font-medium">Rules</h2>- <p className="text-sm text-muted-foreground">- The strictest matching rule wins, so an "ask" rule beats an "allow"- one. Team rules are locked. Changing a password, security settings and- payments are always handed to you.- {rulesOff- ? " Your team has switched personal rules off, so they are kept but do not apply."- : ""}- </p>- {inbox.data?.teamRules.map((rule) => (- <RuleRow- key={rule.id}- rule={rule}- locked={!isAdmin}- disabled={revokeTeam.isPending || changeTeamRule.isPending}- onRevoke={() => revokeTeam.mutate(rule.id)}- onChange={(behaviour) =>- changeTeamRule.mutate({ id: rule.id, behaviour })- }- team- />- ))}- {inbox.data?.rules.map((rule) => (- <RuleRow- key={rule.id}- rule={rule}- locked={rulesOff}- disabled={revoke.isPending || changeRule.isPending}- onRevoke={() => revoke.mutate(rule.id)}- onChange={(behaviour) =>- changeRule.mutate({ id: rule.id, behaviour })- }- />- ))}- {!inbox.data?.rules.length && !inbox.data?.teamRules.length ? (- <p className="text-sm text-muted-foreground">No rules saved.</p>- ) : null}- {inbox.data?.preferences && !rulesOff ? (- <RuleForm- label="Add a rule"- pending={addRule.isPending}- onSave={(input) => addRule.mutate(input)}- />- ) : null}- </div>- {isAdmin && inbox.data?.team ? (- <div className="space-y-3">- <h2 className="font-medium">Team settings</h2>- <label- htmlFor="enforce-auto-review"- className="flex items-center justify-between gap-4 rounded-lg border p-4"- >- <span id="enforce-auto-review-title" className="font-medium">- Require auto-review for everyone- </span>- <Switch- id="enforce-auto-review"- aria-labelledby="enforce-auto-review-title"- checked={inbox.data.team.enforceAutoReview}- disabled={team.isPending}- onCheckedChange={(enforceAutoReview) =>- team.mutate({ enforceAutoReview })- }- />- </label>- <label- htmlFor="custom-rules"- className="flex items-center justify-between gap-4 rounded-lg border p-4"- >- <span id="custom-rules-title" className="font-medium">- Let members set personal rules- </span>- <Switch- id="custom-rules"- aria-labelledby="custom-rules-title"- checked={inbox.data.team.customRulesEnabled}- disabled={team.isPending}- onCheckedChange={(customRulesEnabled) =>- team.mutate({ customRulesEnabled })- }- />- </label>- <label- htmlFor="host-commands-cap"- className="flex items-center justify-between gap-4 rounded-lg border p-4"- >- <span>- <span className="block font-medium">- Commands on members' computers, at most- </span>- <span className="text-sm text-muted-foreground">- A member's own stricter setting still applies.- </span>- </span>- <select- id="host-commands-cap"- aria-label="Commands on members' computers, at most"- className={selectClass}- value={inbox.data.team.hostCommandsCap}- disabled={team.isPending}- onChange={(event) =>- team.mutate({- hostCommandsCap: event.target.value as HostCommandPolicy,- })- }- >- {(Object.keys(HOST_LABELS) as HostCommandPolicy[]).map((key) => (- <option key={key} value={key}>- {HOST_LABELS[key]}- </option>- ))}- </select>- </label>- <RuleForm- label="Add a team rule"- pending={addTeamRule.isPending}- onSave={(input) => addTeamRule.mutate(input)}- />- </div>- ) : null}- </div>- );-}--function RuleRow({- rule,- team,- locked,- disabled,- onRevoke,- onChange,-}: {- rule: ApprovalRuleRow;- team?: boolean;- locked?: boolean;- disabled: boolean;- onRevoke: () => void;- onChange: (behaviour: RuleBehaviour) => void;-}) {- const label = `${BEHAVIOUR_LABELS[rule.behaviour]}${team ? " (team rule)" : ""}`;- return (- <div className="flex items-center justify-between gap-4 rounded-lg border p-4">- <div className="space-y-1">- {locked ? (- <p className="text-sm font-medium">{label}</p>- ) : (- <select- aria-label={`Behaviour for ${rule.toolRef}`}- className={selectClass}- value={rule.behaviour}- disabled={disabled}- onChange={(event) => {- const behaviour = event.target.value as RuleBehaviour;- onChange(behaviour);- }}- >- {(Object.keys(BEHAVIOUR_LABELS) as RuleBehaviour[]).map((key) => (- <option key={key} value={key}>- {BEHAVIOUR_LABELS[key]}- {team ? " (team rule)" : ""}- </option>- ))}- </select>- )}- <p className="text-sm text-muted-foreground">- {rule.toolRef}- {rule.effect !== "*" ? `, ${rule.effect}` : ""}- {rule.scope !== "*" ? ` on ${rule.scope}` : ""}- {rule.botId !== "*" ? ` for ${rule.botId}` : ""}- </p>- </div>- {locked ? (- <span className="text-sm text-muted-foreground">Locked</span>- ) : (- <Button variant="outline" disabled={disabled} onClick={onRevoke}>- Remove- </Button>- )}- </div>- );-}--const EMPTY_RULE: ApprovalRuleInput = {- botId: "*",- toolRef: "",- effect: "*",- scope: "*",- behaviour: "ask",-};--/**- * An action class and a behaviour. `*` matches anything, so `mcp/gmail/*` is every Gmail tool and a- * target of `*.example.com` is every page on that site.- */-function RuleForm({- label,- pending,- onSave,-}: {- label: string;- pending: boolean;- onSave: (input: ApprovalRuleInput) => void;-}) {- const [rule, setRule] = useState<ApprovalRuleInput>(EMPTY_RULE);- const field = (key: keyof ApprovalRuleInput, title: string, hint: string) => (- <label className="grid gap-1 text-sm">- <span>{title}</span>- <input- aria-label={title}- className="h-9 rounded-md border bg-background px-2"- placeholder={hint}- value={rule[key]}- onChange={(event) => {- // Read before the updater runs: React restores a controlled input's DOM value first.- const value = event.target.value;- setRule((prior) => ({ ...prior, [key]: value }));- }}- />- </label>- );- return (- <form- className="grid gap-3 rounded-lg border p-4 sm:grid-cols-2"- onSubmit={(event) => {- event.preventDefault();- onSave(rule);- setRule(EMPTY_RULE);- }}- >- <h3 className="font-medium sm:col-span-2">{label}</h3>- {field("toolRef", "Tool or app", "mcp/gmail/*, computer_click, host/*")}- {field("effect", "Kind of action", "* , write, read, delegate")}- {field("scope", "Target", "*, a site, a folder, a Bot name")}- {field("botId", "Bot", "* for every Bot")}- <label className="grid gap-1 text-sm">- <span>Behaviour</span>- <select- aria-label="Behaviour"- className={selectClass}- value={rule.behaviour}- onChange={(event) => {- const behaviour = event.target.value as RuleBehaviour;- setRule((prior) => ({ ...prior, behaviour }));- }}- >- {(Object.keys(BEHAVIOUR_LABELS) as RuleBehaviour[]).map((key) => (- <option key={key} value={key}>- {BEHAVIOUR_LABELS[key]}- </option>- ))}- </select>- </label>- <div className="flex items-end">- <Button type="submit" disabled={pending || !rule.toolRef.trim()}>- Save rule- </Button>- </div>- </form>- );-}diff --git a/app/src/components/approvals/rules.tsx b/app/src/components/approvals/rules.tsxnew file mode 100644index 00000000..f7b290ea--- /dev/null+++ b/app/src/components/approvals/rules.tsx@@ -0,0 +1,309 @@+import {+ IconChevronRight,+ IconLock,+ IconPlus,+ IconShieldCheck,+} from "@tabler/icons-react";+import type { UseMutationResult } from "@tanstack/react-query";+import { useId, useState } from "react";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Field, FieldGroup, FieldLabel } from "@/components/ui/field";+import { Input } from "@/components/ui/input";+import {+ Item,+ ItemActions,+ ItemContent,+ ItemDescription,+ ItemMedia,+ ItemTitle,+} from "@/components/ui/item";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import {+ type ApprovalRuleInput,+ type ApprovalRuleRow,+ BEHAVIOUR_LABELS,+ type HostCommandPolicy,+ type RuleBehaviour,+} from "@/lib/approvals";++export const HOST_LABELS: Record<HostCommandPolicy, string> = {+ ask: "Ask every time",+ allow: "Always allow",+ never: "Never",+};++/**+ * One value from a fixed set of labelled choices: a rule's behaviour, or how commands on a computer+ * are handled. The keys of `labels` are the values, in the order they are offered.+ */+export function LabelSelect<T extends string>({+ id,+ label,+ labels,+ value,+ disabled,+ onChange,+}: {+ id?: string;+ /** The trigger's accessible name, where no visible label names it. */+ label?: string;+ labels: Record<T, string>;+ value: T;+ disabled?: boolean;+ onChange: (value: T) => void;+}) {+ return (+ <Select+ disabled={disabled}+ onValueChange={(next) => {+ if (next !== null) onChange(next as T);+ }}+ value={value}+ >+ <SelectTrigger aria-label={label} id={id}>+ <SelectValue>{labels[value]}</SelectValue>+ </SelectTrigger>+ <SelectContent>+ {(Object.keys(labels) as T[]).map((key) => (+ <SelectItem key={key} value={key}>+ {labels[key]}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ );+}++/** The behaviours a team rule is offered under, each saying it is the team's. */+const TEAM_BEHAVIOUR_LABELS = Object.fromEntries(+ Object.entries(BEHAVIOUR_LABELS).map(([key, label]) => [+ key,+ `${label} (team rule)`,+ ]),+) as Record<RuleBehaviour, string>;++/**+ * One saved rule, as a row: what it matches, and what a Bot does about it. A locked rule — a team+ * rule seen by a member, or a personal rule the team has switched off — states its behaviour and+ * offers nothing to change.+ */+export function RuleRow({+ rule,+ team,+ locked,+ disabled,+ onRevoke,+ onChange,+}: {+ rule: ApprovalRuleRow;+ team?: boolean;+ locked?: boolean;+ disabled: boolean;+ onRevoke: () => void;+ onChange: (behaviour: RuleBehaviour) => void;+}) {+ const labels = team ? TEAM_BEHAVIOUR_LABELS : BEHAVIOUR_LABELS;+ // The tool is the title; the rest of what the rule matches is the line beneath, never clamped,+ // since two rules for one tool differ only there.+ const match = [+ rule.effect !== "*" ? rule.effect : null,+ rule.scope !== "*" ? `on ${rule.scope}` : null,+ rule.botId !== "*" ? `for ${rule.botId}` : null,+ ]+ .filter(Boolean)+ .join(" ");+ return (+ <Item size="sm">+ <ItemMedia variant="icon">+ {locked ? <IconLock /> : <IconShieldCheck />}+ </ItemMedia>+ <ItemContent>+ <ItemTitle>{rule.toolRef}</ItemTitle>+ {match ? (+ <ItemDescription className="line-clamp-none break-all">+ {match}+ </ItemDescription>+ ) : null}+ {locked ? <ItemDescription>Locked</ItemDescription> : null}+ </ItemContent>+ <ItemActions>+ {locked ? (+ <span className="text-muted-foreground text-sm">+ {labels[rule.behaviour]}+ </span>+ ) : (+ <>+ <LabelSelect+ disabled={disabled}+ label={`Behaviour for ${rule.toolRef}`}+ labels={labels}+ onChange={onChange}+ value={rule.behaviour}+ />+ <Button+ disabled={disabled}+ onClick={onRevoke}+ size="sm"+ variant="outline"+ >+ Remove+ </Button>+ </>+ )}+ </ItemActions>+ </Item>+ );+}++const EMPTY_RULE: ApprovalRuleInput = {+ botId: "*",+ toolRef: "",+ effect: "*",+ scope: "*",+ behaviour: "ask",+};++/**+ * An action class and a behaviour, added from a row that opens a dialog. `*` matches anything, so+ * `mcp/gmail/*` is every Gmail tool and a target of `*.example.com` is every page on that site.+ */+export function RuleForm({+ label,+ save,+ botField = true,+ forBot,+}: {+ label: string;+ /** The write that adds the rule. The dialog closes when it succeeds and shows why when it fails. */+ save: UseMutationResult<unknown, Error, ApprovalRuleInput>;+ /** Off where the rule applies to every Bot, so there is no Bot to name. */+ botField?: boolean;+ /** The Bot every rule from this form is for, already known from the page it is on. */+ forBot?: string;+}) {+ const blank = forBot ? { ...EMPTY_RULE, botId: forBot } : EMPTY_RULE;+ const [rule, setRule] = useState<ApprovalRuleInput>(blank);+ const [open, setOpen] = useState(false);+ const id = useId();+ // Closing without saving drops what was typed, so the dialog opens blank next time.+ const close = () => {+ setOpen(false);+ setRule(blank);+ };+ // Opening starts clean: the last attempt's failure belongs to the draft it was about.+ const show = () => {+ save.reset();+ setOpen(true);+ };+ const field = (key: keyof ApprovalRuleInput, title: string, hint: string) => (+ <Field>+ <FieldLabel htmlFor={`${id}-${key}`}>{title}</FieldLabel>+ <Input+ id={`${id}-${key}`}+ onChange={(event) => {+ // Read before the updater runs: React restores a controlled input's DOM value first.+ const value = event.target.value;+ setRule((prior) => ({ ...prior, [key]: value }));+ }}+ placeholder={hint}+ value={rule[key]}+ />+ </Field>+ );+ return (+ <>+ <Item render={<button onClick={show} type="button" />} size="sm">+ <ItemMedia variant="icon">+ <IconPlus />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>{label}</ItemTitle>+ <ItemDescription>+ A tool or app, and what a Bot does before using it.+ </ItemDescription>+ </ItemContent>+ <ItemActions>+ <IconChevronRight className="size-4 text-muted-foreground" />+ </ItemActions>+ </Item>+ <Dialog onOpenChange={(next) => (next ? show() : close())} open={open}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{label}</DialogTitle>+ <DialogDescription>+ * matches anything, so mcp/gmail/* is every Gmail tool and a+ target of *.example.com is every page on that site.+ </DialogDescription>+ </DialogHeader>+ <DialogBody className="mt-4">+ {/* The submit button is in the footer and reaches this form by id, so DialogBody stays a+ direct child of DialogContent and keeps scrolling. */}+ <form+ id={id}+ onSubmit={(event) => {+ event.preventDefault();+ // A failed save keeps the dialog and the draft, so the person can correct it.+ save.mutate(rule, { onSuccess: close });+ }}+ >+ <FieldGroup>+ {field(+ "toolRef",+ "Tool or app",+ "mcp/gmail/*, computer_click, host/*",+ )}+ {field("effect", "Kind of action", "* , write, read, delegate")}+ {field("scope", "Target", "*, a site, a folder, a Bot name")}+ {botField ? field("botId", "Bot", "* for every Bot") : null}+ <Field>+ <FieldLabel htmlFor={`${id}-behaviour`}>Behaviour</FieldLabel>+ <LabelSelect+ id={`${id}-behaviour`}+ labels={BEHAVIOUR_LABELS}+ onChange={(behaviour) =>+ setRule((prior) => ({ ...prior, behaviour }))+ }+ value={rule.behaviour}+ />+ </Field>+ </FieldGroup>+ </form>+ {save.error ? (+ <p className="mt-4 text-destructive text-sm" role="alert">+ {save.error.message}+ </p>+ ) : null}+ </DialogBody>+ <DialogFooter className="mt-4">+ <Button onClick={close} size="sm" variant="outline">+ Cancel+ </Button>+ <Button+ disabled={save.isPending || !rule.toolRef.trim()}+ form={id}+ size="sm"+ type="submit"+ >+ Save rule+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </>+ );+}diff --git a/app/src/components/approvals/settings.tsx b/app/src/components/approvals/settings.tsxnew file mode 100644index 00000000..8301c09c--- /dev/null+++ b/app/src/components/approvals/settings.tsx@@ -0,0 +1,259 @@+import { IconEyeCheck, IconHandStop, IconTerminal2 } from "@tabler/icons-react";+import { useMutation, useQuery } from "@tanstack/react-query";+import { Link } from "@tanstack/react-router";+import { Fragment } from "react";+import {+ PageEmpty,+ PageRows,+ PageSection,+} from "@/components/layout/page-shell";+import {+ Item,+ ItemActions,+ ItemContent,+ ItemDescription,+ ItemMedia,+ ItemTitle,+} from "@/components/ui/item";+import { Separator } from "@/components/ui/separator";+import { Switch } from "@/components/ui/switch";+import {+ approvalInboxOptions,+ approvalPreferencesMutationOptions,+ createApprovalRuleMutationOptions,+ revokeApprovalRuleMutationOptions,+ ruleCoversBot,+ updateApprovalRuleMutationOptions,+} from "@/lib/approvals";+import { agentListQueryOptions } from "@/lib/agents/queries";+import { currentUserQueryOptions } from "@/lib/auth/queries";+import { queryClient } from "@/query-client";+import { HOST_LABELS, LabelSelect, RuleForm, RuleRow } from "./rules";++/**+ * The person's own approval settings: whether their Bots ask before changing things, and the rules+ * that apply to every one of their Bots. Team rules are listed so the person can see them, locked;+ * administrators change them in Admin → Approvals. Rules for a single Bot are on that Bot's page.+ */+export function ApprovalSettings() {+ const inbox = useQuery(approvalInboxOptions());+ const me = useQuery(currentUserQueryOptions()).data;+ const agents = useQuery(agentListQueryOptions());+ const hiddenAgents = useQuery(agentListQueryOptions(true));+ const preferences = useMutation(+ approvalPreferencesMutationOptions(queryClient),+ );+ const addRule = useMutation(createApprovalRuleMutationOptions(queryClient));+ const changeRule = useMutation(+ updateApprovalRuleMutationOptions(queryClient),+ );+ const revoke = useMutation(revokeApprovalRuleMutationOptions(queryClient));+ const error =+ inbox.error ?? preferences.error ?? changeRule.error ?? revoke.error;+ if (inbox.isPending && !error) return null;+ const enforced = inbox.data?.team?.enforceAutoReview ?? false;+ const rulesOff = inbox.data?.team?.customRulesEnabled === false;+ const everyBot = (inbox.data?.rules ?? []).filter(+ (rule) => rule.botId === "*",+ );+ /*+ * Rules that name no Bot this person can open — a Bot since deleted, or a name typed where an id+ * belonged. They are still enforced, so they are listed here where they can be removed.+ */+ const reachable = [...(agents.data ?? []), ...(hiddenAgents.data ?? [])];+ const otherBots = (inbox.data?.rules ?? []).filter(+ (rule) =>+ rule.botId !== "*" &&+ (agents.data === undefined ||+ !reachable.some((agent) => ruleCoversBot(rule.botId, agent.id))),+ );+ const teamRules = inbox.data?.teamRules ?? [];+ const canAdd = Boolean(inbox.data?.preferences) && !rulesOff;+ const saved = teamRules.length + everyBot.length;++ return (+ <>+ {error ? (+ <p className="mt-6 text-destructive text-sm" role="alert">+ {error.message}+ </p>+ ) : null}+ {me?.role === "admin" ? (+ <p className="mt-6 text-muted-foreground text-sm">+ Team settings and shared account requests are in{" "}+ <Link className="underline underline-offset-4" to="/admin/approvals">+ Admin → Approvals+ </Link>+ .+ </p>+ ) : null}+ <PageSection title="Before a Bot acts">+ <PageRows>+ <Item size="sm">+ <ItemMedia variant="icon">+ <IconHandStop />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>Ask before making changes</ItemTitle>+ <ItemDescription>+ Review a Bot's changes to websites, connected apps, and files.+ </ItemDescription>+ </ItemContent>+ <ItemActions>+ <Switch+ aria-label="Ask before making changes"+ checked={inbox.data?.enabled ?? false}+ disabled={inbox.isLoading || preferences.isPending}+ onCheckedChange={(enabled) => preferences.mutate({ enabled })}+ />+ </ItemActions>+ </Item>+ {inbox.data?.preferences ? (+ <>+ <Separator />+ <Item size="sm">+ <ItemMedia variant="icon">+ <IconEyeCheck />+ </ItemMedia>+ <ItemContent>+ <ItemTitle id="auto-review-title">Auto-review</ItemTitle>+ <ItemDescription+ className="line-clamp-none"+ id="auto-review-description"+ >+ {enforced ? "Required by your team. " : ""}+ Before an action that could affect your accounts or share+ information, a model checks it against what you asked for,+ your rules and the safety requirements. If it cannot decide,+ it asks you.+ </ItemDescription>+ </ItemContent>+ <ItemActions>+ <Switch+ // Named by its title alone and described by the sentence beside it, so the name+ // stays short however long the description grows.+ aria-describedby="auto-review-description"+ aria-labelledby="auto-review-title"+ checked={enforced || inbox.data.preferences.autoReview}+ disabled={enforced || preferences.isPending}+ onCheckedChange={(autoReview) =>+ preferences.mutate({ autoReview })+ }+ />+ </ItemActions>+ </Item>+ <Separator />+ <Item size="sm">+ <ItemMedia variant="icon">+ <IconTerminal2 />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>Commands on your computer</ItemTitle>+ <ItemDescription className="line-clamp-none">+ {inbox.data.hostCommands &&+ inbox.data.hostCommands !==+ inbox.data.preferences.hostCommands+ ? `Your team limits this to "${HOST_LABELS[inbox.data.hostCommands]}". `+ : ""}+ The OpenBot desktop app still shows each command before it+ runs on your computer.+ </ItemDescription>+ </ItemContent>+ <ItemActions>+ <LabelSelect+ disabled={preferences.isPending}+ label="Commands on your computer"+ labels={HOST_LABELS}+ onChange={(hostCommands) =>+ preferences.mutate({ hostCommands })+ }+ value={inbox.data.preferences.hostCommands}+ />+ </ItemActions>+ </Item>+ </>+ ) : null}+ </PageRows>+ </PageSection>+ <PageSection+ description={+ <>+ The strictest matching rule wins, so an "ask" rule beats an "allow"+ one. Team rules are locked. Changing a password, security settings+ and payments are always handed to you. Rules for a single Bot are on{" "}+ <Link className="underline underline-offset-4" to="/bots">+ that Bot's page+ </Link>+ .+ {rulesOff+ ? " Your team has switched personal rules off, so they are kept but do not apply."+ : ""}+ </>+ }+ title="Rules for every Bot"+ >+ {saved === 0 ? <PageEmpty>No rules saved.</PageEmpty> : null}+ {saved > 0 || canAdd ? (+ <PageRows>+ {teamRules.map((rule, index) => (+ <Fragment key={rule.id}>+ {index > 0 ? <Separator /> : null}+ <RuleRow+ disabled+ locked+ onChange={() => {}}+ onRevoke={() => {}}+ rule={rule}+ team+ />+ </Fragment>+ ))}+ {everyBot.map((rule, index) => (+ <Fragment key={rule.id}>+ {teamRules.length + index > 0 ? <Separator /> : null}+ <RuleRow+ disabled={revoke.isPending || changeRule.isPending}+ locked={rulesOff}+ onChange={(behaviour) =>+ changeRule.mutate({ id: rule.id, behaviour })+ }+ onRevoke={() => revoke.mutate(rule.id)}+ rule={rule}+ />+ </Fragment>+ ))}+ {canAdd ? (+ <>+ {saved > 0 ? <Separator /> : null}+ <RuleForm botField={false} label="Add a rule" save={addRule} />+ </>+ ) : null}+ </PageRows>+ ) : null}+ </PageSection>+ {agents.data !== undefined && otherBots.length > 0 ? (+ <PageSection+ description="These name no Bot you can open, but they still apply to any Bot they match. Remove the ones you no longer want."+ title="Rules for other Bots"+ >+ <PageRows>+ {otherBots.map((rule, index) => (+ <Fragment key={rule.id}>+ {index > 0 ? <Separator /> : null}+ <RuleRow+ disabled={revoke.isPending || changeRule.isPending}+ locked={rulesOff}+ onChange={(behaviour) =>+ changeRule.mutate({ id: rule.id, behaviour })+ }+ onRevoke={() => revoke.mutate(rule.id)}+ rule={rule}+ />+ </Fragment>+ ))}+ </PageRows>+ </PageSection>+ ) : null}+ </>+ );+}diff --git a/app/src/components/approvals/shared-use-requests.tsx b/app/src/components/approvals/shared-use-requests.tsxindex 924d4522..b0e85d26 100644--- a/app/src/components/approvals/shared-use-requests.tsx+++ b/app/src/components/approvals/shared-use-requests.tsx@@ -1,5 +1,17 @@+import { IconShare } from "@tabler/icons-react";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { Fragment } from "react";+import { PageRows, PageSection } from "@/components/layout/page-shell";import { Button } from "@/components/ui/button";+import {+ Item,+ ItemContent,+ ItemDescription,+ ItemFooter,+ ItemMedia,+ ItemTitle,+} from "@/components/ui/item";+import { Separator } from "@/components/ui/separator";import { currentUserQueryOptions } from "@/lib/auth/queries";import {decideSharedUseMutationOptions,@@ -16,6 +28,11 @@ const WHY: Record<SharedUseRequestReason, string> = {grant: "It was granted the app's actions.",};+/**+ * Requests to use a shared account, for an administrator to approve or decline: one row each,+ * saying what is approved now against what is asked, with the decision beneath. Nothing is drawn+ * for anyone else, or when nothing is waiting.+ */export function SharedUseRequests() {const queryClient = useQueryClient();const me = useQuery(currentUserQueryOptions()).data;@@ -25,51 +42,63 @@ export function SharedUseRequests() {if (!isAdmin || !requests.data?.length) return null;return (- <div className="space-y-3">- <h2 className="font-medium">Shared account requests</h2>+ <PageSection title="Shared account requests">{decide.error ? (- <p className="text-destructive text-sm" role="alert">+ <p className="mt-4 text-destructive text-sm" role="alert">{decide.error.message}</p>) : null}- {requests.data.map((request) => (- <article className="space-y-2 rounded-lg border p-4" key={request.id}>- <h3 className="font-medium text-sm">- {request.botName} wants the shared {request.title} account- </h3>- <p className="text-muted-foreground text-sm">- {WHY[request.reason as SharedUseRequestReason] ?? request.reason}- </p>- <p className="text-sm">- Now:{" "}- {request.current- ? describeApproval(request.current)- : "Not approved"}- </p>- <p className="text-sm">Asked: {describeApproval(request.proposed)}</p>- <div className="flex gap-2">- <Button- disabled={decide.isPending}- onClick={() =>- decide.mutate({ id: request.id, decision: "approve" })- }- size="sm"- >- Approve- </Button>- <Button- disabled={decide.isPending}- onClick={() =>- decide.mutate({ id: request.id, decision: "decline" })- }- size="sm"- variant="outline"- >- Decline- </Button>- </div>- </article>- ))}- </div>+ <PageRows>+ {requests.data.map((request, index) => (+ <Fragment key={request.id}>+ {index > 0 ? <Separator /> : null}+ <Item size="sm">+ <ItemMedia variant="icon">+ <IconShare />+ </ItemMedia>+ <ItemContent>+ <ItemTitle className="line-clamp-none">+ {request.botName} wants the shared {request.title} account+ </ItemTitle>+ <ItemDescription className="line-clamp-none">+ {WHY[request.reason as SharedUseRequestReason] ??+ request.reason}+ </ItemDescription>+ <p className="text-sm">+ Now:{" "}+ {request.current+ ? describeApproval(request.current)+ : "Not approved"}+ </p>+ <p className="text-sm">+ Asked: {describeApproval(request.proposed)}+ </p>+ </ItemContent>+ <ItemFooter className="justify-start">+ <Button+ disabled={decide.isPending}+ onClick={() =>+ decide.mutate({ id: request.id, decision: "approve" })+ }+ size="sm"+ >+ Approve+ </Button>+ <Button+ disabled={decide.isPending}+ onClick={() =>+ decide.mutate({ id: request.id, decision: "decline" })+ }+ size="sm"+ variant="outline"+ >+ Decline+ </Button>+ </ItemFooter>+ </Item>+ </Fragment>+ ))}+ </PageRows>+ </PageSection>);}diff --git a/app/src/components/approvals/team-settings.tsx b/app/src/components/approvals/team-settings.tsxnew file mode 100644index 00000000..c4eff933--- /dev/null+++ b/app/src/components/approvals/team-settings.tsx@@ -0,0 +1,156 @@+import { IconEyeCheck, IconTerminal2, IconUserCog } from "@tabler/icons-react";+import { useMutation, useQuery } from "@tanstack/react-query";+import { Fragment } from "react";+import {+ PageEmpty,+ PageRows,+ PageSection,+} from "@/components/layout/page-shell";+import {+ Item,+ ItemActions,+ ItemContent,+ ItemDescription,+ ItemMedia,+ ItemTitle,+} from "@/components/ui/item";+import { Separator } from "@/components/ui/separator";+import { Switch } from "@/components/ui/switch";+import {+ approvalInboxOptions,+ createTeamApprovalRuleMutationOptions,+ revokeTeamApprovalRuleMutationOptions,+ teamApprovalSettingsMutationOptions,+ updateTeamApprovalRuleMutationOptions,+} from "@/lib/approvals";+import { queryClient } from "@/query-client";+import { HOST_LABELS, LabelSelect, RuleForm, RuleRow } from "./rules";+import { SharedUseRequests } from "./shared-use-requests";++/**+ * What every member's Bots must do, set by an administrator: the team-wide controls, the rules that+ * apply to everyone, and requests to use a shared account. Members read the team rules, locked, in+ * Settings → Approvals.+ */+export function TeamApprovalSettings() {+ const inbox = useQuery(approvalInboxOptions());+ const team = useMutation(teamApprovalSettingsMutationOptions(queryClient));+ const addTeamRule = useMutation(+ createTeamApprovalRuleMutationOptions(queryClient),+ );+ const changeTeamRule = useMutation(+ updateTeamApprovalRuleMutationOptions(queryClient),+ );+ const revokeTeam = useMutation(+ revokeTeamApprovalRuleMutationOptions(queryClient),+ );+ const error =+ inbox.error ?? team.error ?? changeTeamRule.error ?? revokeTeam.error;+ if (inbox.isPending && !error) return null;+ const settings = inbox.data?.team;+ const teamRules = inbox.data?.teamRules ?? [];++ return (+ <>+ {error ? (+ <p className="mt-6 text-destructive text-sm" role="alert">+ {error.message}+ </p>+ ) : null}+ {settings ? (+ <PageSection title="Team settings">+ <PageRows>+ <Item size="sm">+ <ItemMedia variant="icon">+ <IconEyeCheck />+ </ItemMedia>+ <ItemContent>+ <ItemTitle id="enforce-auto-review-title">+ Require auto-review for everyone+ </ItemTitle>+ </ItemContent>+ <ItemActions>+ <Switch+ aria-labelledby="enforce-auto-review-title"+ checked={settings.enforceAutoReview}+ disabled={team.isPending}+ onCheckedChange={(enforceAutoReview) =>+ team.mutate({ enforceAutoReview })+ }+ />+ </ItemActions>+ </Item>+ <Separator />+ <Item size="sm">+ <ItemMedia variant="icon">+ <IconUserCog />+ </ItemMedia>+ <ItemContent>+ <ItemTitle id="custom-rules-title">+ Let members set personal rules+ </ItemTitle>+ </ItemContent>+ <ItemActions>+ <Switch+ aria-labelledby="custom-rules-title"+ checked={settings.customRulesEnabled}+ disabled={team.isPending}+ onCheckedChange={(customRulesEnabled) =>+ team.mutate({ customRulesEnabled })+ }+ />+ </ItemActions>+ </Item>+ <Separator />+ <Item size="sm">+ <ItemMedia variant="icon">+ <IconTerminal2 />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>Commands on members' computers, at most</ItemTitle>+ <ItemDescription>+ A member's own stricter setting still applies.+ </ItemDescription>+ </ItemContent>+ <ItemActions>+ <LabelSelect+ disabled={team.isPending}+ label="Commands on members' computers, at most"+ labels={HOST_LABELS}+ onChange={(hostCommandsCap) =>+ team.mutate({ hostCommandsCap })+ }+ value={settings.hostCommandsCap}+ />+ </ItemActions>+ </Item>+ </PageRows>+ </PageSection>+ ) : null}+ <PageSection+ description="These apply to every member's Bots, and members cannot change them."+ title="Team rules"+ >+ {teamRules.length === 0 ? <PageEmpty>No team rules.</PageEmpty> : null}+ <PageRows>+ {teamRules.map((rule) => (+ <Fragment key={rule.id}>+ <RuleRow+ disabled={revokeTeam.isPending || changeTeamRule.isPending}+ onChange={(behaviour) =>+ changeTeamRule.mutate({ id: rule.id, behaviour })+ }+ onRevoke={() => revokeTeam.mutate(rule.id)}+ rule={rule}+ team+ />+ <Separator />+ </Fragment>+ ))}+ <RuleForm label="Add a team rule" save={addTeamRule} />+ </PageRows>+ </PageSection>+ <SharedUseRequests />+ </>+ );+}diff --git a/app/src/components/approvals/waiting.tsx b/app/src/components/approvals/waiting.tsxnew file mode 100644index 00000000..b101dddd--- /dev/null+++ b/app/src/components/approvals/waiting.tsx@@ -0,0 +1,219 @@+import { IconHandStop, IconMessageQuestion } from "@tabler/icons-react";+import { useMutation, useQuery } from "@tanstack/react-query";+import { Fragment, useState } from "react";+import { PageRows, PageSection } from "@/components/layout/page-shell";+import { Button } from "@/components/ui/button";+import {+ Item,+ ItemContent,+ ItemDescription,+ ItemFooter,+ ItemMedia,+ ItemTitle,+} from "@/components/ui/item";+import { Separator } from "@/components/ui/separator";+import { Textarea } from "@/components/ui/textarea";+import { agentListQueryOptions } from "@/lib/agents/queries";+import {+ answerPersonQuestionMutationOptions,+ approvalInboxOptions,+ decideApprovalMutationOptions,+} from "@/lib/approvals";+import { queryClient } from "@/query-client";++/**+ * Questions and actions waiting on the person, one row each, decided where it is shown: the answer+ * box and the decision buttons sit on the row's own footer line. Given a Bot, only that Bot's. The+ * same requests the conversation draws inline, so a decision made in either place is the one+ * decision.+ */+export function WaitingForYou({ agentId }: { agentId?: string }) {+ const inbox = useQuery(approvalInboxOptions());+ const agents = useQuery(agentListQueryOptions());+ const botName = (id: string) =>+ agents.data?.find((agent) => agent.id === id)?.name ?? id;+ const decision = useMutation(decideApprovalMutationOptions(queryClient));+ const [answers, setAnswers] = useState<Record<string, string>>({});+ const answer = useMutation(answerPersonQuestionMutationOptions(queryClient));+ const ours = (botId: string) => agentId === undefined || botId === agentId;+ const questions = (inbox.data?.questions ?? []).filter((question) =>+ ours(question.conversationBotId ?? question.botId),+ );+ const pending = (inbox.data?.requests ?? []).filter(+ (request) => request.status === "pending" && ours(request.action.botId),+ );+ const error = inbox.error ?? decision.error ?? answer.error;+ return (+ <>+ {error ? (+ <p role="alert" className="mt-4 text-sm text-destructive">+ {error.message}+ </p>+ ) : null}+ {questions.length + pending.length > 0 ? (+ <PageRows>+ {questions.map((question, index) => (+ <Fragment key={question.id}>+ {index > 0 ? <Separator /> : null}+ <Item size="sm">+ <ItemMedia variant="icon">+ <IconMessageQuestion />+ </ItemMedia>+ <ItemContent>+ <ItemTitle className="line-clamp-none">+ {botName(question.botId)} asks: {question.question}+ </ItemTitle>+ {question.why ? (+ <ItemDescription className="line-clamp-none">+ {question.why}+ </ItemDescription>+ ) : null}+ </ItemContent>+ <ItemFooter className="flex-col items-start">+ <Textarea+ aria-label="Your answer"+ onChange={(event) =>+ setAnswers((prior) => ({+ ...prior,+ [question.id]: event.target.value,+ }))+ }+ placeholder="Your answer"+ value={answers[question.id] ?? ""}+ />+ <Button+ disabled={answer.isPending || !answers[question.id]?.trim()}+ onClick={() =>+ answer.mutate({+ id: question.id,+ response: answers[question.id] ?? "",+ })+ }+ size="sm"+ >+ Send answer+ </Button>+ </ItemFooter>+ </Item>+ </Fragment>+ ))}+ {pending.map((request, index) => (+ <Fragment key={request.id}>+ {questions.length + index > 0 ? <Separator /> : null}+ <Item size="sm">+ <ItemMedia variant="icon">+ <IconHandStop />+ </ItemMedia>+ <ItemContent className="min-w-0">+ <ItemTitle className="line-clamp-none">+ {botName(request.action.botId)} wants to{" "}+ {request.action.toolRef+ .replace(/^computer_|^host\//, "")+ .replaceAll("_", " ")}+ </ItemTitle>+ <ItemDescription className="line-clamp-none break-all">+ {request.action.scope}+ </ItemDescription>+ {request.action.policy ? (+ <p className="text-sm">+ {request.action.policy.behaviour === "hand_off"+ ? "Handed to you: "+ : ""}+ {request.action.policy.reason}+ </p>+ ) : null}+ <pre className="mt-1 max-h-52 overflow-auto whitespace-pre-wrap rounded bg-muted p-3 text-xs">+ {JSON.stringify(request.action.args, null, 2)}+ </pre>+ </ItemContent>+ {request.action.policy?.behaviour === "hand_off" ? (+ <ItemFooter className="flex-wrap justify-start">+ <Button+ disabled={decision.isPending}+ onClick={() =>+ decision.mutate({ id: request.id, choice: "handled" })+ }+ size="sm"+ >+ I did it myself+ </Button>+ <Button+ disabled={decision.isPending}+ onClick={() =>+ decision.mutate({ id: request.id, choice: "deny" })+ }+ size="sm"+ variant="outline"+ >+ Don't do it+ </Button>+ </ItemFooter>+ ) : (+ <ItemFooter className="flex-wrap justify-start">+ <Button+ disabled={decision.isPending}+ onClick={() =>+ decision.mutate({+ id: request.id,+ choice: "allow_once",+ })+ }+ size="sm"+ >+ Allow once+ </Button>+ <Button+ disabled={decision.isPending}+ onClick={() =>+ decision.mutate({+ id: request.id,+ choice: "allow_always",+ })+ }+ size="sm"+ variant="outline"+ >+ Always allow here+ </Button>+ <Button+ disabled={decision.isPending}+ onClick={() =>+ decision.mutate({ id: request.id, choice: "deny" })+ }+ size="sm"+ variant="outline"+ >+ Deny+ </Button>+ </ItemFooter>+ )}+ </Item>+ </Fragment>+ ))}+ </PageRows>+ ) : null}+ </>+ );+}++/**+ * What one Bot is waiting on the person for, at the top of its page. Nothing is drawn when nothing+ * waits: the sidebar's badge already said whether to look.+ */+export function BotNeedsYou({ agentId }: { agentId: string }) {+ const inbox = useQuery(approvalInboxOptions());+ const waiting =+ (inbox.data?.questions ?? []).some(+ (question) => (question.conversationBotId ?? question.botId) === agentId,+ ) ||+ (inbox.data?.requests ?? []).some(+ (request) =>+ request.status === "pending" && request.action.botId === agentId,+ );+ if (!waiting) return null;+ return (+ <PageSection title="Needs you">+ <WaitingForYou agentId={agentId} />+ </PageSection>+ );+}diff --git a/app/src/components/bot-profile/access.tsx b/app/src/components/bot-profile/access.tsxnew file mode 100644index 00000000..14a8b8be--- /dev/null+++ b/app/src/components/bot-profile/access.tsx@@ -0,0 +1,234 @@+import { IconApps, IconBox, IconChevronRight } from "@tabler/icons-react";+import { useMutation, useQuery } from "@tanstack/react-query";+import { Link } from "@tanstack/react-router";+import { Fragment } from "react";+import { HandoffPanel } from "@/components/agents/handoff-panel";+import {+ PageEmpty,+ PageRows,+ PageSection,+} from "@/components/layout/page-shell";+import {+ Item,+ ItemActions,+ ItemContent,+ ItemDescription,+ ItemMedia,+ ItemTitle,+} from "@/components/ui/item";+import { Separator } from "@/components/ui/separator";+import { Switch } from "@/components/ui/switch";+import type { AgentProfile } from "@/lib/agents/queries";+import { currentUserQueryOptions } from "@/lib/auth/queries";+import { setPluginGrantMutationOptions } from "@/lib/plugins/mutations";+import {+ agentPluginsQueryOptions,+ type GrantedPlugins,+ pluginsPageQueryOptions,+} from "@/lib/plugins/queries";+import { readToolName } from "@/lib/plugins/tool-name";+import { queryClient } from "@/query-client";++/** "google-drive" as "Google Drive": the connector key, said the way a person would. */+function connectorName(key: string): string {+ return key+ .split(/[-_]/)+ .filter(Boolean)+ .map((word) => word[0]?.toUpperCase() + word.slice(1))+ .join(" ");+}++/**+ * Connector key → the labels of the tools this Bot holds on it.+ *+ * Vendors prefix every tool with their own name — "Notion create pages" — which next to a row+ * already titled Notion reads as a stutter. Stripped only as a leading word, and re-cased, so+ * "Notion search" becomes "Search" while "Search notion pages" is left alone.+ */+function connectorTools(plugins: GrantedPlugins): Map<string, string[]> {+ const connectors = new Map<string, string[]>();+ for (const tool of plugins.tools) {+ const key = tool.ref.split("/")[0] ?? tool.ref;+ let label = readToolName(tool.toolName).label;+ const prefix = `${key.toLowerCase()} `;+ if (label.toLowerCase().startsWith(prefix)) {+ const rest = label.slice(prefix.length);+ label = rest ? rest[0]?.toUpperCase() + rest.slice(1) : label;+ }+ connectors.set(key, [...(connectors.get(key) ?? []), label]);+ }+ return connectors;+}++/** How many apps this Bot holds tools on. For the summary on the Bot's page. */+export function connectorCount(plugins: GrantedPlugins): number {+ return connectorTools(plugins).size;+}++/** What this Bot may reach: your skills on it, everything granted to it, and who it may ask. */+export function AccessSections({ agent }: { agent: AgentProfile }) {+ return (+ <>+ {agent.mine ? <YourSkills agentId={agent.id} /> : null}+ <Granted agentId={agent.id} />+ <HandoffPanel agentId={agent.id} />+ </>+ );+}++/**+ * Your own skills, one switch each. Only on your own Bot: the server lets a person put their own+ * skill on a Bot they own, and neither half alone is enough.+ */+function YourSkills({ agentId }: { agentId: string }) {+ const me = useQuery(currentUserQueryOptions()).data;+ const page = useQuery(pluginsPageQueryOptions());+ const grant = useMutation(setPluginGrantMutationOptions(queryClient));+ const skills = (page.data?.skills ?? []).filter(+ (skill) => me && skill.ownerUserId === me.id,+ );+ return (+ <PageSection+ description="A skill this Bot carries is offered in its composer as /name."+ title="Your skills"+ >+ {grant.error ? (+ <p className="mt-4 text-destructive text-sm" role="alert">+ {grant.error.message}+ </p>+ ) : null}+ {page.isPending ? null : page.error ? (+ <p className="mt-4 text-destructive text-sm" role="alert">+ Could not load your skills.+ </p>+ ) : skills.length === 0 ? (+ <PageEmpty>+ You have not written a skill yet.{" "}+ <Link className="underline underline-offset-4" to="/skills">+ Write one+ </Link>+ .+ </PageEmpty>+ ) : (+ <PageRows>+ {skills.map((skill, index) => (+ <Fragment key={skill.slug}>+ {index > 0 ? <Separator /> : null}+ <Item size="sm">+ <ItemMedia variant="icon">+ <IconBox />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>/{skill.slug}</ItemTitle>+ <ItemDescription>{skill.summary}</ItemDescription>+ </ItemContent>+ <ItemActions>+ <Switch+ aria-label={skill.slug}+ checked={skill.grantedTo.includes(agentId)}+ disabled={grant.isPending}+ onCheckedChange={(granted) =>+ grant.mutate({+ agentId,+ granted,+ kind: "skill",+ ref: skill.slug,+ })+ }+ />+ </ItemActions>+ </Item>+ </Fragment>+ ))}+ </PageRows>+ )}+ </PageSection>+ );+}++/**+ * Everything this Bot holds, read from the same snapshot a run is offered. Read-only: apps are+ * granted by an administrator, who gets a link to where that is decided.+ */+function Granted({ agentId }: { agentId: string }) {+ const me = useQuery(currentUserQueryOptions()).data;+ const plugins = useQuery(agentPluginsQueryOptions(agentId));+ if (plugins.isPending) return null;+ if (!plugins.data) {+ return (+ <p className="mt-6 text-destructive text-sm" role="alert">+ What this Bot may reach could not be loaded.+ </p>+ );+ }+ const connectors = [...connectorTools(plugins.data).entries()];+ const skills = plugins.data.skills;+ return (+ <PageSection+ description="What this Bot may reach when it works. Anything not listed is refused when called."+ title="Granted"+ >+ {connectors.length === 0 && skills.length === 0 ? (+ <PageEmpty>+ Nothing granted yet. An administrator grants apps from the Plugins+ screens; until then this Bot can converse, and nothing more.+ </PageEmpty>+ ) : (+ <PageRows>+ {connectors.map(([key, labels], index) => (+ <Fragment key={key}>+ {index > 0 ? <Separator /> : null}+ <Item+ render={+ me?.role === "admin" ? (+ <Link+ params={{ agentId, key }}+ to="/admin/plugins/$key/bots/$agentId"+ />+ ) : undefined+ }+ size="sm"+ >+ <ItemMedia variant="icon">+ <IconApps />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>{connectorName(key)}</ItemTitle>+ <ItemDescription>+ {labels.slice(0, 4).join(", ")}+ {labels.length > 4 ? ` and ${labels.length - 4} more` : ""}+ </ItemDescription>+ </ItemContent>+ <ItemActions>+ <span className="text-muted-foreground text-sm tabular-nums">+ {labels.length} {labels.length === 1 ? "tool" : "tools"}+ </span>+ {me?.role === "admin" ? (+ <IconChevronRight className="size-4 text-muted-foreground" />+ ) : null}+ </ItemActions>+ </Item>+ </Fragment>+ ))}+ {skills.map((skill, index) => (+ <Fragment key={skill.slug}>+ {connectors.length + index > 0 ? <Separator /> : null}+ <Item size="sm">+ <ItemMedia variant="icon">+ <IconBox />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>{skill.title}</ItemTitle>+ <ItemDescription>{skill.summary}</ItemDescription>+ </ItemContent>+ <ItemActions>+ <span className="text-muted-foreground text-sm">Skill</span>+ </ItemActions>+ </Item>+ </Fragment>+ ))}+ </PageRows>+ )}+ </PageSection>+ );+}diff --git a/app/src/components/bot-profile/activity.tsx b/app/src/components/bot-profile/activity.tsxindex 4bf00ac1..cf50d94b 100644--- a/app/src/components/bot-profile/activity.tsx+++ b/app/src/components/bot-profile/activity.tsx@@ -56,7 +56,7 @@ const KIND_LABEL: Record<ActivityKind, string> = {};/** Where an item opens: its conversation when it has one, otherwise the screen that owns its kind. */-function linkFor(item: ActivityItem) {+function linkFor(item: ActivityItem, agentId: string) {if (item.channelId)return (<Link to="/channel/$channelId" params={{ channelId: item.channelId }} />@@ -64,11 +64,11 @@ function linkFor(item: ActivityItem) {switch (item.kind) {case "approval":case "question":- return <Link to="/approvals" />;+ return <Link params={{ agentId }} to="/bots/$agentId" />;case "responsibility":- return <Link to="/responsibilities" />;+ return <Link params={{ agentId }} to="/bots/$agentId/responsibilities" />;case "routine":- return <Link to="/routines" />;+ return <Link params={{ agentId }} to="/bots/$agentId/routines" />;default:return null;}@@ -84,7 +84,7 @@ function ActivityRow({const stop = useMutation(stopHandoffMutationOptions(queryClient));const cancel = useMutation(cancelFollowUpMutationOptions(queryClient));const Icon = ICONS[item.kind];- const link = linkFor(item);+ const link = linkFor(item, agentId);const when = relativeTime(item.at);const control = item.stoppable ? (<Buttondiff --git a/app/src/components/bot-profile/attention.tsx b/app/src/components/bot-profile/attention.tsxindex 80bb0f64..d157492c 100644--- a/app/src/components/bot-profile/attention.tsx+++ b/app/src/components/bot-profile/attention.tsx@@ -1,14 +1,9 @@-import { IconPlayerPause } from "@tabler/icons-react";-import { useMutation, useQuery } from "@tanstack/react-query";-import { Link } from "@tanstack/react-router";+import { useQuery } from "@tanstack/react-query";import { useEffect, useRef } from "react";-import { SidebarMenuButton, SidebarMenuItem } from "@/components/ui/sidebar";-import { setBotPausedMutationOptions } from "@/lib/bot-lifecycle/mutations";import {type BotAttention,botAttentionQueryOptions,} from "@/lib/bot-lifecycle/queries";-import { queryClient } from "@/query-client";/** Questions, approvals and stalled hand-offs: the things only the person can move forward. */export function needsInput(bot: BotAttention): number {@@ -68,67 +63,39 @@ function useAttentionNotifications(bots: BotAttention[] | undefined) {}/**- * The Bots that need this person, for the sidebar: a badge per Bot that has a question, an approval- * or a stalled hand-off waiting, or something unread, and a resume button for one they paused.+ * The badge on the sidebar's Bots item: how many questions, approvals and stalled hand-offs wait on+ * this person across all their Bots, or a dot when the only news is something unread. Opening Bots+ * lists the Bots behind the number first, under Needs you.*- * Renders nothing when no Bot needs anything, so a quiet day costs the roster no space.+ * It also sends the browser notification when a Bot starts needing the person, since it is the one+ * piece of the app that is always on screen and always reading this.+ *+ * Renders nothing when nothing is waiting, so a quiet day costs the sidebar nothing.*/-export function BotAttentionList() {+export function BotsNavBadge() {const attention = useQuery(botAttentionQueryOptions());- const resume = useMutation(setBotPausedMutationOptions(queryClient));useAttentionNotifications(attention.data);- const bots = (attention.data ?? []).filter(- (bot) => bot.paused || needsInput(bot) > 0 || bot.unread > 0,- );- if (attention.isPending || attention.error || bots.length === 0) return null;- return (- <>- {bots.map((bot) => {- const waiting = needsInput(bot);- return (- <SidebarMenuItem key={bot.agentId} className="flex flex-row gap-1">- <SidebarMenuButton- aria-label={`${bot.name}: ${bot.paused ? "paused" : attentionSummary(bot)}`}- className="hover:bg-foreground/5 h-9 flex-1"- render={(props) => (- <Link- {...props}- to="/bots/$agentId"- params={{ agentId: bot.agentId }}- activeProps={{ className: "bg-foreground/5" }}- />- )}- >- <span className="truncate text-sm">{bot.name}</span>- {waiting > 0 ? (- <span- className="ml-auto rounded-full bg-primary px-1.5 text-[11px] font-medium text-primary-foreground tabular-nums"- title={attentionSummary(bot)}- >- {waiting}- </span>- ) : bot.unread > 0 ? (- <span- className="ml-auto size-2 rounded-full bg-primary"- title={attentionSummary(bot)}- />- ) : null}- </SidebarMenuButton>- {bot.paused ? (- <SidebarMenuButton- className="hover:bg-foreground/5 h-9 w-auto shrink-0 gap-1 text-muted-foreground text-xs"- disabled={resume.isPending}- onClick={() =>- resume.mutate({ agentId: bot.agentId, paused: false })- }- >- <IconPlayerPause className="size-3.5" />- Paused, tap to resume- </SidebarMenuButton>- ) : null}- </SidebarMenuItem>- );- })}- </>- );+ const bots = attention.data ?? [];+ const waiting = bots.reduce((total, bot) => total + needsInput(bot), 0);+ if (waiting > 0) {+ return (+ <span+ aria-label={`${waiting} ${waiting === 1 ? "thing needs" : "things need"} you`}+ className="ml-auto rounded-full bg-primary px-1.5 text-[11px] font-medium text-primary-foreground tabular-nums"+ role="img"+ >+ {waiting}+ </span>+ );+ }+ if (bots.some((bot) => bot.unread > 0)) {+ return (+ <span+ aria-label="Unread messages"+ className="ml-auto size-2 rounded-full bg-primary"+ role="img"+ />+ );+ }+ return null;}diff --git a/app/src/components/bot-profile/bot-subpage.tsx b/app/src/components/bot-profile/bot-subpage.tsxnew file mode 100644index 00000000..6eec42fc--- /dev/null+++ b/app/src/components/bot-profile/bot-subpage.tsx@@ -0,0 +1,42 @@+import { useQuery } from "@tanstack/react-query";+import type * as React from "react";+import { PageShell } from "@/components/layout/page-shell";+import { type AgentProfile, agentQueryOptions } from "@/lib/agents/queries";++/**+ * The frame of every `/bots/$agentId/<area>` page: back to the Bot by name, then the area.+ *+ * One frame so each area page is only its own rows, and so a Bot the person cannot reach says so in+ * the same words everywhere.+ */+export function BotSubpage({+ agentId,+ title,+ description,+ children,+}: {+ agentId: string;+ title: string;+ description: string;+ children: (agent: AgentProfile) => React.ReactNode;+}) {+ const agent = useQuery(agentQueryOptions(agentId));+ return (+ <PageShell+ backButton={{+ label: agent.data?.name ?? "Bot",+ linkProps: { params: { agentId }, to: "/bots/$agentId" },+ }}+ description={description}+ title={title}+ >+ {agent.isPending ? null : agent.error ? (+ <p className="mt-6 text-destructive text-sm" role="alert">+ This Bot is not one you can reach.+ </p>+ ) : (+ children(agent.data)+ )}+ </PageShell>+ );+}diff --git a/app/src/components/bot-profile/manage.tsx b/app/src/components/bot-profile/manage.tsxnew file mode 100644index 00000000..b033d88c--- /dev/null+++ b/app/src/components/bot-profile/manage.tsx@@ -0,0 +1,345 @@+import {+ IconChevronRight,+ IconCopy,+ IconEyeOff,+ IconPin,+ IconRefresh,+ IconTrash,+} from "@tabler/icons-react";+import { useMutation, useQuery } from "@tanstack/react-query";+import { useState } from "react";+import { PageRows, PageSection } from "@/components/layout/page-shell";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import {+ Item,+ ItemActions,+ ItemContent,+ ItemDescription,+ ItemMedia,+ ItemTitle,+} from "@/components/ui/item";+import { Separator } from "@/components/ui/separator";+import { Switch } from "@/components/ui/switch";+import {+ deleteAgentMutationOptions,+ duplicateAgentMutationOptions,+ setAgentHiddenMutationOptions,+ setAgentPinnedMutationOptions,+} from "@/lib/agents/mutations";+import type { AgentProfile } from "@/lib/agents/queries";+import { resetBotMutationOptions } from "@/lib/bot-lifecycle/mutations";+import {+ botResetPlanQueryOptions,+ type ResetPlan,+} from "@/lib/bot-lifecycle/queries";+import { queryClient } from "@/query-client";++/** Each count the notice lists, in the words the person reads, skipping the kinds with nothing. */+function resetLines(plan: ResetPlan): string[] {+ const lines: [number, string, string][] = [+ [plan.conversations, "conversation", "conversations"],+ [plan.memorySources, "memory source", "memory sources"],+ [plan.memories, "imported memory", "imported memories"],+ [plan.routines, "routine", "routines"],+ [plan.responsibilities, "responsibility", "responsibilities"],+ [plan.followUps, "scheduled follow-up", "scheduled follow-ups"],+ [plan.formedMemories, "memory it formed", "memories it formed"],+ [plan.backgroundResearch, "background research", "background research"],+ [plan.standingApprovals, "standing permission", "standing permissions"],+ ];+ return lines+ .filter(([count]) => count > 0)+ .map(([count, one, many]) => `${count} ${count === 1 ? one : many}`);+}++function ResetDialog({+ agent,+ onOpenChange,+ open,+}: {+ agent: AgentProfile;+ onOpenChange: (open: boolean) => void;+ open: boolean;+}) {+ const plan = useQuery({+ ...botResetPlanQueryOptions(agent.id),+ enabled: open,+ });+ const reset = useMutation(resetBotMutationOptions(queryClient));+ const lines = plan.data ? resetLines(plan.data) : [];+ return (+ <Dialog onOpenChange={onOpenChange} open={open}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Reset {agent.name}?</DialogTitle>+ <DialogDescription>+ This deletes what {agent.name} has with you, and only with you.+ Nobody else's conversations or data are touched. It cannot be+ undone.+ </DialogDescription>+ </DialogHeader>+ <DialogBody className="mt-4 overflow-y-auto">+ {plan.isPending ? null : plan.error ? (+ <p className="text-destructive text-sm" role="alert">+ Could not count what a reset would delete.+ </p>+ ) : reset.isSuccess ? (+ <p className="text-sm">Done. {agent.name} starts fresh with you.</p>+ ) : (+ <div className="grid gap-2 text-sm">+ {lines.length === 0 ? (+ <p>There is nothing of yours to delete.</p>+ ) : (+ <>+ <p>This will delete:</p>+ <ul className="list-disc pl-5">+ {lines.map((line) => (+ <li key={line}>{line}</li>+ ))}+ </ul>+ </>+ )}+ {plan.data.sharedConversationsKept > 0 ? (+ <p className="text-muted-foreground">+ {plan.data.sharedConversationsKept} conversation+ {plan.data.sharedConversationsKept === 1 ? " is" : "s are"}{" "}+ shared with other people or Bots and will be kept.+ </p>+ ) : null}+ <p className="text-muted-foreground">+ Your own memories, the ones you told a Bot directly, are kept.+ </p>+ </div>+ )}+ {reset.error ? (+ <p className="mt-2 text-destructive text-sm" role="alert">+ {reset.error.message}+ </p>+ ) : null}+ </DialogBody>+ <DialogFooter className="mt-4">+ <Button+ onClick={() => onOpenChange(false)}+ size="sm"+ variant="outline"+ >+ {reset.isSuccess ? "Close" : "Cancel"}+ </Button>+ {reset.isSuccess ? null : (+ <Button+ disabled={!plan.data || lines.length === 0 || reset.isPending}+ onClick={() => reset.mutate(agent.id)}+ size="sm"+ variant="destructive"+ >+ {reset.isPending ? "Resetting…" : "Delete and reset"}+ </Button>+ )}+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}++/**+ * What can be done to a Bot: pin and hide (the person's own list only), duplicate, reset what it+ * has with this person, and — for whoever may manage it — delete it.+ *+ * Navigation is the caller's: hiding and deleting leave the page, duplicating opens the copy.+ */+export function ManageSection({+ agent,+ onHidden,+ onDuplicated,+ onDeleted,+}: {+ agent: AgentProfile;+ onHidden: () => void;+ onDuplicated: (copyId: string) => void;+ onDeleted: () => void;+}) {+ const setPinned = useMutation(setAgentPinnedMutationOptions(queryClient));+ const setHidden = useMutation(setAgentHiddenMutationOptions(queryClient));+ const duplicate = useMutation(duplicateAgentMutationOptions(queryClient));+ const remove = useMutation(deleteAgentMutationOptions(queryClient));+ const [resetOpen, setResetOpen] = useState(false);+ const [deleteOpen, setDeleteOpen] = useState(false);+ const error = setPinned.error ?? setHidden.error ?? duplicate.error;+ // An administrator put it in this person's list; it stays pinned and cannot be hidden.+ const assigned = agent.assignedToMe === true;++ return (+ <PageSection title="Manage">+ {error ? (+ <p className="mt-4 text-destructive text-sm" role="alert">+ {error.message}+ </p>+ ) : null}+ <PageRows>+ <Item size="sm">+ <ItemMedia variant="icon">+ <IconPin />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>Pinned</ItemTitle>+ <ItemDescription>+ {assigned+ ? "Assigned to you by an administrator, so it stays at the top of your Bots list."+ : agent.pinned+ ? "At the top of your Bots list. Nobody else's list changes."+ : "Keep it at the top of your Bots list. Nobody else's list changes."}+ </ItemDescription>+ </ItemContent>+ <ItemActions>+ <Switch+ aria-label="Pinned"+ checked={agent.pinned || assigned}+ disabled={assigned || setPinned.isPending}+ onCheckedChange={(pinned) =>+ setPinned.mutate({ agentId: agent.id, pinned })+ }+ />+ </ItemActions>+ </Item>+ <Separator />+ <Item size="sm">+ <ItemMedia variant="icon">+ <IconEyeOff />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>Hidden</ItemTitle>+ <ItemDescription>+ {assigned+ ? "Assigned to you by an administrator, so it cannot be hidden."+ : agent.hidden+ ? "Folded under Hidden on your Bots list. Nobody else's list changes."+ : "Take it off your Bots list. Nobody else's list changes."}+ </ItemDescription>+ </ItemContent>+ <ItemActions>+ <Switch+ aria-label="Hidden"+ checked={agent.hidden}+ disabled={assigned || setHidden.isPending}+ onCheckedChange={async (hidden) => {+ await setHidden.mutateAsync({ agentId: agent.id, hidden });+ if (hidden) onHidden();+ }}+ />+ </ItemActions>+ </Item>+ <Separator />+ <Item+ render={+ <button+ disabled={duplicate.isPending}+ onClick={async () =>+ onDuplicated((await duplicate.mutateAsync(agent.id)).id)+ }+ type="button"+ />+ }+ size="sm"+ >+ <ItemMedia variant="icon">+ <IconCopy />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>Duplicate</ItemTitle>+ <ItemDescription>+ A copy of your own, with no key and no conversations.+ </ItemDescription>+ </ItemContent>+ </Item>+ <Separator />+ <Item+ render={<button onClick={() => setResetOpen(true)} type="button" />}+ size="sm"+ >+ <ItemMedia variant="icon">+ <IconRefresh />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>Reset</ItemTitle>+ <ItemDescription>+ Delete your conversations with it, what it remembers for you, and+ its scheduled work. You see what will go first.+ </ItemDescription>+ </ItemContent>+ <ItemActions>+ <IconChevronRight className="size-4 text-muted-foreground" />+ </ItemActions>+ </Item>+ {agent.canManage ? (+ <>+ <Separator />+ <Item+ render={+ <button onClick={() => setDeleteOpen(true)} type="button" />+ }+ size="sm"+ >+ <ItemMedia variant="icon">+ <IconTrash />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>Delete</ItemTitle>+ <ItemDescription>+ For everyone. This cannot be undone.+ </ItemDescription>+ </ItemContent>+ <ItemActions>+ <IconChevronRight className="size-4 text-muted-foreground" />+ </ItemActions>+ </Item>+ </>+ ) : null}+ </PageRows>+ <ResetDialog agent={agent} onOpenChange={setResetOpen} open={resetOpen} />+ <Dialog onOpenChange={setDeleteOpen} open={deleteOpen}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Delete {agent.name}?</DialogTitle>+ <DialogDescription>This cannot be undone.</DialogDescription>+ </DialogHeader>+ {remove.error ? (+ <DialogBody className="mt-4">+ <p className="text-destructive text-sm" role="alert">+ {remove.error.message}+ </p>+ </DialogBody>+ ) : null}+ <DialogFooter className="mt-4">+ <Button+ onClick={() => setDeleteOpen(false)}+ size="sm"+ variant="outline"+ >+ Cancel+ </Button>+ <Button+ disabled={remove.isPending}+ onClick={async () => {+ await remove.mutateAsync(agent.id);+ onDeleted();+ }}+ size="sm"+ variant="destructive"+ >+ {remove.isPending ? "Deleting…" : "Delete"}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </PageSection>+ );+}diff --git a/app/src/components/bot-profile/profile.tsx b/app/src/components/bot-profile/profile.tsxindex 86429894..2fc72bd9 100644--- a/app/src/components/bot-profile/profile.tsx+++ b/app/src/components/bot-profile/profile.tsx@@ -1,52 +1,44 @@import {IconBell,+ IconChevronRight,IconMessage,IconPlayerPause,- IconRefresh,- IconRoute,} from "@tabler/icons-react";import { useMutation, useQuery } from "@tanstack/react-query";import { Link } from "@tanstack/react-router";-import { Fragment, useState } from "react";+import type * as React from "react";+import { useState } from "react";import { AbstractAvatar } from "@/components/agents/abstract-avatar";+import { BotNeedsYou } from "@/components/approvals/waiting";import { PageRows, PageSection } from "@/components/layout/page-shell";import { SharedAppNotice } from "@/components/plugins/shared-app-notice";+import { SuggestionsInbox } from "@/components/suggestions/proactive-panel";import { Button } from "@/components/ui/button";-import {- Dialog,- DialogBody,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from "@/components/ui/dialog";import {Item,ItemActions,ItemContent,ItemDescription,- ItemFooter,ItemMedia,ItemTitle,} from "@/components/ui/item";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";import { Separator } from "@/components/ui/separator";import { Switch } from "@/components/ui/switch";import type { AgentProfile } from "@/lib/agents/queries";import {- resetBotMutationOptions,setBotNotifyMutationOptions,setBotPausedMutationOptions,- setUpdateRoutingMutationOptions,} from "@/lib/bot-lifecycle/mutations";import {type BotNotify,botLifecycleQueryOptions,- botResetPlanQueryOptions,- type ResetPlan,- type UpdateKind,- type UpdateTransport,- updateRoutingQueryOptions,} from "@/lib/bot-lifecycle/queries";import { queryClient } from "@/query-client";import { BotActivitySections } from "./activity";@@ -58,213 +50,21 @@ const NOTIFY_LABEL: Record<BotNotify, string> = {none: "Nothing (badges only)",};-const KIND_LABEL: Record<UpdateKind, { title: string; description: string }> = {- progress: {- title: "Progress",- description: "Replies and results from work you were not watching.",- },- decision: {- title: "Decisions",- description: "Approvals a Bot needs before it acts.",- },- question: {- title: "Questions",- description: "Things a Bot asked you and is waiting on.",- },-};--const TRANSPORTS: { id: UpdateTransport; label: string }[] = [- { id: "push", label: "Push" },- { id: "slack", label: "Slack" },- { id: "teams", label: "Microsoft Teams" },- { id: "sms", label: "SMS" },-];--const selectClass = "h-8 rounded-md border bg-background px-2 text-sm";--/** Each count the notice lists, in the words the person reads, skipping the kinds with nothing. */-function resetLines(plan: ResetPlan): string[] {- const lines: [number, string, string][] = [- [plan.conversations, "conversation", "conversations"],- [plan.memorySources, "memory source", "memory sources"],- [plan.memories, "imported memory", "imported memories"],- [plan.routines, "routine", "routines"],- [plan.responsibilities, "responsibility", "responsibilities"],- [plan.followUps, "scheduled follow-up", "scheduled follow-ups"],- [plan.formedMemories, "memory it formed", "memories it formed"],- [plan.backgroundResearch, "background research", "background research"],- [plan.standingApprovals, "standing permission", "standing permissions"],- ];- return lines- .filter(([count]) => count > 0)- .map(([count, one, many]) => `${count} ${count === 1 ? one : many}`);-}--function ResetDialog({+/** A Bot's own page: its state for you, what it is doing, its settings, and what can be done to it. */+export function BotProfile({agent,- onOpenChange,- open,+ settings,+ manage,}: {agent: AgentProfile;- onOpenChange: (open: boolean) => void;- open: boolean;+ /** The "Settings for this Bot" card. */+ settings?: React.ReactNode;+ /** Pin, hide, duplicate, reset, delete. */+ manage?: React.ReactNode;}) {- const plan = useQuery({- ...botResetPlanQueryOptions(agent.id),- enabled: open,- });- const reset = useMutation(resetBotMutationOptions(queryClient));- const lines = plan.data ? resetLines(plan.data) : [];- return (- <Dialog onOpenChange={onOpenChange} open={open}>- <DialogContent>- <DialogHeader>- <DialogTitle>Reset {agent.name}?</DialogTitle>- <DialogDescription>- This deletes what {agent.name} has with you, and only with you.- Nobody else's conversations or data are touched. It cannot be- undone.- </DialogDescription>- </DialogHeader>- <DialogBody className="mt-4 overflow-y-auto">- {plan.isPending ? null : plan.error ? (- <p className="text-destructive text-sm" role="alert">- Could not count what a reset would delete.- </p>- ) : reset.isSuccess ? (- <p className="text-sm">Done. {agent.name} starts fresh with you.</p>- ) : (- <div className="grid gap-2 text-sm">- {lines.length === 0 ? (- <p>There is nothing of yours to delete.</p>- ) : (- <>- <p>This will delete:</p>- <ul className="list-disc pl-5">- {lines.map((line) => (- <li key={line}>{line}</li>- ))}- </ul>- </>- )}- {plan.data.sharedConversationsKept > 0 ? (- <p className="text-muted-foreground">- {plan.data.sharedConversationsKept} conversation- {plan.data.sharedConversationsKept === 1 ? " is" : "s are"}{" "}- shared with other people or Bots and will be kept.- </p>- ) : null}- <p className="text-muted-foreground">- Your own memories, the ones you told a Bot directly, are kept.- </p>- </div>- )}- {reset.error ? (- <p className="mt-2 text-destructive text-sm" role="alert">- {reset.error.message}- </p>- ) : null}- </DialogBody>- <DialogFooter className="mt-4">- <Button- onClick={() => onOpenChange(false)}- size="sm"- variant="outline"- >- {reset.isSuccess ? "Close" : "Cancel"}- </Button>- {reset.isSuccess ? null : (- <Button- disabled={!plan.data || lines.length === 0 || reset.isPending}- onClick={() => reset.mutate(agent.id)}- size="sm"- variant="destructive"- >- {reset.isPending ? "Resetting…" : "Delete and reset"}- </Button>- )}- </DialogFooter>- </DialogContent>- </Dialog>- );-}--function UpdateRoutingSection() {- const routing = useQuery(updateRoutingQueryOptions());- const save = useMutation(setUpdateRoutingMutationOptions(queryClient));- return (- <PageSection- description="Where each kind of update goes when you are not looking. The web always shows everything. Applies to all your Bots."- title="Where updates go"- >- {routing.isPending ? null : routing.error ? (- <p className="mt-4 text-destructive text-sm" role="alert">- Could not load where your updates go.- </p>- ) : (- <PageRows>- {(Object.keys(KIND_LABEL) as UpdateKind[]).map((kind, index) => {- const current = routing.data[kind];- const allowed = (transport: UpdateTransport) =>- current === "all" || current.includes(transport);- return (- <Fragment key={kind}>- {index > 0 ? <Separator /> : null}- <Item size="sm">- <ItemMedia variant="icon">- <IconRoute />- </ItemMedia>- <ItemContent>- <ItemTitle>{KIND_LABEL[kind].title}</ItemTitle>- <ItemDescription>- {KIND_LABEL[kind].description}- </ItemDescription>- </ItemContent>- <ItemFooter className="gap-4 pl-8">- {TRANSPORTS.map((transport) => (- <div- className="flex items-center gap-2 text-sm"- key={transport.id}- >- <Switch- aria-label={`${KIND_LABEL[kind].title} by ${transport.label}`}- checked={allowed(transport.id)}- disabled={save.isPending}- onCheckedChange={(checked) => {- const next = TRANSPORTS.map((t) => t.id).filter(- (id) =>- id === transport.id ? checked : allowed(id),- );- save.mutate({- kind,- transports:- next.length === TRANSPORTS.length- ? "all"- : next,- });- }}- size="sm"- />- {transport.label}- </div>- ))}- </ItemFooter>- </Item>- </Fragment>- );- })}- </PageRows>- )}- </PageSection>- );-}--/** A Bot's own page: its state for you, what it is doing, and the lifecycle controls. */-export function BotProfile({ agent }: { agent: AgentProfile }) {const lifecycle = useQuery(botLifecycleQueryOptions(agent.id));const pause = useMutation(setBotPausedMutationOptions(queryClient));const notify = useMutation(setBotNotifyMutationOptions(queryClient));- const [resetOpen, setResetOpen] = useState(false);const [permission, setPermission] = useState<string>(() => {try {return typeof Notification === "undefined"@@ -290,7 +90,13 @@ export function BotProfile({ agent }: { agent: AgentProfile }) {<BotPausedBanner agentId={agent.id} /></div>+ <BotNeedsYou agentId={agent.id} />+ <SuggestionsInbox agentId={agent.id} />+<PageSection title="For you">+ {/* Whether this Bot's Shared-app calls are being refused right now, with the button that+ asks an administrator. About its present reach, so it lives here, not only where+ publishing happens. */}{agent.canManage ? (<SharedAppNotice botId={agent.id} reason="publish" />) : null}@@ -305,20 +111,22 @@ export function BotProfile({ agent }: { agent: AgentProfile }) {<IconPlayerPause /></ItemMedia><ItemContent>- <ItemTitle>Paused</ItemTitle>+ {/* On means working, the way a responsibility's Active switch reads: titled "Paused",+ the row showed the word "Paused" beside a switch that was off for a running Bot. */}+ <ItemTitle>Active</ItemTitle><ItemDescription>{lifecycle.data.paused- ? "No routine, responsibility, hand-off or follow-up starts for you, and what was running has stopped."+ ? "Paused. No routine, responsibility, hand-off or follow-up starts for you, and what was running has stopped.": "Runs its routines, responsibilities, hand-offs and follow-ups for you."}</ItemDescription></ItemContent><ItemActions><Switch- aria-label="Paused"- checked={lifecycle.data.paused}+ aria-label="Active"+ checked={!lifecycle.data.paused}disabled={pause.isPending}- onCheckedChange={(paused) =>- pause.mutate({ agentId: agent.id, paused })+ onCheckedChange={(active) =>+ pause.mutate({ agentId: agent.id, paused: !active })}/></ItemActions>@@ -336,24 +144,30 @@ export function BotProfile({ agent }: { agent: AgentProfile }) {</ItemDescription></ItemContent><ItemActions>- <select- aria-label="Notifications"- className={selectClass}+ <Selectdisabled={notify.isPending}- onChange={(event) =>+ // The label map, so the closed trigger says "Everything" rather than the raw value.+ items={NOTIFY_LABEL}+ onValueChange={(next) => {+ if (next === lifecycle.data.notify) return;notify.mutate({agentId: agent.id,- notify: event.target.value as BotNotify,- })- }+ notify: next as BotNotify,+ });+ }}value={lifecycle.data.notify}>- {(Object.keys(NOTIFY_LABEL) as BotNotify[]).map((value) => (- <option key={value} value={value}>- {NOTIFY_LABEL[value]}- </option>- ))}- </select>+ <SelectTrigger aria-label="Notifications">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {(Object.keys(NOTIFY_LABEL) as BotNotify[]).map((value) => (+ <SelectItem key={value} value={value}>+ {NOTIFY_LABEL[value]}+ </SelectItem>+ ))}+ </SelectContent>+ </Select></ItemActions></Item>{permission === "default" ? (@@ -400,32 +214,17 @@ export function BotProfile({ agent }: { agent: AgentProfile }) {<ItemTitle>Message {agent.name}</ItemTitle><ItemDescription>Start a conversation.</ItemDescription></ItemContent>- </Item>- <Separator />- <Item- render={- <button onClick={() => setResetOpen(true)} type="button" />- }- size="sm"- >- <ItemMedia variant="icon">- <IconRefresh />- </ItemMedia>- <ItemContent>- <ItemTitle>Reset</ItemTitle>- <ItemDescription>- Delete your conversations with it, what it remembers for you,- and its scheduled work. You see what will go first.- </ItemDescription>- </ItemContent>+ <ItemActions>+ <IconChevronRight className="size-4 text-muted-foreground" />+ </ItemActions></Item></PageRows>)}</PageSection><BotActivitySections agentId={agent.id} />- <UpdateRoutingSection />- <ResetDialog agent={agent} onOpenChange={setResetOpen} open={resetOpen} />+ {settings}+ {manage}</>);}diff --git a/app/src/components/bot-profile/settings-rows.tsx b/app/src/components/bot-profile/settings-rows.tsxnew file mode 100644index 00000000..3bf70032--- /dev/null+++ b/app/src/components/bot-profile/settings-rows.tsx@@ -0,0 +1,212 @@+import {+ IconBrain,+ IconChecks,+ IconChevronRight,+ IconDeviceMobile,+ IconTargetArrow,+ IconClock,+ IconPuzzle,+ IconSettings,+ IconUsersGroup,+} from "@tabler/icons-react";+import { useQuery } from "@tanstack/react-query";+import { Link } from "@tanstack/react-router";+import { Fragment } from "react";+import { PageRows, PageSection } from "@/components/layout/page-shell";+import {+ Item,+ ItemActions,+ ItemContent,+ ItemDescription,+ ItemMedia,+ ItemTitle,+} from "@/components/ui/item";+import { Separator } from "@/components/ui/separator";+import {+ accessSummary,+ countLabel,+ memorySummary,+ reachSummary,+ setupSummary,+ sharingSummary,+} from "@/lib/agents/bot-summaries";+import type { AgentProfile } from "@/lib/agents/queries";+import { approvalInboxOptions, ruleCoversBot } from "@/lib/approvals";+import { currentUserQueryOptions } from "@/lib/auth/queries";+import { deliveryQueryOptions } from "@/lib/delivery";+import { memorySourcesQueryOptions } from "@/lib/memory";+import { proactiveSettingsQueryOptions } from "@/lib/proactive";+import { responsibilitiesQueryOptions } from "@/lib/responsibilities";+import { agentPluginsQueryOptions } from "@/lib/plugins/queries";+import { routinesQueryOptions } from "@/lib/routines/queries";+import { teamBotsQueryOptions } from "@/lib/team-bots";+import { connectorCount } from "./access";++type Row = {+ to:+ | "/bots/$agentId/responsibilities"+ | "/bots/$agentId/reach"+ | "/bots/$agentId/memory"+ | "/bots/$agentId/approvals"+ | "/bots/$agentId/routines"+ | "/bots/$agentId/access"+ | "/bots/$agentId/sharing"+ | "/bots/$agentId/setup";+ title: string;+ icon: typeof IconClock;+ summary: string;+};++/**+ * One row per area of this Bot's configuration, each stating its current answer and opening the page+ * that changes it. Sharing is for its owner, administrators, and anyone it is published to.+ */+export function BotSettingsRows({ agent }: { agent: AgentProfile }) {+ const me = useQuery(currentUserQueryOptions()).data;+ const routines = useQuery(routinesQueryOptions());+ const plugins = useQuery(agentPluginsQueryOptions(agent.id));+ const teamBots = useQuery(teamBotsQueryOptions());+ const published = teamBots.data?.teamBots.find((bot) => bot.id === agent.id);+ // Its owner and administrators change it there; anyone it is published to finds its link there.+ const canShare =+ agent.mine || me?.role === "admin" || published !== undefined;++ const goals = useQuery(responsibilitiesQueryOptions());+ const reach = useQuery(deliveryQueryOptions());+ const sources = useQuery(memorySourcesQueryOptions());+ const research = useQuery(proactiveSettingsQueryOptions());+ const approvals = useQuery(approvalInboxOptions());++ const rows: Row[] = [+ {+ to: "/bots/$agentId/responsibilities",+ title: "Responsibilities",+ icon: IconTargetArrow,+ summary: goals.data+ ? countLabel(+ goals.data.filter(+ (goal) => goal.agentId === agent.id && goal.status === "active",+ ).length,+ "active",+ "active",+ "None active",+ )+ : "",+ },+ {+ to: "/bots/$agentId/reach",+ title: "Reaching you",+ icon: IconDeviceMobile,+ summary: reach.data+ ? reachSummary(+ reach.data.bindings+ .filter(+ (binding) => binding.enabled && binding.agentId === agent.id,+ )+ .map((binding) => binding.transport),+ )+ : "",+ },+ {+ to: "/bots/$agentId/memory",+ title: "Memory",+ icon: IconBrain,+ summary:+ sources.data && research.data+ ? memorySummary(+ sources.data.filter((source) => source.agentId === agent.id)+ .length,+ research.data.some(+ (setting) => setting.agentId === agent.id && setting.enabled,+ ),+ )+ : "",+ },+ {+ to: "/bots/$agentId/approvals",+ title: "Approval rules",+ icon: IconChecks,+ summary: approvals.data+ ? countLabel(+ approvals.data.rules.filter(+ (rule) =>+ rule.botId !== "*" && ruleCoversBot(rule.botId, agent.id),+ ).length,+ "rule",+ "rules",+ "No rules",+ )+ : "",+ },+ {+ to: "/bots/$agentId/routines",+ title: "Routines",+ icon: IconClock,+ summary: routines.data+ ? countLabel(+ routines.data.routines.filter((row) => row.agentId === agent.id)+ .length,+ "routine",+ "routines",+ "No routines",+ )+ : "",+ },+ {+ to: "/bots/$agentId/access",+ title: "Skills and access",+ icon: IconPuzzle,+ summary: plugins.data+ ? accessSummary(+ plugins.data.skills.length,+ connectorCount(plugins.data),+ )+ : "",+ },+ ...(canShare+ ? [+ {+ to: "/bots/$agentId/sharing" as const,+ title: "Sharing",+ icon: IconUsersGroup,+ summary: teamBots.data+ ? sharingSummary(published, agent.visibility)+ : "",+ },+ ]+ : []),+ {+ to: "/bots/$agentId/setup",+ title: "Setup",+ icon: IconSettings,+ summary: setupSummary(agent),+ },+ ];++ return (+ <PageSection title="Settings for this Bot">+ <PageRows>+ {rows.map(({ to, title, icon: Icon, summary }, index) => (+ <Fragment key={to}>+ {index > 0 ? <Separator /> : null}+ <Item+ render={<Link params={{ agentId: agent.id }} to={to} />}+ size="sm"+ >+ <ItemMedia variant="icon">+ <Icon />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>{title}</ItemTitle>+ <ItemDescription>{summary}</ItemDescription>+ </ItemContent>+ <ItemActions>+ <IconChevronRight className="size-4 text-muted-foreground" />+ </ItemActions>+ </Item>+ </Fragment>+ ))}+ </PageRows>+ </PageSection>+ );+}diff --git a/app/src/components/bot-profile/setup.tsx b/app/src/components/bot-profile/setup.tsxnew file mode 100644index 00000000..c79643fc--- /dev/null+++ b/app/src/components/bot-profile/setup.tsx@@ -0,0 +1,343 @@+import {+ IconChevronRight,+ IconEye,+ IconId,+ IconPlugConnected,+ IconShieldCheck,+ IconTag,+ IconTextCaption,+} from "@tabler/icons-react";+import { useMutation } from "@tanstack/react-query";+import { Fragment, useState } from "react";+import type { ZodType } from "zod";+import { CallbackTokenPanel } from "@/components/agents/callback-token-panel";+import { PageRows, PageSection } from "@/components/layout/page-shell";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogBody,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import {+ Item,+ ItemActions,+ ItemContent,+ ItemDescription,+ ItemMedia,+ ItemTitle,+} from "@/components/ui/item";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { Separator } from "@/components/ui/separator";+import { Textarea } from "@/components/ui/textarea";+import {+ type AgentFormValues,+ agentFormSchema,+ profileUpdateInput,+} from "@/lib/agents/form";+import { updateAgentMutationOptions } from "@/lib/agents/mutations";+import type { AgentProfile } from "@/lib/agents/queries";+import { isComposing } from "@/lib/composing";+import { queryClient } from "@/query-client";++type TextField = "name" | "title" | "roleDescription";++const TEXT_FIELDS: {+ field: TextField;+ label: string;+ icon: typeof IconId;+ multiline?: boolean;+}[] = [+ { field: "name", label: "Name", icon: IconId },+ { field: "title", label: "Title", icon: IconTag },+ {+ field: "roleDescription",+ label: "Role",+ icon: IconTextCaption,+ multiline: true,+ },+];++/** Who a Bot is and where it runs. Editable by whoever may manage it; read-only for everyone else. */+export function SetupSections({ agent }: { agent: AgentProfile }) {+ const update = useMutation(updateAgentMutationOptions(queryClient));+ const [editing, setEditing] = useState<TextField | null>(null);+ const save = (patch: Partial<AgentFormValues>) =>+ update.mutateAsync({+ agentId: agent.id,+ input: profileUpdateInput(agent, patch),+ });+ const open = TEXT_FIELDS.find((entry) => entry.field === editing);++ return (+ <>+ <PageSection title="Identity">+ <PageRows>+ {TEXT_FIELDS.map(({ field, label, icon: Icon }, index) => (+ <Fragment key={field}>+ {index > 0 ? <Separator /> : null}+ <Item+ render={+ agent.canManage ? (+ <button onClick={() => setEditing(field)} type="button" />+ ) : undefined+ }+ size="sm"+ >+ <ItemMedia variant="icon">+ <Icon />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>{label}</ItemTitle>+ <ItemDescription>{agent[field]}</ItemDescription>+ </ItemContent>+ {agent.canManage ? (+ <ItemActions>+ <IconChevronRight className="size-4 text-muted-foreground" />+ </ItemActions>+ ) : null}+ </Item>+ </Fragment>+ ))}+ <Separator />+ <VisibilityRow+ agent={agent}+ onSave={(visibility) => save({ visibility })}+ />+ {agent.systemOwned ? (+ <>+ <Separator />+ <Item size="sm">+ <ItemMedia variant="icon">+ <IconShieldCheck />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>System owned</ItemTitle>+ <ItemDescription>+ Ships with this deployment rather than belonging to a+ person.+ </ItemDescription>+ </ItemContent>+ </Item>+ </>+ ) : null}+ </PageRows>+ </PageSection>+ <ConnectionSection agent={agent} />+ {open ? (+ <EditTextDialog+ label={open.label}+ multiline={open.multiline ?? false}+ onClose={() => setEditing(null)}+ onSave={(value) => save({ [open.field]: value })}+ schema={agentFormSchema.shape[open.field]}+ value={agent[open.field]}+ />+ ) : null}+ </>+ );+}++/** Two named choices that write on pick: no draft worth holding, so no dialog. */+function VisibilityRow({+ agent,+ onSave,+}: {+ agent: AgentProfile;+ onSave: (visibility: AgentProfile["visibility"]) => Promise<unknown>;+}) {+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState<string | null>(null);+ return (+ <Item size="sm">+ <ItemMedia variant="icon">+ <IconEye />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>Visibility</ItemTitle>+ <ItemDescription>+ {error ??+ (agent.visibility === "private"+ ? "Only you can see it and start conversations with it."+ : "Everyone in the deployment can find and use it.")}+ </ItemDescription>+ </ItemContent>+ <ItemActions>+ {agent.canManage ? (+ <Select+ disabled={saving}+ // The label map, so the closed trigger says "Private" rather than the raw value.+ items={{ private: "Private", public: "Public" }}+ onValueChange={async (next) => {+ if (next === agent.visibility) return;+ setError(null);+ setSaving(true);+ try {+ await onSave(next as AgentProfile["visibility"]);+ } catch (failure) {+ setError(+ failure instanceof Error+ ? failure.message+ : "Could not save.",+ );+ } finally {+ setSaving(false);+ }+ }}+ value={agent.visibility}+ >+ <SelectTrigger className="w-28">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="private">Private</SelectItem>+ <SelectItem value="public">Public</SelectItem>+ </SelectContent>+ </Select>+ ) : (+ <span className="text-muted-foreground text-sm">+ {agent.visibility === "private" ? "Private" : "Public"}+ </span>+ )}+ </ItemActions>+ </Item>+ );+}++/**+ * One text field in a dialog, validated against the same limits the server enforces. Enter saves a+ * single-line field — but not the Enter that confirms a composed character, which would save the+ * value before the person finished typing it.+ */+function EditTextDialog({+ label,+ value,+ multiline,+ schema,+ onSave,+ onClose,+}: {+ label: string;+ value: string;+ multiline: boolean;+ schema: ZodType<string>;+ onSave: (value: string) => Promise<unknown>;+ onClose: () => void;+}) {+ const [draft, setDraft] = useState(value);+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const submit = async () => {+ const parsed = schema.safeParse(draft);+ if (!parsed.success) {+ setError(parsed.error.issues[0]?.message ?? "That value does not fit.");+ return;+ }+ setSaving(true);+ try {+ await onSave(parsed.data);+ onClose();+ } catch (failure) {+ setError(failure instanceof Error ? failure.message : "Could not save.");+ } finally {+ setSaving(false);+ }+ };+ return (+ <Dialog onOpenChange={(next) => !next && onClose()} open>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{label}</DialogTitle>+ </DialogHeader>+ <DialogBody className="mt-4 grid gap-2">+ {multiline ? (+ <Textarea+ aria-label={label}+ autoFocus+ onChange={(event) => setDraft(event.target.value)}+ rows={5}+ value={draft}+ />+ ) : (+ <Input+ aria-label={label}+ autoFocus+ onChange={(event) => setDraft(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Enter" && !isComposing(event)) {+ event.preventDefault();+ void submit();+ }+ }}+ value={draft}+ />+ )}+ {error ? (+ <p className="text-destructive text-sm" role="alert">+ {error}+ </p>+ ) : null}+ </DialogBody>+ <DialogFooter className="mt-4">+ <Button+ disabled={saving}+ onClick={onClose}+ size="sm"+ variant="outline"+ >+ Cancel+ </Button>+ <Button disabled={saving} onClick={() => void submit()} size="sm">+ {saving ? "Saving…" : "Save"}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}++/**+ * Where it runs. A built-in Bot runs on the deployment's own Bot, whose process already holds the+ * deployment's tool credential, so there is nothing to show but that sentence.+ */+function ConnectionSection({ agent }: { agent: AgentProfile }) {+ const builtIn = !agent.endpoint || agent.builtIn;+ return (+ <PageSection title="Connection">+ <PageRows>+ <Item size="sm">+ <ItemMedia variant="icon">+ <IconPlugConnected />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>{builtIn ? "Built in" : "Endpoint"}</ItemTitle>+ <ItemDescription+ className={+ builtIn ? undefined : "line-clamp-none break-all font-mono"+ }+ >+ {builtIn+ ? "Runs on this deployment's own Bot. Nothing to connect and nothing to authenticate."+ : agent.endpoint}+ </ItemDescription>+ </ItemContent>+ </Item>+ </PageRows>+ {!builtIn && agent.canManage ? (+ <CallbackTokenPanel+ agentId={agent.id}+ hasToken={agent.hasCallbackToken}+ />+ ) : null}+ </PageSection>+ );+}diff --git a/app/src/components/bot-profile/sharing.tsx b/app/src/components/bot-profile/sharing.tsxnew file mode 100644index 00000000..5a2e7d38--- /dev/null+++ b/app/src/components/bot-profile/sharing.tsx@@ -0,0 +1,470 @@+import {+ IconChevronRight,+ IconLink,+ IconPlus,+ IconUsers,+ IconUsersGroup,+} from "@tabler/icons-react";+import { useMutation, useQuery } from "@tanstack/react-query";+import { Fragment, useId, useState } from "react";+import {+ PageEmpty,+ PageRows,+ PageSection,+} from "@/components/layout/page-shell";+import { SharedAppNotice } from "@/components/plugins/shared-app-notice";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Field, FieldGroup, FieldLabel } from "@/components/ui/field";+import { Input } from "@/components/ui/input";+import {+ Item,+ ItemActions,+ ItemContent,+ ItemDescription,+ ItemMedia,+ ItemTitle,+} from "@/components/ui/item";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { Separator } from "@/components/ui/separator";+import { countLabel } from "@/lib/agents/bot-summaries";+import type { AgentProfile } from "@/lib/agents/queries";+import { currentUserQueryOptions } from "@/lib/auth/queries";+import {+ assignTeamBotMutationOptions,+ publishTeamBotMutationOptions,+ type TeamBot,+ teamBotLink,+ teamBotsQueryOptions,+ unpublishTeamBotMutationOptions,+} from "@/lib/team-bots";+import { queryClient } from "@/query-client";++const list = (value: string) =>+ value+ .split(",")+ .map((part) => part.trim())+ .filter(Boolean);++/**+ * Who else can use this Bot. Its owner publishes it to the whole team or to named people and groups;+ * an administrator can also pin it at the top of a group's Bots lists. Each chat with a published+ * Bot is private to the person having it; its owner cannot read it.+ */+export function SharingSections({ agent }: { agent: AgentProfile }) {+ const data = useQuery(teamBotsQueryOptions());+ const me = useQuery(currentUserQueryOptions()).data;+ const unpublish = useMutation(unpublishTeamBotMutationOptions(queryClient));+ const [copied, setCopied] = useState(false);+ const [publishing, setPublishing] = useState(false);+ if (data.isPending) return null;+ if (data.error) {+ return (+ <p className="mt-6 text-destructive text-sm" role="alert">+ {data.error.message}+ </p>+ );+ }+ const published = data.data.teamBots.find((bot) => bot.id === agent.id);+ const publishable = data.data.publishable.some((bot) => bot.id === agent.id);++ return (+ <>+ <PageSection title="Published">+ {unpublish.error ? (+ <p className="mt-4 text-destructive text-sm" role="alert">+ {unpublish.error.message}+ </p>+ ) : null}+ {published ? (+ <PageRows>+ <Item size="sm">+ <ItemMedia variant="icon">+ <IconUsersGroup />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>+ {published.audience === "team"+ ? "To the whole team"+ : `To ${[...(published.people ?? []), ...(published.groups ?? []).map((group) => `group ${group}`)].join(", ")}`}+ </ItemTitle>+ <ItemDescription>+ {published.visibleToTeam+ ? "Each chat with it is private to the person having it."+ : "Hidden from teammates until it has a real name and a description."}+ </ItemDescription>+ </ItemContent>+ {agent.mine ? (+ <ItemActions>+ <Button+ disabled={unpublish.isPending}+ onClick={() => unpublish.mutate(agent.id)}+ size="sm"+ variant="outline"+ >+ Unpublish+ </Button>+ </ItemActions>+ ) : null}+ </Item>+ <Separator />+ <Item size="sm">+ <ItemMedia variant="icon">+ <IconLink />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>Link</ItemTitle>+ <ItemDescription>Opens a private chat with it.</ItemDescription>+ </ItemContent>+ <ItemActions>+ <Button+ onClick={() =>+ void navigator.clipboard+ .writeText(teamBotLink(agent.id))+ .then(() => setCopied(true))+ }+ size="sm"+ variant="outline"+ >+ {copied ? "Copied" : "Copy link"}+ </Button>+ </ItemActions>+ </Item>+ </PageRows>+ ) : (+ <PageEmpty>+ {agent.visibility === "public"+ ? "Not published to the team. It is public, so everyone in the deployment can already use it."+ : agent.mine+ ? "Not published. Only you can use it."+ : "Not published."}+ </PageEmpty>+ )}+ </PageSection>+ {agent.mine && (published || publishable) ? (+ <PageSection+ description="Publishing does not change its visibility, and it can be undone."+ title={published ? "Who it is published to" : "Publish"}+ >+ {/* More than one value — an audience, then people and groups — so a summary row and a+ dialog rather than a form on the page. */}+ <PageRows>+ <Item+ render={+ <button onClick={() => setPublishing(true)} type="button" />+ }+ size="sm"+ >+ <ItemMedia variant="icon">+ <IconUsersGroup />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>Audience</ItemTitle>+ <ItemDescription>{audienceSummary(published)}</ItemDescription>+ </ItemContent>+ <ItemActions>+ <IconChevronRight className="size-4 text-muted-foreground" />+ </ItemActions>+ </Item>+ </PageRows>+ {publishing ? (+ <PublishDialog+ botId={agent.id}+ current={published}+ onClose={() => setPublishing(false)}+ />+ ) : null}+ </PageSection>+ ) : null}+ {me?.role === "admin" && published ? (+ <PageSection+ description="An assigned Bot is pinned at the top of every member's Bots list. Use * for the whole team."+ title="Assign to groups"+ >+ <Assignments bot={published} />+ </PageSection>+ ) : null}+ </>+ );+}++/** The current answer on the Audience row: who it is published to, as a count. */+function audienceSummary(current: TeamBot | undefined): string {+ if (!current) return "Not published";+ if (current.audience === "team") return "The whole team";+ const parts = [+ countLabel(current.people?.length ?? 0, "person", "people", ""),+ countLabel(current.groups?.length ?? 0, "group", "groups", ""),+ ].filter(Boolean);+ return parts.length ? parts.join(", ") : "Specific people or groups";+}++const AUDIENCES = {+ team: "The whole team",+ people: "Specific people or groups",+} as const;++/**+ * Who a Bot is published to: the whole team, or named people and groups. Mounted only while open,+ * so each opening starts from the current answer rather than from an abandoned edit.+ */+function PublishDialog({+ botId,+ current,+ onClose,+}: {+ botId: string;+ current?: TeamBot;+ onClose: () => void;+}) {+ const formId = useId();+ const publish = useMutation(publishTeamBotMutationOptions(queryClient));+ const [audience, setAudience] = useState<"team" | "people">(+ current?.audience ?? "team",+ );+ const [emails, setEmails] = useState((current?.people ?? []).join(", "));+ const [groups, setGroups] = useState((current?.groups ?? []).join(", "));+ return (+ <Dialog onOpenChange={(next) => !next && onClose()} open>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>+ {current ? "Who it is published to" : "Publish"}+ </DialogTitle>+ <DialogDescription>+ Publishing does not change its visibility, and it can be undone.+ </DialogDescription>+ </DialogHeader>+ <DialogBody className="mt-4 overflow-y-auto">+ {/* The submit button is in the footer and reaches this form by id, so DialogBody stays a+ direct child of DialogContent and keeps scrolling. */}+ <form+ id={formId}+ onSubmit={(event) => {+ event.preventDefault();+ publish.mutate(+ {+ botId,+ audience,+ emails: audience === "people" ? list(emails) : [],+ groups: audience === "people" ? list(groups) : [],+ },+ { onSuccess: onClose },+ );+ }}+ >+ <FieldGroup>+ <Field>+ <FieldLabel htmlFor={`${formId}-audience`}>+ Published to+ </FieldLabel>+ <Select+ items={AUDIENCES}+ onValueChange={(value) => {+ if (value === "team" || value === "people") {+ setAudience(value);+ }+ }}+ value={audience}+ >+ <SelectTrigger className="w-full" id={`${formId}-audience`}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {(Object.keys(AUDIENCES) as (keyof typeof AUDIENCES)[]).map(+ (value) => (+ <SelectItem key={value} value={value}>+ {AUDIENCES[value]}+ </SelectItem>+ ),+ )}+ </SelectContent>+ </Select>+ </Field>+ {audience === "people" ? (+ <>+ <Field>+ <FieldLabel htmlFor={`${formId}-people`}>+ People, by email+ </FieldLabel>+ <Input+ id={`${formId}-people`}+ onChange={(event) => setEmails(event.target.value)}+ placeholder="Comma separated"+ value={emails}+ />+ </Field>+ <Field>+ <FieldLabel htmlFor={`${formId}-groups`}>Groups</FieldLabel>+ <Input+ id={`${formId}-groups`}+ onChange={(event) => setGroups(event.target.value)}+ placeholder="Comma separated"+ value={groups}+ />+ </Field>+ </>+ ) : null}+ <SharedAppNotice botId={botId} reason="publish" />+ </FieldGroup>+ </form>+ {publish.error ? (+ <p className="mt-4 text-destructive text-sm" role="alert">+ {publish.error.message}+ </p>+ ) : null}+ </DialogBody>+ <DialogFooter className="mt-4">+ <Button onClick={onClose} size="sm" type="button" variant="outline">+ Cancel+ </Button>+ <Button+ disabled={publish.isPending}+ form={formId}+ size="sm"+ type="submit"+ >+ {current ? "Update" : "Publish to team"}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}++/**+ * The groups an administrator has pinned this Bot for: one row each with a Remove, and a row that+ * opens a dialog to add one.+ */+function Assignments({ bot }: { bot: TeamBot }) {+ const remove = useMutation(assignTeamBotMutationOptions(queryClient));+ const [assigning, setAssigning] = useState(false);+ const assigned = bot.assignments ?? [];+ return (+ <>+ {remove.error ? (+ <p className="mt-4 text-destructive text-sm" role="alert">+ {remove.error.message}+ </p>+ ) : null}+ {assigned.length === 0 ? (+ <PageEmpty>Not assigned to any group.</PageEmpty>+ ) : null}+ <PageRows>+ {assigned.map((name) => (+ <Fragment key={name}>+ <Item size="sm">+ <ItemMedia variant="icon">+ <IconUsers />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>{name === "*" ? "Whole team" : name}</ItemTitle>+ </ItemContent>+ <ItemActions>+ <Button+ aria-label={`Remove ${name}`}+ disabled={remove.isPending}+ onClick={() =>+ remove.mutate({ botId: bot.id, group: name, remove: true })+ }+ size="sm"+ variant="outline"+ >+ Remove+ </Button>+ </ItemActions>+ </Item>+ <Separator />+ </Fragment>+ ))}+ <Item+ render={<button onClick={() => setAssigning(true)} type="button" />}+ size="sm"+ >+ <ItemMedia variant="icon">+ <IconPlus />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>Assign to a group</ItemTitle>+ </ItemContent>+ <ItemActions>+ <IconChevronRight className="size-4 text-muted-foreground" />+ </ItemActions>+ </Item>+ </PageRows>+ {assigning ? (+ <AssignDialog bot={bot} onClose={() => setAssigning(false)} />+ ) : null}+ </>+ );+}++/** One group to pin this Bot for, or * for the whole team. */+function AssignDialog({ bot, onClose }: { bot: TeamBot; onClose: () => void }) {+ const formId = useId();+ const assign = useMutation(assignTeamBotMutationOptions(queryClient));+ const [group, setGroup] = useState("");+ return (+ <Dialog onOpenChange={(next) => !next && onClose()} open>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Assign {bot.name} to a group</DialogTitle>+ <DialogDescription>+ It is pinned at the top of every member's Bots list.+ </DialogDescription>+ </DialogHeader>+ <DialogBody className="mt-4">+ <form+ id={formId}+ onSubmit={(event) => {+ event.preventDefault();+ assign.mutate({ botId: bot.id, group }, { onSuccess: onClose });+ }}+ >+ <Field>+ <FieldLabel htmlFor={`${formId}-group`}>Group, or *</FieldLabel>+ <Input+ id={`${formId}-group`}+ onChange={(event) => setGroup(event.target.value)}+ placeholder="* for the whole team"+ value={group}+ />+ </Field>+ </form>+ {assign.error ? (+ <p className="mt-4 text-destructive text-sm" role="alert">+ {assign.error.message}+ </p>+ ) : null}+ </DialogBody>+ <DialogFooter className="mt-4">+ <Button onClick={onClose} size="sm" type="button" variant="outline">+ Cancel+ </Button>+ <Button+ disabled={!group.trim() || assign.isPending}+ form={formId}+ size="sm"+ type="submit"+ >+ Assign+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/app/src/components/bots/bot-roster.tsx b/app/src/components/bots/bot-roster.tsxnew file mode 100644index 00000000..cb595dd5--- /dev/null+++ b/app/src/components/bots/bot-roster.tsx@@ -0,0 +1,179 @@+import { IconChevronRight } from "@tabler/icons-react";+import { useQuery } from "@tanstack/react-query";+import { Link } from "@tanstack/react-router";+import { Fragment, useState } from "react";+import { AbstractAvatar } from "@/components/agents/abstract-avatar";+import {+ attentionSummary,+ needsInput,+} from "@/components/bot-profile/attention";+import {+ PageEmpty,+ PageRows,+ PageSection,+} from "@/components/layout/page-shell";+import { Button } from "@/components/ui/button";+import {+ Item,+ ItemActions,+ ItemContent,+ ItemDescription,+ ItemMedia,+ ItemTitle,+} from "@/components/ui/item";+import { Separator } from "@/components/ui/separator";+import { type AgentProfile, agentListQueryOptions } from "@/lib/agents/queries";+import { groupRoster } from "@/lib/agents/roster";+import {+ type BotAttention,+ botAttentionQueryOptions,+} from "@/lib/bot-lifecycle/queries";++/**+ * Every Bot the person can reach, in the one place they are listed: pinned first, then their own,+ * then the ones shared with them, and the ones they hid folded away at the end.+ *+ * This replaces three screens — Bots, Agents and Team Bots — that listed the same Bots three ways.+ */+export function BotRoster() {+ const agents = useQuery(agentListQueryOptions());+ const hidden = useQuery(agentListQueryOptions(true));+ const attention = useQuery(botAttentionQueryOptions());+ const byId = new Map((attention.data ?? []).map((bot) => [bot.agentId, bot]));++ if (agents.isPending) return null;+ // Only when nothing ever loaded: a failed background refetch keeps the roster it had.+ if (agents.data === undefined) {+ return (+ <p className="mt-6 text-destructive text-sm" role="alert">+ Could not load your Bots.+ </p>+ );+ }+ const { needsYou, pinned, yours, shared } = groupRoster(+ agents.data,+ (agentId) => {+ const state = byId.get(agentId);+ return state ? needsInput(state) : 0;+ },+ );+ const yoursPinned = pinned.some((agent) => agent.mine);+ const yoursWaiting = needsYou.some((agent) => agent.mine);++ return (+ <>+ {needsYou.length ? (+ <PageSection title="Needs you">+ <RosterRows agents={needsYou} byId={byId} />+ </PageSection>+ ) : null}+ {pinned.length ? (+ <PageSection title="Pinned">+ <RosterRows agents={pinned} byId={byId} />+ </PageSection>+ ) : null}+ <PageSection title="Yours">+ {yours.length ? (+ <RosterRows agents={yours} byId={byId} />+ ) : (+ <PageEmpty>+ {yoursPinned+ ? "Your Bots are all pinned above."+ : yoursWaiting+ ? "Your Bots are all under Needs you."+ : "You have no Bots of your own yet."}+ </PageEmpty>+ )}+ </PageSection>+ <PageSection title="Shared with you">+ {shared.length ? (+ <RosterRows agents={shared} byId={byId} />+ ) : (+ <PageEmpty>Nobody has shared a Bot with you yet.</PageEmpty>+ )}+ </PageSection>+ {hidden.data?.length ? (+ <HiddenSection agents={hidden.data} byId={byId} />+ ) : null}+ </>+ );+}++/**+ * The Bots this person hid, folded until asked for: a way back for somebody who hid something, not+ * a fourth list everybody reads past. A Bot's page is where Unhide lives.+ */+function HiddenSection({+ agents,+ byId,+}: {+ agents: AgentProfile[];+ byId: Map<string, BotAttention>;+}) {+ const [open, setOpen] = useState(false);+ return (+ <PageSection+ action={+ <Button onClick={() => setOpen(!open)} size="sm" variant="ghost">+ {open ? "Hide" : "Show"}+ </Button>+ }+ description={`${agents.length} ${agents.length === 1 ? "Bot" : "Bots"} you took off this list. Nobody else's list changed.`}+ title="Hidden"+ >+ {open ? <RosterRows agents={agents} byId={byId} /> : null}+ </PageSection>+ );+}++function RosterRows({+ agents,+ byId,+}: {+ agents: AgentProfile[];+ byId: Map<string, BotAttention>;+}) {+ return (+ <PageRows>+ {agents.map((agent, index) => {+ const state = byId.get(agent.id);+ const summary = state+ ? [state.paused ? "Paused" : "", attentionSummary(state)]+ .filter(Boolean)+ .join(" · ")+ : "";+ return (+ <Fragment key={agent.id}>+ {index > 0 ? <Separator /> : null}+ <Item+ render={+ <Link params={{ agentId: agent.id }} to="/bots/$agentId" />+ }+ size="sm"+ >+ <ItemMedia>+ <AbstractAvatar+ name={agent.name}+ seed={agent.avatarSeed}+ size={28}+ />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>{agent.name}</ItemTitle>+ <ItemDescription>{summary || agent.title}</ItemDescription>+ </ItemContent>+ <ItemActions>+ {state && needsInput(state) > 0 ? (+ <span className="rounded-full bg-primary px-1.5 text-[11px] font-medium text-primary-foreground tabular-nums">+ {needsInput(state)}+ </span>+ ) : null}+ <IconChevronRight className="size-4 text-muted-foreground" />+ </ItemActions>+ </Item>+ </Fragment>+ );+ })}+ </PageRows>+ );+}diff --git a/app/src/components/channels/avatar.tsx b/app/src/components/channels/avatar.tsxindex 11a19e22..44487201 100644--- a/app/src/components/channels/avatar.tsx+++ b/app/src/components/channels/avatar.tsx@@ -21,31 +21,11 @@ export const ChannelAvatar = memo(function ChannelAvatar({size?: number;typing?: boolean;}) {- const channelSize = participantIds?.length;-const avatar =- channelSize === 1 ? (+ participantIds.length === 1 ? (<Avatar className="size-full" name={participantIds[0]} size={size} />) : (- <div className="flex flex-row items-center size-full">- {participantIds.slice(0, 3).map((c, i, shown) => (- <div- className="shrink-0 border-2 border-sidebar rounded-full flex items-center justify-center"- key={c}- style={{- height: size / (shown.length / 2),- width: size / (shown.length / 2),- transform: `translateX(${i * -75}%)`,- }}- >- <Avatar- className="size-full"- name={c}- size={size / (shown.length / 2)}- />- </div>- ))}- </div>+ <GroupFaces participantIds={participantIds} size={size} />);return (@@ -56,6 +36,75 @@ export const ChannelAvatar = memo(function ChannelAvatar({);});+/** Where each face sits in a group's avatar, as fractions of its size, back to front. */+const LAYOUTS = {+ 2: {+ diameter: 0.68,+ at: [+ [0, 0],+ [0.32, 0.32],+ ],+ },+ 3: {+ diameter: 0.56,+ at: [+ [0.22, 0],+ [0, 0.44],+ [0.44, 0.44],+ ],+ },+} as const;++/**+ * A group's first two or three Bots, overlapping inside the avatar's own square so the row around+ * it keeps its layout. Each face is cut out where a later one covers it, leaving a gap that reads+ * on any background — selected, hovered, or the conversation's header.+ */+function GroupFaces({+ participantIds,+ size,+}: {+ participantIds: string[];+ size: number;+}) {+ const shown = participantIds.slice(0, 3);+ const layout = LAYOUTS[shown.length === 2 ? 2 : 3];+ const diameter = Math.round(size * layout.diameter);+ const gap = Math.max(1, size * 0.05);+ const at = layout.at.map(([x, y]) => [x * size, y * size]);+ return (+ <div className="relative size-full">+ {shown.map((id, i) => {+ const cuts = at.slice(i + 1).map(([x, y]) => {+ const cx = x - at[i][0] + diameter / 2;+ const cy = y - at[i][1] + diameter / 2;+ const r = diameter / 2 + gap;+ return `radial-gradient(circle at ${cx}px ${cy}px, transparent ${r}px, #000 ${r + 0.5}px)`;+ });+ const mask = cuts.length > 0 ? cuts.join(", ") : undefined;+ return (+ <div+ className="absolute overflow-hidden rounded-full"+ key={id}+ style={{+ left: at[i][0],+ top: at[i][1],+ height: diameter,+ width: diameter,+ maskImage: mask,+ WebkitMaskImage: mask,+ maskComposite: "intersect",+ WebkitMaskComposite: "source-in",+ }}+ >+ <Avatar className="size-full" name={id} size={diameter} />+ </div>+ );+ })}+ </div>+ );+}+/*** Three bouncing dots in a small badge, ringed in the sidebar's own colour so it sits on the* avatar as a badge rather than floating over it. The staggered negative delays start each dot atdiff --git a/app/src/components/channels/compose-state.ts b/app/src/components/channels/compose-state.tsindex cdf31544..e55f873d 100644--- a/app/src/components/channels/compose-state.ts+++ b/app/src/components/channels/compose-state.ts@@ -10,13 +10,12 @@ export type Recipient = {};/**- * One coworker per channel.- *- * Matches the chat screen's current one-coworker render contract.+ * How many Bots one new conversation may hold: the server's limit for a group. One Bot is an+ * ordinary conversation; two or more are a group, answering in the order they were picked.*/-export const MAX_RECIPIENTS = 1;+export const MAX_RECIPIENTS = 20;-/** Add a coworker, replacing the oldest once the channel recipient cap is reached. */+/** Add a Bot after the others, dropping the earliest once the cap is reached. */export function addRecipient(current: readonly Recipient[],next: Recipient,@@ -34,10 +33,35 @@ export function removeRecipient(return current.filter((recipient) => recipient.id !== id);}-/** Whether this draft can start a channel. */+/** Whether this draft can start a conversation. */export function canSend(recipients: readonly Recipient[],text: string,): boolean {- return recipients.length === MAX_RECIPIENTS && text.trim().length > 0;+ return (+ recipients.length >= 1 &&+ recipients.length <= MAX_RECIPIENTS &&+ text.trim().length > 0+ );+}++/** Whether these recipients make a group rather than a conversation with one Bot. */+export function startsGroup(recipients: readonly Recipient[]): boolean {+ return recipients.length > 1;+}++/**+ * What the To: field holds after the picker reports a change.+ *+ * The picker clears every selection on Escape once its list is closed, which would throw away a+ * group someone spent a while choosing in the moment they meant to dismiss a list. That one kind of+ * change is ignored; picks and removals are kept, at most `MAX_RECIPIENTS` of them.+ */+export function toFieldChange<T>(+ current: readonly T[],+ next: readonly T[],+ reason: string,+): T[] {+ if (reason === "escape-key") return [...current];+ return next.slice(-MAX_RECIPIENTS);}diff --git a/app/src/components/channels/group-chat.tsx b/app/src/components/channels/group-chat.tsxindex dfc81bb9..7f501bc2 100644--- a/app/src/components/channels/group-chat.tsx+++ b/app/src/components/channels/group-chat.tsx@@ -1,6 +1,6 @@import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import { Link } from "@tanstack/react-router";-import { useEffect, useRef, useState } from "react";+import { useEffect, useRef } from "react";import { Streamdown } from "streamdown";import { Bubble, BubbleContent } from "@/components/ui/bubble";import {@@ -8,13 +8,8 @@ import {MessageHeader,Message as MessageRow,} from "@/components/ui/message";-import { Button } from "@/components/ui/button";-import { Input } from "@/components/ui/input";import { currentUserQueryOptions } from "@/lib/auth/queries";import {- addGroupMemberMutationOptions,- type GroupPerson,- removeGroupMemberMutationOptions,type GroupMessage,groupQueryOptions,sendGroupMessageMutationOptions,@@ -65,7 +60,7 @@ export function GroupChat({ channelId }: { channelId: string }) {return (<div className="flex min-h-0 flex-1 flex-col"><div className="min-h-0 flex-1 overflow-y-auto">- <div className="mx-auto flex w-full max-w-3xl flex-col gap-5 px-4 py-6">+ <div className="mx-auto flex w-full max-w-2xl flex-col gap-5 py-6">{messages.length === 0 ? (<p className="text-sm text-muted-foreground">Say something to {bots.map((bot) => bot.name).join(" and ")}.@@ -94,21 +89,18 @@ export function GroupChat({ channelId }: { channelId: string }) {<div ref={endRef} /></div></div>- <div className="mx-auto w-full max-w-3xl px-4 pb-4">+ {/* The same column and the same compact composer as a conversation with one Bot. */}+ <div className="mx-auto w-full max-w-2xl shrink-0 pb-4">{send.error ? (<p className="pb-2 text-sm text-destructive" role="alert">{send.error.message}</p>) : null}- <People- channelId={channelId}- me={me?.id}- people={group.data?.people ?? []}- />- <AddPerson channelId={channelId} /><Composeragents={toAgentOptions(bots)}+ className="mt-auto w-full"commands={[]}+ compactdisabled={bots.length === 0}pending={send.isPending || working}autoFocus@@ -176,8 +168,12 @@ function GroupLine({) : message.status === "waiting" ? (<p className="text-sm text-muted-foreground">{message.reason ?? "Waiting for your response."}{" "}- <Link className="underline" to="/approvals">- Open approvals+ <Link+ className="underline"+ params={{ agentId: message.agentId }}+ to="/bots/$agentId"+ >+ Open {name}</Link></p>) : message.consent ? (@@ -216,103 +212,3 @@ function GroupLine({</MessageRow>);}--/** Invite another person who has signed in here. They see this whole conversation. */-function AddPerson({ channelId }: { channelId: string }) {- const [open, setOpen] = useState(false);- const [email, setEmail] = useState("");- const add = useMutation(addGroupMemberMutationOptions(channelId));- if (!open)- return (- <div className="flex justify-end pb-2">- <Button onClick={() => setOpen(true)} size="sm" variant="ghost">- Add a person- </Button>- </div>- );- return (- <form- className="flex items-center gap-2 pb-2"- onSubmit={(event) => {- event.preventDefault();- add.mutate(email, {- onSuccess: () => {- setEmail("");- setOpen(false);- },- });- }}- >- <Input- aria-label="Their email"- onChange={(event) => setEmail(event.target.value)}- placeholder="Their email"- type="email"- value={email}- />- <Button disabled={!email.trim() || add.isPending} size="sm" type="submit">- Add- </Button>- {add.error ? (- <span className="text-sm text-destructive" role="alert">- {add.error.message}- </span>- ) : null}- </form>- );-}--/** Who is in the group. The creator can take people out; anyone else can leave. */-function People({- channelId,- me,- people,-}: {- channelId: string;- me: string | undefined;- people: GroupPerson[];-}) {- const queryClient = useQueryClient();- const remove = useMutation(- removeGroupMemberMutationOptions(queryClient, channelId),- );- const iCreated = people.some(- (person) => person.creator && person.userId === me,- );- if (people.length < 2) return null;- return (- <div className="flex flex-wrap items-center gap-1.5 pb-2 text-xs text-muted-foreground">- <span>People:</span>- {people.map((person) => {- const self = person.userId === me;- const removable = self ? !person.creator : iCreated;- return (- <span- className="flex items-center gap-1 rounded-full border border-border px-2 py-0.5"- key={person.userId}- >- {self ? "You" : (person.name ?? person.email)}- {removable ? (- <button- aria-label={- self ? "Leave this group" : `Remove ${person.email}`- }- className="hover:text-foreground"- disabled={remove.isPending}- onClick={() => remove.mutate(person.userId)}- type="button"- >- {self ? "leave" : "×"}- </button>- ) : null}- </span>- );- })}- {remove.error ? (- <span className="text-destructive" role="alert">- {remove.error.message}- </span>- ) : null}- </div>- );-}diff --git a/app/src/components/channels/group-people.tsx b/app/src/components/channels/group-people.tsxnew file mode 100644index 00000000..46303bc4--- /dev/null+++ b/app/src/components/channels/group-people.tsx@@ -0,0 +1,148 @@+import { IconUser, IconUsers } from "@tabler/icons-react";+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { Fragment, useState } from "react";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import {+ Item,+ ItemActions,+ ItemContent,+ ItemDescription,+ ItemMedia,+ ItemTitle,+} from "@/components/ui/item";+import { Separator } from "@/components/ui/separator";+import { currentUserQueryOptions } from "@/lib/auth/queries";+import {+ addGroupMemberMutationOptions,+ groupQueryOptions,+ removeGroupMemberMutationOptions,+} from "@/lib/groups";++/**+ * Who is in a group, from its top bar: how many people, and a dialog listing them where the creator+ * can take someone out, anyone else can leave, and anyone in it can add a person who has signed in+ * here. Everyone added sees the whole conversation.+ */+export function GroupPeopleButton({ channelId }: { channelId: string }) {+ const queryClient = useQueryClient();+ const group = useQuery(groupQueryOptions(channelId));+ const me = useQuery(currentUserQueryOptions()).data;+ const add = useMutation(+ addGroupMemberMutationOptions(queryClient, channelId),+ );+ const remove = useMutation(+ removeGroupMemberMutationOptions(queryClient, channelId),+ );+ const [open, setOpen] = useState(false);+ const [email, setEmail] = useState("");+ const people = group.data?.people ?? [];+ if (!group.data) return null;+ const iCreated = people.some(+ (person) => person.creator && person.userId === me?.id,+ );+ const count = `${people.length} ${people.length === 1 ? "person" : "people"}`;++ return (+ <>+ <Button+ className="ml-auto"+ onClick={() => setOpen(true)}+ size="sm"+ variant="ghost"+ >+ <IconUsers />+ {count}+ </Button>+ <Dialog onOpenChange={setOpen} open={open}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>People in this group</DialogTitle>+ <DialogDescription>+ Everyone here sees the whole conversation, and every Bot in it+ answers them.+ </DialogDescription>+ </DialogHeader>+ <DialogBody className="mt-4 grid gap-4 overflow-y-auto">+ <div className="overflow-hidden rounded-lg">+ {people.map((person, index) => {+ const self = person.userId === me?.id;+ const removable = self ? !person.creator : iCreated;+ return (+ <Fragment key={person.userId}>+ {index > 0 ? <Separator /> : null}+ <Item size="sm" variant="muted">+ <ItemMedia variant="icon">+ <IconUser />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>+ {self ? "You" : (person.name ?? person.email)}+ </ItemTitle>+ <ItemDescription>+ {person.creator ? "Started this group" : person.email}+ </ItemDescription>+ </ItemContent>+ {removable ? (+ <ItemActions>+ <Button+ aria-label={+ self+ ? "Leave this group"+ : `Remove ${person.email}`+ }+ disabled={remove.isPending}+ onClick={() => remove.mutate(person.userId)}+ size="sm"+ variant="outline"+ >+ {self ? "Leave" : "Remove"}+ </Button>+ </ItemActions>+ ) : null}+ </Item>+ </Fragment>+ );+ })}+ </div>+ <form+ className="flex items-center gap-2"+ onSubmit={(event) => {+ event.preventDefault();+ add.mutate(email.trim(), { onSuccess: () => setEmail("") });+ }}+ >+ <Input+ aria-label="Their email"+ onChange={(event) => setEmail(event.target.value)}+ placeholder="Add someone by email"+ type="email"+ value={email}+ />+ <Button+ disabled={!email.trim() || add.isPending}+ size="sm"+ type="submit"+ >+ Add+ </Button>+ </form>+ {add.error || remove.error ? (+ <p className="text-destructive text-sm" role="alert">+ {(add.error ?? remove.error)?.message}+ </p>+ ) : null}+ </DialogBody>+ </DialogContent>+ </Dialog>+ </>+ );+}diff --git a/app/src/components/computer/computer-controls.tsx b/app/src/components/computer/computer-controls.tsxindex ec9208dc..60a6cc3e 100644--- a/app/src/components/computer/computer-controls.tsx+++ b/app/src/components/computer/computer-controls.tsx@@ -42,6 +42,11 @@ export function ComputerControlButton({);}+/**+ * The header's way into the Computer: an icon that opens and closes it, with a dot when the+ * Computer wants the person. Taking and handing back control happen inside the Computer, where the+ * person can see what they are taking over; the Computer opens itself once for each new prompt.+ */export function ComputerChatControls({computerId,open,@@ -70,31 +75,23 @@ export function ComputerChatControls({if (promptKey) onOpenChange(true);}, [promptKey, onOpenChange]);return (- <div className="flex items-start gap-1.5">- <Button- size="sm"- variant={open ? "secondary" : "ghost"}- aria-label={open ? "Close Computer" : "Open Computer"}- aria-expanded={open}- disabled={!computerId}- onClick={() => onOpenChange(!open)}- >- <IconDeviceDesktop className="size-4" />- Computer- {needsYou ? (- <span- className="size-2 rounded-full bg-amber-500"- role="img"- aria-label="Needs you"- />- ) : null}- </Button>- {computerId ? (- <ComputerControlButton- computerId={computerId}- onTakeControl={() => onOpenChange(true)}+ <Button+ aria-expanded={open}+ aria-label={open ? "Close Computer" : "Open Computer"}+ className={open ? "relative bg-foreground/5" : "relative"}+ disabled={!computerId}+ onClick={() => onOpenChange(!open)}+ size="icon"+ variant="ghost"+ >+ <IconDeviceDesktop className="size-4.5" />+ {needsYou ? (+ <span+ aria-label="Needs you"+ className="absolute top-1 right-1 size-2 rounded-full bg-amber-500 ring-2 ring-background"+ role="img"/>) : null}- </div>+ </Button>);}diff --git a/app/src/components/delivery/reaching-you.tsx b/app/src/components/delivery/reaching-you.tsxnew file mode 100644index 00000000..189275fc--- /dev/null+++ b/app/src/components/delivery/reaching-you.tsx@@ -0,0 +1,563 @@+import {+ IconBrandSlack,+ IconBrandTeams,+ IconChevronRight,+ IconDeviceMobileMessage,+} from "@tabler/icons-react";+import { useInfiniteQuery, useMutation, useQuery } from "@tanstack/react-query";+import { Link } from "@tanstack/react-router";+import { Fragment, useEffect, useId, useState } from "react";+import {+ PageEmpty,+ PageRows,+ PageSection,+} from "@/components/layout/page-shell";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Field, FieldLabel } from "@/components/ui/field";+import { Input } from "@/components/ui/input";+import {+ Item,+ ItemActions,+ ItemContent,+ ItemDescription,+ ItemMedia,+ ItemTitle,+} from "@/components/ui/item";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { Separator } from "@/components/ui/separator";+import { agentListQueryOptions } from "@/lib/agents/queries";+import { conversationLabel } from "@/lib/channels/label";+import { channelListQueryOptions } from "@/lib/channels/queries";+import {+ type ChatLink,+ confirmSmsMutationOptions,+ deliveryQueryOptions,+ type Reachability,+ removeDeliveryBindingMutationOptions,+ startChatLinkMutationOptions,+ startSmsMutationOptions,+} from "@/lib/delivery";+import { queryClient } from "@/query-client";++/**+ * The phone verification waiting for its code, kept for the tab.+ *+ * Only the challenge id lives in the page, and the text with the code arrives on the person's+ * phone a moment after they may have looked away: leaving and coming back used to drop the box to+ * type it into, with no way to confirm the code they had just been sent.+ */+const PENDING_SMS = "openbot.reachability.pendingSms";+function readPending(): string {+ try {+ return sessionStorage.getItem(PENDING_SMS) ?? "";+ } catch {+ return "";+ }+}+function writePending(id: string) {+ try {+ if (id) sessionStorage.setItem(PENDING_SMS, id);+ else sessionStorage.removeItem(PENDING_SMS);+ } catch {+ /* A browser that keeps nothing still confirms within the visit. */+ }+}++type Transport = Reachability["bindings"][number]["transport"];+type ChatPlatform = ChatLink["platform"];++/** A one-time link message, the conversation and Bot it links, and when it stops working. */+type HeldLink = ChatLink & {+ channelId: string;+ agentId: string;+ expiresAt: number;+};++const TRANSPORT: Record<+ Transport,+ { link: string; icon: typeof IconBrandSlack; summary: string }+> = {+ slack: {+ link: "Link Slack",+ icon: IconBrandSlack,+ summary: "Continue a conversation from Slack.",+ },+ teams: {+ link: "Link Microsoft Teams",+ icon: IconBrandTeams,+ summary: "Continue a conversation from Microsoft Teams.",+ },+ sms: {+ link: "Connect a phone",+ icon: IconDeviceMobileMessage,+ summary: "Continue a conversation by text message.",+ },+};++/**+ * Continuing a conversation in Slack, Microsoft Teams or by text message. Given a Bot, only that+ * Bot's conversations and destinations, and no Bot to pick.+ *+ * The destinations already connected are rows with a Disconnect each. Connecting one is a row per+ * transport that opens a dialog, because it is several inputs — a conversation, then an account or+ * a phone number — and the answer is a code to send back.+ */+export function ReachingYou({ agentId: fixedBot }: { agentId?: string }) {+ const reach = useQuery(deliveryQueryOptions());+ const bots = useQuery(agentListQueryOptions());+ // People read Bots by name; the id is what the list used to show.+ const botName = (id: string) =>+ bots.data?.find((bot) => bot.id === id)?.name ?? id;+ const [challengeId, setChallengeId] = useState(readPending);+ useEffect(() => writePending(challengeId), [challengeId]);+ const [connecting, setConnecting] = useState<Transport | null>(null);+ /*+ * The last link message per platform, held here rather than in the dialog: the dialog unmounts+ * when it closes, and the code is only useful once it has been sent from Slack or Teams, which is+ * exactly when somebody closes it to go and do that. Dropped once it has expired.+ */+ const [links, setLinks] = useState<Partial<Record<ChatPlatform, HeldLink>>>(+ {},+ );+ const heldLink = (transport: Transport) => {+ if (transport === "sms") return undefined;+ const held = links[transport];+ return held && held.expiresAt > Date.now() ? held : undefined;+ };+ const remove = useMutation(removeDeliveryBindingMutationOptions(queryClient));+ const destinations = reach.data?.bindings.filter(+ (binding) =>+ binding.enabled &&+ (fixedBot === undefined || binding.agentId === fixedBot),+ );+ const listError = reach.error ?? remove.error;+ /*+ * A transport the deployment cannot reach is a row that says why rather than one that opens a+ * dialog whose every button is disabled. A phone with a code already on its way stays reachable,+ * so the code can still be confirmed.+ */+ const open = (transport: Transport) =>+ !!reach.data?.available[transport] ||+ (transport === "sms" && challengeId !== "");+ const summary = (transport: Transport) => {+ if (transport === "sms" && challengeId) {+ return "A verification code is on its way. Enter it to finish.";+ }+ if (heldLink(transport)) {+ return "A link code is waiting to be sent. Open this to see it again.";+ }+ if (open(transport)) return TRANSPORT[transport].summary;+ return transport === "sms"+ ? "Text messages are not set up on this deployment."+ : "An administrator needs to pair OpenBot with OpenTag before Slack or Teams can be linked.";+ };++ return (+ <>+ {fixedBot === undefined ? (+ <p className="mt-6 text-muted-foreground text-sm">+ Your devices, recent deliveries, and where each kind of update goes+ are in{" "}+ <Link+ className="underline underline-offset-4"+ to="/settings/notifications"+ >+ Settings → Notifications+ </Link>+ .+ </p>+ ) : null}+ <PageSection title="Connected destinations">+ {listError ? (+ <p className="mt-4 text-destructive text-sm" role="alert">+ {listError.message}+ </p>+ ) : null}+ {reach.isPending || !destinations ? null : destinations.length === 0 ? (+ <PageEmpty>No destinations connected.</PageEmpty>+ ) : (+ <PageRows>+ {destinations.map((binding, index) => {+ const Icon = TRANSPORT[binding.transport].icon;+ return (+ <Fragment key={binding.id}>+ {index > 0 ? <Separator /> : null}+ <Item size="sm">+ <ItemMedia variant="icon">+ <Icon />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>+ {binding.transport === "slack"+ ? "Slack"+ : binding.transport === "teams"+ ? "Microsoft Teams"+ : binding.address}+ </ItemTitle>+ <ItemDescription>+ {botName(binding.agentId)}+ {binding.optedOutAt+ ? " · Replied STOP; text START to resume"+ : null}+ </ItemDescription>+ </ItemContent>+ <ItemActions>+ <Button+ disabled={remove.isPending}+ onClick={() => remove.mutate(binding.id)}+ size="sm"+ variant="outline"+ >+ Disconnect+ </Button>+ </ItemActions>+ </Item>+ </Fragment>+ );+ })}+ </PageRows>+ )}+ </PageSection>+ <PageSection+ description="In a channel other people can read, the Bot answers you in a direct message instead."+ title="Connect a conversation"+ >+ {reach.data ? (+ <PageRows>+ {(Object.keys(TRANSPORT) as Transport[]).map((transport, index) => {+ const Icon = TRANSPORT[transport].icon;+ const opens = open(transport);+ return (+ <Fragment key={transport}>+ {index > 0 ? <Separator /> : null}+ <Item+ render={+ opens ? (+ <button+ onClick={() => setConnecting(transport)}+ type="button"+ />+ ) : undefined+ }+ size="sm"+ >+ <ItemMedia variant="icon">+ <Icon />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>{TRANSPORT[transport].link}</ItemTitle>+ <ItemDescription>{summary(transport)}</ItemDescription>+ </ItemContent>+ {opens ? (+ <ItemActions>+ <IconChevronRight className="size-4 text-muted-foreground" />+ </ItemActions>+ ) : null}+ </Item>+ </Fragment>+ );+ })}+ </PageRows>+ ) : null}+ </PageSection>+ {connecting && reach.data ? (+ <ConnectDialog+ available={reach.data.available}+ botName={botName}+ challengeId={challengeId}+ fixedBot={fixedBot}+ linked={heldLink(connecting)}+ onChallenge={setChallengeId}+ onClose={() => setConnecting(null)}+ onLinked={(link) =>+ setLinks((prior) => ({ ...prior, [link.platform]: link }))+ }+ transport={connecting}+ />+ ) : null}+ </>+ );+}++/**+ * Choose the conversation, then link an account or verify a phone. Linking an account answers with a+ * one-time `link <code>` message to send to the OpenBot app; a phone answers with a text carrying a+ * code to type back here.+ */+function ConnectDialog({+ transport,+ available,+ fixedBot,+ botName,+ challengeId,+ linked,+ onChallenge,+ onLinked,+ onClose,+}: {+ transport: Transport;+ available: Reachability["available"];+ fixedBot: string | undefined;+ botName: (id: string) => string;+ challengeId: string;+ /** The link message this platform last answered with, while it still works. */+ linked: HeldLink | undefined;+ onChallenge: (id: string) => void;+ onLinked: (link: HeldLink) => void;+ onClose: () => void;+}) {+ const formId = useId();+ const channels = useInfiniteQuery(channelListQueryOptions());+ // Reopened with a link message still held, the dialog shows the conversation it links.+ const [channelId, setChannelId] = useState(linked?.channelId ?? "");+ const [pickedBot, setAgentId] = useState(linked?.agentId ?? "");+ const agentId = fixedBot ?? pickedBot;+ const [phone, setPhone] = useState("");+ const [code, setCode] = useState("");+ const [copied, setCopied] = useState(false);+ const link = useMutation(startChatLinkMutationOptions());+ const sms = useMutation(startSmsMutationOptions());+ const confirm = useMutation(confirmSmsMutationOptions(queryClient));+ const startLink = (platform: ChatPlatform) =>+ link.mutate(+ { channelId, agentId, platform },+ {+ onSuccess: (result) => {+ onLinked({+ ...result,+ channelId,+ agentId,+ expiresAt: Date.now() + result.expiresInMinutes * 60_000,+ });+ setCopied(false);+ },+ },+ );+ const conversations =+ channels.data?.filter(+ (channel) =>+ channel.active &&+ (fixedBot === undefined || channel.agentIds.includes(fixedBot)),+ ) ?? [];+ const selected = channels.data?.find((channel) => channel.id === channelId);+ const chosen = !!agentId && !!channelId;+ const error = channels.error ?? link.error ?? sms.error ?? confirm.error;++ return (+ <Dialog onOpenChange={(next) => !next && onClose()} open>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{TRANSPORT[transport].link}</DialogTitle>+ <DialogDescription>+ An account or phone number reaches one conversation at a time.+ Linking it here moves it from wherever it is linked now.+ </DialogDescription>+ </DialogHeader>+ <DialogBody className="mt-4 grid gap-4 overflow-y-auto">+ <Field>+ <FieldLabel htmlFor={`${formId}-conversation`}>+ Conversation+ </FieldLabel>+ <Select+ items={Object.fromEntries(+ conversations.map((channel) => [+ channel.id,+ conversationLabel(channel),+ ]),+ )}+ onValueChange={(next) => {+ setChannelId(typeof next === "string" ? next : "");+ if (fixedBot === undefined) setAgentId("");+ }}+ value={channelId || null}+ >+ <SelectTrigger className="w-full" id={`${formId}-conversation`}>+ <SelectValue placeholder="Choose a conversation" />+ </SelectTrigger>+ <SelectContent>+ {conversations.map((channel) => (+ <SelectItem key={channel.id} value={channel.id}>+ {conversationLabel(channel)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>+ {fixedBot === undefined ? (+ <Field>+ <FieldLabel htmlFor={`${formId}-bot`}>Bot</FieldLabel>+ <Select+ items={Object.fromEntries(+ (selected?.agentIds ?? []).map((id) => [id, botName(id)]),+ )}+ onValueChange={(next) =>+ setAgentId(typeof next === "string" ? next : "")+ }+ value={pickedBot || null}+ >+ <SelectTrigger className="w-full" id={`${formId}-bot`}>+ <SelectValue placeholder="Choose a Bot" />+ </SelectTrigger>+ <SelectContent>+ {selected?.agentIds.map((id) => (+ <SelectItem key={id} value={id}>+ {botName(id)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>+ ) : null}+ {channels.hasNextPage ? (+ <Button+ className="justify-self-start"+ onClick={() => channels.fetchNextPage()}+ size="sm"+ variant="outline"+ >+ Load more conversations+ </Button>+ ) : null}+ {transport === "sms" ? (+ <>+ <form+ onSubmit={(event) => {+ event.preventDefault();+ sms.mutate(+ { channelId, agentId, phone },+ { onSuccess: onChallenge },+ );+ }}+ >+ <Field>+ <FieldLabel htmlFor={`${formId}-phone`}>+ Phone number+ </FieldLabel>+ <div className="flex items-center gap-2">+ <Input+ id={`${formId}-phone`}+ onChange={(event) => setPhone(event.target.value)}+ pattern="\+[1-9][0-9]{7,14}"+ placeholder="+15551234567"+ required+ type="tel"+ value={phone}+ />+ <Button+ disabled={!chosen || !available.sms || sms.isPending}+ size="sm"+ type="submit"+ variant={challengeId ? "outline" : "default"}+ >+ Send verification code+ </Button>+ </div>+ </Field>+ </form>+ {challengeId ? (+ <form+ onSubmit={(event) => {+ event.preventDefault();+ confirm.mutate(+ { challengeId, code },+ {+ onSuccess: () => {+ onChallenge("");+ setCode("");+ onClose();+ },+ },+ );+ }}+ >+ <Field>+ <FieldLabel htmlFor={`${formId}-code`}>+ Verification code+ </FieldLabel>+ <div className="flex items-center gap-2">+ <Input+ autoComplete="one-time-code"+ id={`${formId}-code`}+ onChange={(event) => setCode(event.target.value)}+ required+ value={code}+ />+ <Button+ disabled={confirm.isPending}+ size="sm"+ type="submit"+ >+ Confirm phone+ </Button>+ </div>+ </Field>+ </form>+ ) : null}+ </>+ ) : linked ? (+ <Item size="sm" variant="muted">+ <ItemContent>+ <ItemDescription className="line-clamp-none">+ Send this message to the OpenBot app in{" "}+ {linked.platform === "teams" ? "Microsoft Teams" : "Slack"}{" "}+ within {Math.ceil((linked.expiresAt - Date.now()) / 60_000)}{" "}+ minutes. It links that account to this conversation and Bot.+ </ItemDescription>+ <ItemTitle className="break-all font-mono">+ {linked.command}+ </ItemTitle>+ </ItemContent>+ <ItemActions>+ <Button+ onClick={async () => {+ await navigator.clipboard.writeText(linked.command);+ setCopied(true);+ }}+ size="sm"+ variant="outline"+ >+ {copied ? "Copied" : "Copy"}+ </Button>+ </ItemActions>+ </Item>+ ) : null}+ {error ? (+ <p className="text-destructive text-sm" role="alert">+ {error.message}+ </p>+ ) : null}+ </DialogBody>+ <DialogFooter className="mt-4">+ <Button onClick={onClose} size="sm" variant="outline">+ Close+ </Button>+ {/* A phone's two steps each submit their own field, beside it. */}+ {transport === "sms" ? null : (+ <Button+ disabled={!chosen || !available[transport] || link.isPending}+ onClick={() => startLink(transport)}+ size="sm"+ >+ {TRANSPORT[transport].link}+ </Button>+ )}+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/app/src/components/memory/memories.tsx b/app/src/components/memory/memories.tsxnew file mode 100644index 00000000..9dd39a75--- /dev/null+++ b/app/src/components/memory/memories.tsx@@ -0,0 +1,344 @@+import { IconPlus, IconRobot, IconUser } from "@tabler/icons-react";+import { useMutation, useQuery } from "@tanstack/react-query";+import { Fragment, useId, useState } from "react";+import {+ PageEmpty,+ PageRows,+ PageSection,+} from "@/components/layout/page-shell";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Field, FieldLabel } from "@/components/ui/field";+import {+ Item,+ ItemActions,+ ItemContent,+ ItemDescription,+ ItemFooter,+ ItemMedia,+ ItemTitle,+} from "@/components/ui/item";+import { Separator } from "@/components/ui/separator";+import { Switch } from "@/components/ui/switch";+import { Textarea } from "@/components/ui/textarea";+import { agentListQueryOptions } from "@/lib/agents/queries";+import {+ createMemoryMutationOptions,+ deleteMemoryMutationOptions,+ type MemoryRecord,+ memoriesQueryOptions,+ updateMemoryMutationOptions,+} from "@/lib/memory";+import { queryClient } from "@/query-client";++/**+ * A fact the person tells their Bots directly. It reaches every one of them.+ *+ * The page's one primary verb, so it is a button for `PageShell`'s `action` that opens a dialog,+ * rather than a form standing above the list somebody came to read.+ */+export function RememberFact() {+ const [open, setOpen] = useState(false);+ const [content, setContent] = useState("");+ const formId = useId();+ const remember = useMutation(createMemoryMutationOptions(queryClient));+ return (+ <>+ <Button+ onClick={() => {+ // Opening starts clean: no draft or failure left from an earlier attempt.+ setContent("");+ remember.reset();+ setOpen(true);+ }}+ size="sm"+ variant="ghost"+ >+ <IconPlus />+ Remember a fact+ </Button>+ <Dialog onOpenChange={setOpen} open={open}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Remember a fact</DialogTitle>+ <DialogDescription>+ It reaches every one of your Bots.+ </DialogDescription>+ </DialogHeader>+ <DialogBody className="mt-4">+ {/* The submit button is in the footer and reaches this form by id, so DialogBody stays a+ direct child of DialogContent and keeps scrolling. */}+ <form+ id={formId}+ onSubmit={(event) => {+ event.preventDefault();+ remember.mutate(content, {+ onSuccess: () => {+ setContent("");+ setOpen(false);+ },+ });+ }}+ >+ <Field>+ <FieldLabel htmlFor={`${formId}-content`}>+ Something you want your Bots to know+ </FieldLabel>+ <Textarea+ id={`${formId}-content`}+ required+ maxLength={6000}+ value={content}+ onChange={(event) => setContent(event.target.value)}+ placeholder="I prefer meetings in the morning."+ />+ </Field>+ </form>+ {remember.error ? (+ <p role="alert" className="text-destructive text-sm">+ {remember.error.message}+ </p>+ ) : null}+ </DialogBody>+ <DialogFooter className="mt-4">+ <Button onClick={() => setOpen(false)} size="sm" variant="outline">+ Cancel+ </Button>+ <Button+ disabled={remember.isPending || !content.trim()}+ form={formId}+ size="sm"+ type="submit"+ >+ Remember+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </>+ );+}++/** Everything the person's Bots remember about them, with who formed each memory. */+export function MemoryList() {+ const memories = useQuery(memoriesQueryOptions());+ const agents = useQuery(agentListQueryOptions());+ const botName = (id: string | null) =>+ agents.data?.find((agent) => agent.id === id)?.name ?? "your Bot";+ return (+ <PageSection title="Your memories">+ {memories.isPending ? null : memories.error ? (+ <p role="alert" className="mt-4 text-destructive text-sm">+ {memories.error.message}+ </p>+ ) : memories.data.length ? (+ <PageRows>+ {memories.data.map((memory, index) => (+ <Fragment key={memory.id}>+ {index > 0 ? <Separator /> : null}+ <MemoryRow+ botName={botName(memory.formedByAgentId)}+ memory={memory}+ />+ </Fragment>+ ))}+ </PageRows>+ ) : (+ <PageEmpty>You have no memories yet.</PageEmpty>+ )}+ </PageSection>+ );+}++/**+ * One memory: the fact itself, then where it came from. Whether Bots use it is a switch; editing+ * its words opens a dialog, and confirming or forgetting it are the buttons beneath.+ */+function MemoryRow({+ memory,+ botName,+}: {+ memory: MemoryRecord;+ botName: string;+}) {+ const [editing, setEditing] = useState(false);+ const save = useMutation(updateMemoryMutationOptions(queryClient));+ const forget = useMutation(deleteMemoryMutationOptions(queryClient));+ const update = (input: {+ content?: string;+ enabled?: boolean;+ reviewState?: "confirmed";+ }) => save.mutate({ id: memory.id, input });+ const status = !memory.enabled+ ? "Disabled"+ : memory.formedBy === "bot"+ ? `Formed by ${botName}${memory.reviewState === "unreviewed" ? " · awaiting review" : ""}`+ : memory.reviewState === "unreviewed"+ ? "Imported · awaiting review"+ : "Reviewed";+ return (+ <Item size="sm">+ <ItemMedia variant="icon">+ {memory.formedBy === "bot" ? <IconRobot /> : <IconUser />}+ </ItemMedia>+ <ItemContent>+ <ItemTitle className="line-clamp-none whitespace-pre-wrap">+ {memory.content}+ </ItemTitle>+ <ItemDescription className="line-clamp-none">+ {memory.provenance} · {status}+ </ItemDescription>+ {memory.formedBy === "bot" && (+ <ItemDescription className="line-clamp-none">+ From {memory.sourceApp ?? "a conversation"}+ {memory.observedAt+ ? `, read ${new Date(memory.observedAt).toLocaleString()}`+ : ""}+ {memory.sourceLink && (+ <>+ {" · "}+ <a href={memory.sourceLink} target="_blank" rel="noreferrer">+ Open record+ </a>+ </>+ )}+ </ItemDescription>+ )}+ {/* A set, so it wraps onto its own line rather than crowding the fact. */}+ <ItemFooter>+ <div className="flex flex-wrap gap-2">+ <Button+ onClick={() => {+ save.reset();+ setEditing(true);+ }}+ size="sm"+ variant="outline"+ >+ Edit+ </Button>+ {memory.reviewState === "unreviewed" && (+ <Button+ size="sm"+ variant="outline"+ onClick={() => update({ reviewState: "confirmed" })}+ >+ Confirm+ </Button>+ )}+ <Button+ size="sm"+ variant="outline"+ disabled={forget.isPending}+ onClick={() => forget.mutate(memory.id)}+ >+ Forget+ </Button>+ </div>+ </ItemFooter>+ {!editing && (save.error || forget.error) && (+ <p role="alert" className="text-destructive text-sm">+ {save.error?.message || forget.error?.message}+ </p>+ )}+ </ItemContent>+ <ItemActions>+ {/* Binary and immediate: Bots stop or start using it when switched. */}+ <Switch+ aria-label={`Use this memory: ${clip(memory.content)}`}+ checked={memory.enabled}+ disabled={save.isPending}+ onCheckedChange={(enabled) => update({ enabled })}+ />+ </ItemActions>+ {editing ? (+ <EditMemoryDialog+ memory={memory}+ onClose={() => setEditing(false)}+ onSave={(content) =>+ save.mutate(+ { id: memory.id, input: { content } },+ { onSuccess: () => setEditing(false) },+ )+ }+ error={save.error?.message ?? null}+ saving={save.isPending}+ />+ ) : null}+ </Item>+ );+}++/** A memory's words, cut short enough to name the switch beside them. */+function clip(content: string) {+ const line = content.replace(/\s+/g, " ").trim();+ return line.length > 60 ? `${line.slice(0, 59)}…` : line;+}++/** The memory's words in a dialog. Saving rewrites them; the server records it as edited. */+function EditMemoryDialog({+ memory,+ saving,+ error,+ onSave,+ onClose,+}: {+ memory: MemoryRecord;+ saving: boolean;+ error: string | null;+ onSave: (content: string) => void;+ onClose: () => void;+}) {+ const [content, setContent] = useState(memory.content);+ const id = useId();+ return (+ <Dialog onOpenChange={(next) => !next && onClose()} open>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Edit memory</DialogTitle>+ <DialogDescription>{memory.provenance}</DialogDescription>+ </DialogHeader>+ <DialogBody className="mt-4">+ <Field>+ <FieldLabel className="sr-only" htmlFor={id}>+ Memory+ </FieldLabel>+ <Textarea+ autoFocus+ id={id}+ maxLength={6000}+ onChange={(event) => setContent(event.target.value)}+ rows={5}+ value={content}+ />+ </Field>+ {error ? (+ <p role="alert" className="text-destructive text-sm">+ {error}+ </p>+ ) : null}+ </DialogBody>+ <DialogFooter className="mt-4">+ <Button onClick={onClose} size="sm" variant="outline">+ Cancel+ </Button>+ <Button+ disabled={saving || !content.trim()}+ onClick={() => onSave(content)}+ size="sm"+ >+ Save+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/app/src/components/memory/sources.tsx b/app/src/components/memory/sources.tsxnew file mode 100644index 00000000..a3f552e2--- /dev/null+++ b/app/src/components/memory/sources.tsx@@ -0,0 +1,418 @@+import { IconPlugConnected, IconPlus } from "@tabler/icons-react";+import { useMutation, useQuery } from "@tanstack/react-query";+import { Fragment, useId, useState } from "react";+import {+ PageEmpty,+ PageRows,+ PageSection,+} from "@/components/layout/page-shell";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import {+ Field,+ FieldDescription,+ FieldGroup,+ FieldLabel,+} from "@/components/ui/field";+import { Input } from "@/components/ui/input";+import {+ Item,+ ItemActions,+ ItemContent,+ ItemDescription,+ ItemFooter,+ ItemMedia,+ ItemTitle,+} from "@/components/ui/item";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { Separator } from "@/components/ui/separator";+import { Switch } from "@/components/ui/switch";+import { agentListQueryOptions } from "@/lib/agents/queries";+import {+ addMemorySourceMutationOptions,+ availableMemorySourcesQueryOptions,+ memorySourceActionMutationOptions,+ memorySourcesQueryOptions,+} from "@/lib/memory";+import { queryClient } from "@/query-client";++/**+ * Connected apps a Bot reads facts from. Given a Bot, only that Bot's sources, and a new one is that+ * Bot's without asking.+ *+ * Each source is a row; adding one is a dialog behind the section's action. The draft lives here+ * rather than in the dialog, so the Bot's read actions are already loaded when it opens.+ */+export function MemorySources({ agentId: fixedBot }: { agentId?: string }) {+ const sources = useQuery(memorySourcesQueryOptions());+ const bots = useQuery(agentListQueryOptions());+ const [adding, setAdding] = useState(false);+ const [pickedBot, setAgentId] = useState("");+ const agentId = fixedBot ?? pickedBot;+ const [toolRef, setToolRef] = useState("");+ const [title, setTitle] = useState("");+ const [args, setArgs] = useState<Record<string, string>>({});+ const [error, setError] = useState("");+ const id = useId();+ const tools = useQuery(availableMemorySourcesQueryOptions(agentId));+ const chosen = tools.data?.find((tool) => tool.ref === toolRef);+ const properties = chosen?.inputSchema.properties;+ const settings =+ properties && typeof properties === "object" && !Array.isArray(properties)+ ? Object.entries(properties).flatMap(([name, value]) =>+ value && typeof value === "object" && !Array.isArray(value)+ ? [+ {+ name,+ schema: value as {+ type?: string;+ title?: string;+ description?: string;+ enum?: unknown[];+ },+ },+ ]+ : [],+ )+ : [];+ const required = Array.isArray(chosen?.inputSchema.required)+ ? chosen.inputSchema.required+ : [];+ const add = useMutation(addMemorySourceMutationOptions(queryClient));+ const action = useMutation(memorySourceActionMutationOptions(queryClient));+ const shown = (sources.data ?? []).filter(+ (source) => fixedBot === undefined || source.agentId === fixedBot,+ );+ return (+ <PageSection+ action={+ <Button+ onClick={() => {+ // The draft is kept on purpose; the last attempt's failure is not.+ setError("");+ add.reset();+ setAdding(true);+ }}+ size="sm"+ variant="ghost"+ >+ <IconPlus />+ Add source+ </Button>+ }+ description="Opt in to a read from an app this Bot can already access. Enabled sources refresh every 15 minutes, and their facts are available to this Bot only."+ title="Connected app sources"+ >+ {sources.isPending ? null : sources.error ? (+ <p role="alert" className="mt-4 text-destructive text-sm">+ {sources.error.message}+ </p>+ ) : shown.length === 0 ? (+ <PageEmpty>No connected app sources yet.</PageEmpty>+ ) : (+ <PageRows>+ {shown.map((source, index) => (+ <Fragment key={source.id}>+ {index > 0 ? <Separator /> : null}+ <Item size="sm">+ <ItemMedia variant="icon">+ <IconPlugConnected />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>{source.title}</ItemTitle>+ <ItemDescription>+ {source.enabled+ ? source.syncStatus === "succeeded"+ ? "Up to date"+ : source.syncStatus+ : "Disabled"}+ {source.lastSyncAt+ ? ` · Last read ${new Date(source.lastSyncAt).toLocaleString()}`+ : ""}+ </ItemDescription>+ {source.syncError && (+ <p role="alert" className="text-destructive text-sm">+ {source.syncError}+ </p>+ )}+ {/* A set, so it wraps onto its own line rather than crowding the title. */}+ <ItemFooter>+ <div className="flex flex-wrap gap-2">+ <Button+ size="sm"+ variant="outline"+ disabled={!source.enabled || action.isPending}+ onClick={() =>+ action.mutate({ sourceId: source.id, name: "sync" })+ }+ >+ Sync now+ </Button>+ <Button+ size="sm"+ variant="outline"+ onClick={() =>+ action.mutate({ sourceId: source.id, name: "remove" })+ }+ >+ Remove+ </Button>+ </div>+ </ItemFooter>+ </ItemContent>+ <ItemActions>+ {/* Binary and immediate: it refreshes, or stops refreshing, when switched. */}+ <Switch+ aria-label={`Read ${source.title}`}+ checked={source.enabled}+ disabled={action.isPending}+ onCheckedChange={(enabled) =>+ action.mutate({+ sourceId: source.id,+ name: enabled ? "enable" : "disable",+ })+ }+ />+ </ItemActions>+ </Item>+ </Fragment>+ ))}+ </PageRows>+ )}+ {action.error && (+ <p role="alert" className="mt-4 text-destructive text-sm">+ {action.error.message}+ </p>+ )}+ <Dialog onOpenChange={setAdding} open={adding}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Add a source</DialogTitle>+ <DialogDescription>+ It is read now, and then every 15 minutes while it is enabled.+ </DialogDescription>+ </DialogHeader>+ <DialogBody className="mt-4 overflow-y-auto">+ {/* The submit button is in the footer and reaches this form by id, so DialogBody stays a+ direct child of DialogContent and keeps scrolling. */}+ <form+ id={id}+ onSubmit={(event) => {+ event.preventDefault();+ try {+ const values: Record<string, unknown> = {};+ for (const setting of settings) {+ const value = args[setting.name];+ if (!value) continue;+ if (+ setting.schema.type === "number" ||+ setting.schema.type === "integer"+ ) {+ const number = Number(value);+ if (!Number.isFinite(number))+ throw new Error(`Enter a number for ${setting.name}.`);+ values[setting.name] = number;+ } else if (setting.schema.type === "boolean")+ values[setting.name] = value === "true";+ else if (setting.schema.type === "array")+ values[setting.name] = value+ .split("\n")+ .map((entry) => entry.trim())+ .filter(Boolean);+ else if (setting.schema.type === "object")+ throw new Error(+ "Choose an action with simple search settings.",+ );+ else values[setting.name] = value;+ }+ setError("");+ add.mutate(+ {+ agentId,+ toolRef,+ title,+ args: values,+ },+ {+ onSuccess: () => {+ setTitle("");+ setAdding(false);+ },+ },+ );+ } catch (cause) {+ setError(+ cause instanceof Error+ ? cause.message+ : "Check the source settings.",+ );+ }+ }}+ >+ <FieldGroup>+ {fixedBot === undefined ? (+ <Field>+ <FieldLabel htmlFor={`${id}-bot`}>Bot</FieldLabel>+ <Select+ items={bots.data?.map((bot) => ({+ value: bot.id,+ label: bot.name,+ }))}+ onValueChange={(value) => {+ setAgentId(value ?? "");+ setToolRef("");+ }}+ required+ value={agentId || null}+ >+ <SelectTrigger className="w-full" id={`${id}-bot`}>+ <SelectValue placeholder="Choose a Bot" />+ </SelectTrigger>+ <SelectContent>+ {bots.data?.map((bot) => (+ <SelectItem key={bot.id} value={bot.id}>+ {bot.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>+ ) : null}+ <Field>+ <FieldLabel htmlFor={`${id}-action`}>+ Connected app action+ </FieldLabel>+ <Select+ items={tools.data?.map((tool) => ({+ value: tool.ref,+ label: tool.title,+ }))}+ onValueChange={(value) => {+ setToolRef(value ?? "");+ setArgs({});+ }}+ required+ value={toolRef || null}+ >+ <SelectTrigger className="w-full" id={`${id}-action`}>+ <SelectValue placeholder="Choose a read action" />+ </SelectTrigger>+ <SelectContent>+ {tools.data?.map((tool) => (+ <SelectItem key={tool.ref} value={tool.ref}>+ {tool.title}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ {chosen?.description ? (+ <FieldDescription>{chosen.description}</FieldDescription>+ ) : null}+ </Field>+ <Field>+ <FieldLabel htmlFor={`${id}-name`}>Source name</FieldLabel>+ <Input+ id={`${id}-name`}+ required+ maxLength={160}+ value={title}+ onChange={(event) => setTitle(event.target.value)}+ placeholder="My project documents"+ />+ </Field>+ {settings.map(({ name, schema }) => (+ <Field key={name}>+ {/* `arg-` keeps a setting called `name` or `bot` off the fixed fields' ids. */}+ <FieldLabel htmlFor={`${id}-arg-${name}`}>+ {schema.title || name.replaceAll("_", " ")}+ {required.includes(name) ? " *" : ""}+ </FieldLabel>+ {schema.type === "boolean" || schema.enum ? (+ <Select+ onValueChange={(value) =>+ setArgs({ ...args, [name]: value ?? "" })+ }+ required={required.includes(name)}+ value={args[name] || null}+ >+ <SelectTrigger+ className="w-full"+ id={`${id}-arg-${name}`}+ >+ <SelectValue placeholder="Choose a value" />+ </SelectTrigger>+ <SelectContent>+ {(schema.enum ?? ["true", "false"]).map((value) => (+ <SelectItem+ key={String(value)}+ value={String(value)}+ >+ {String(value)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ ) : (+ <Input+ id={`${id}-arg-${name}`}+ type={+ schema.type === "number" || schema.type === "integer"+ ? "number"+ : "text"+ }+ required={required.includes(name)}+ value={args[name] ?? ""}+ onChange={(event) =>+ setArgs({ ...args, [name]: event.target.value })+ }+ />+ )}+ {schema.description && (+ <FieldDescription>{schema.description}</FieldDescription>+ )}+ </Field>+ ))}+ </FieldGroup>+ </form>+ {(error || add.error || tools.error) && (+ <p role="alert" className="text-destructive text-sm">+ {error || add.error?.message || tools.error?.message}+ </p>+ )}+ </DialogBody>+ <DialogFooter className="mt-4">+ <Button+ onClick={() => setAdding(false)}+ size="sm"+ variant="outline"+ >+ Cancel+ </Button>+ <Button+ disabled={add.isPending || !toolRef}+ form={id}+ size="sm"+ type="submit"+ >+ {add.isPending ? "Reading source…" : "Add and sync source"}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </PageSection>+ );+}diff --git a/app/src/components/responsibilities/new-responsibility-dialog.tsx b/app/src/components/responsibilities/new-responsibility-dialog.tsxnew file mode 100644index 00000000..757abe0b--- /dev/null+++ b/app/src/components/responsibilities/new-responsibility-dialog.tsx@@ -0,0 +1,303 @@+import { useInfiniteQuery, useMutation, useQuery } from "@tanstack/react-query";+import { Link } from "@tanstack/react-router";+import { useId, useState } from "react";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import {+ Field,+ FieldDescription,+ FieldGroup,+ FieldLabel,+} from "@/components/ui/field";+import { Input } from "@/components/ui/input";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { Textarea } from "@/components/ui/textarea";+import { agentListQueryOptions } from "@/lib/agents/queries";+import { conversationLabel } from "@/lib/channels/label";+import { channelListQueryOptions } from "@/lib/channels/queries";+import {+ createResponsibilityMutationOptions,+ type ResponsibilityRecord,+} from "@/lib/responsibilities";+import { queryClient } from "@/query-client";++type Source = "none" | ResponsibilityRecord["subscriptions"][number]["source"];++/** The event sources a new responsibility can subscribe to, in the order they are offered. */+const SOURCES = {+ none: "Run when asked",+ github: "GitHub",+ slack: "Slack",+ connector: "Connected app",+ schedule: "Schedule",+} as const satisfies Partial<Record<Source, string>>;++/**+ * A new responsibility: where it runs, what it is for, and what — if anything — starts it on its+ * own. Given a Bot, the Bot is not asked for and only conversations that Bot is in are offered.+ */+export function NewResponsibilityDialog({+ agentId: fixedBot,+ onClose,+}: {+ agentId?: string;+ onClose: () => void;+}) {+ const formId = useId();+ const bots = useQuery(agentListQueryOptions());+ const channels = useInfiniteQuery(channelListQueryOptions());+ const [channelId, setChannelId] = useState("");+ const [pickedBot, setAgentId] = useState("");+ const agentId = fixedBot ?? pickedBot;+ const [title, setTitle] = useState("");+ const [instruction, setInstruction] = useState("");+ const [successCriteria, setSuccessCriteria] = useState("");+ const [source, setSource] = useState<Source>("none");+ const [eventType, setEventType] = useState("");+ const selectedChannel = channels.data?.find(+ (channel) => channel.id === channelId,+ );+ const availableBots =+ bots.data?.filter((bot) => selectedChannel?.agentIds.includes(bot.id)) ??+ [];+ const offered =+ channels.data?.filter(+ (channel) =>+ channel.active &&+ (fixedBot === undefined || channel.agentIds.includes(fixedBot)),+ ) ?? [];+ const create = useMutation(createResponsibilityMutationOptions(queryClient));+ return (+ <Dialog onOpenChange={(next) => !next && onClose()} open>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>New responsibility</DialogTitle>+ <DialogDescription>+ A lasting goal, worked on in the conversation you pick.+ </DialogDescription>+ </DialogHeader>+ <DialogBody className="mt-4 overflow-y-auto">+ {/* The submit button is in the footer and reaches this form by id, so DialogBody stays a+ direct child of DialogContent and keeps scrolling. */}+ <form+ id={formId}+ onSubmit={(event) => {+ event.preventDefault();+ create.mutate(+ {+ channelId,+ agentId,+ title,+ instruction,+ successCriteria,+ subscriptions:+ source === "none" ? [] : [{ source, eventType }],+ },+ { onSuccess: onClose },+ );+ }}+ >+ <FieldGroup>+ <FieldGroup className="sm:grid sm:grid-cols-2">+ <Field>+ <FieldLabel htmlFor={`${formId}-conversation`}>+ Conversation+ </FieldLabel>+ <Select+ items={Object.fromEntries(+ offered.map((channel) => [+ channel.id,+ conversationLabel(channel),+ ]),+ )}+ onValueChange={(value) => {+ setChannelId(value ?? "");+ setAgentId("");+ }}+ required+ value={channelId || null}+ >+ <SelectTrigger+ className="w-full"+ id={`${formId}-conversation`}+ >+ <SelectValue placeholder="Choose a conversation" />+ </SelectTrigger>+ <SelectContent>+ {offered.map((channel) => (+ <SelectItem key={channel.id} value={channel.id}>+ {conversationLabel(channel)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>+ {fixedBot === undefined ? (+ <Field>+ <FieldLabel htmlFor={`${formId}-bot`}>Bot</FieldLabel>+ <Select+ items={Object.fromEntries(+ availableBots.map((bot) => [bot.id, bot.name]),+ )}+ onValueChange={(value) => setAgentId(value ?? "")}+ required+ value={agentId || null}+ >+ <SelectTrigger className="w-full" id={`${formId}-bot`}>+ <SelectValue placeholder="Choose a Bot" />+ </SelectTrigger>+ <SelectContent>+ {availableBots.map((bot) => (+ <SelectItem key={bot.id} value={bot.id}>+ {bot.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>+ ) : null}+ </FieldGroup>+ {channels.hasNextPage && (+ <Button+ className="w-fit"+ onClick={() => channels.fetchNextPage()}+ size="sm"+ type="button"+ variant="outline"+ >+ Load more conversations+ </Button>+ )}+ {(channels.error || bots.error) && (+ <p role="alert" className="text-destructive text-sm">+ {channels.error?.message ?? bots.error?.message}+ </p>+ )}+ <Field>+ <FieldLabel htmlFor={`${formId}-title`}>Title</FieldLabel>+ <Input+ id={`${formId}-title`}+ required+ maxLength={160}+ value={title}+ onChange={(event) => setTitle(event.target.value)}+ placeholder="Keep the customer report up to date"+ />+ </Field>+ <Field>+ <FieldLabel htmlFor={`${formId}-instruction`}>+ Instruction+ </FieldLabel>+ <Textarea+ id={`${formId}-instruction`}+ required+ maxLength={6000}+ value={instruction}+ onChange={(event) => setInstruction(event.target.value)}+ />+ </Field>+ <Field>+ <FieldLabel htmlFor={`${formId}-criteria`}>+ Success criteria+ </FieldLabel>+ <Textarea+ id={`${formId}-criteria`}+ required+ maxLength={3000}+ value={successCriteria}+ onChange={(event) => setSuccessCriteria(event.target.value)}+ placeholder="The report contains the current quarter's graph and a source link."+ />+ </Field>+ <FieldGroup className="sm:grid sm:grid-cols-2">+ <Field>+ <FieldLabel htmlFor={`${formId}-source`}>+ Event source+ </FieldLabel>+ <Select+ items={SOURCES}+ onValueChange={(value) => {+ if (value && value in SOURCES) setSource(value as Source);+ }}+ value={source}+ >+ <SelectTrigger className="w-full" id={`${formId}-source`}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {(Object.keys(SOURCES) as (keyof typeof SOURCES)[]).map(+ (value) => (+ <SelectItem key={value} value={value}>+ {SOURCES[value]}+ </SelectItem>+ ),+ )}+ </SelectContent>+ </Select>+ {source === "github" && (+ <FieldDescription>+ Events come from the repositories you connected in{" "}+ <Link to="/settings/connected-accounts">+ Settings → Connected accounts+ </Link>+ .+ </FieldDescription>+ )}+ </Field>+ {source !== "none" && (+ <Field>+ <FieldLabel htmlFor={`${formId}-event`}>+ Event type+ </FieldLabel>+ <Input+ id={`${formId}-event`}+ required+ maxLength={128}+ value={eventType}+ onChange={(event) => setEventType(event.target.value)}+ placeholder={+ source === "github" ? "issues.opened" : "Event type"+ }+ />+ </Field>+ )}+ </FieldGroup>+ </FieldGroup>+ </form>+ {create.error && (+ <p role="alert" className="text-destructive text-sm">+ {create.error.message}+ </p>+ )}+ </DialogBody>+ <DialogFooter className="mt-4">+ <Button onClick={onClose} size="sm" type="button" variant="outline">+ Cancel+ </Button>+ <Button+ disabled={create.isPending}+ form={formId}+ size="sm"+ type="submit"+ >+ {create.isPending ? "Creating…" : "Create responsibility"}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/app/src/components/responsibilities/responsibilities.tsx b/app/src/components/responsibilities/responsibilities.tsxnew file mode 100644index 00000000..6fd060ce--- /dev/null+++ b/app/src/components/responsibilities/responsibilities.tsx@@ -0,0 +1,128 @@+import { IconChevronRight, IconPlus } from "@tabler/icons-react";+import { useQuery } from "@tanstack/react-query";+import { Fragment, useState } from "react";+import {+ PageEmpty,+ PageRows,+ PageSection,+} from "@/components/layout/page-shell";+import { Button } from "@/components/ui/button";+import {+ Item,+ ItemActions,+ ItemContent,+ ItemDescription,+ ItemMedia,+ ItemTitle,+} from "@/components/ui/item";+import { Separator } from "@/components/ui/separator";+import {+ type ResponsibilityRecord,+ responsibilitiesQueryOptions,+ triggersQueryOptions,+} from "@/lib/responsibilities";+import { NewResponsibilityDialog } from "./new-responsibility-dialog";+import {+ ResponsibilityDialog,+ STATUS,+ summaryFor,+} from "./responsibility-dialog";++/**+ * Lasting goals and their runs. Given a Bot, only that Bot's, and a new one is that Bot's without+ * asking. The list is the person's whole set, capped at 100 by the server across all their Bots, so+ * a Bot page filters it here rather than asking for a second list.+ *+ * One row per responsibility, saying where it stands; everything else about it — its wording, its+ * triggers, its runs, pausing and completing it — is in the dialog the row opens, because that is+ * many values and a settings screen that edits many values in place turns back into a form.+ */+export function BotResponsibilities({ agentId }: { agentId?: string }) {+ const goals = useQuery(responsibilitiesQueryOptions());+ const [creating, setCreating] = useState(false);+ const [openId, setOpenId] = useState<string | null>(null);+ const shown = (goals.data ?? []).filter(+ (goal) => agentId === undefined || goal.agentId === agentId,+ );+ // Looked up from the query rather than held, so the dialog follows every refetch.+ const open = shown.find((goal) => goal.id === openId);+ return (+ <PageSection+ action={+ <Button onClick={() => setCreating(true)} size="sm" variant="ghost">+ <IconPlus />+ New responsibility+ </Button>+ }+ title="Goals"+ >+ {/* Pending, error, empty, rows — pending first, so no sentence asserts anything mid-fetch. */}+ {goals.isPending ? null : goals.error ? (+ <p role="alert" className="mt-4 text-destructive text-sm">+ {goals.error.message}+ </p>+ ) : shown.length === 0 ? (+ <PageEmpty>+ {agentId+ ? "No responsibilities for this Bot yet."+ : "You have no responsibilities yet."}+ </PageEmpty>+ ) : (+ <PageRows>+ {shown.map((goal, index) => (+ <Fragment key={goal.id}>+ {index > 0 ? <Separator /> : null}+ <ResponsibilityRow+ goal={goal}+ onOpen={() => setOpenId(goal.id)}+ />+ </Fragment>+ ))}+ </PageRows>+ )}+ {creating ? (+ <NewResponsibilityDialog+ agentId={agentId}+ onClose={() => setCreating(false)}+ />+ ) : null}+ {open ? (+ <ResponsibilityDialog+ goal={open}+ key={open.id}+ onClose={() => setOpenId(null)}+ />+ ) : null}+ </PageSection>+ );+}++/**+ * A responsibility's row: its title, and its state and what starts it as the summary. A chevron+ * rather than a Switch, although pausing is binary: the row opens a dialog, and a Switch inside a+ * row that is itself a button would be a control nested in a control.+ */+function ResponsibilityRow({+ goal,+ onOpen,+}: {+ goal: ResponsibilityRecord;+ onOpen: () => void;+}) {+ const triggers = useQuery(triggersQueryOptions(goal.id));+ const Icon = STATUS[goal.status].icon;+ return (+ <Item render={<button onClick={onOpen} type="button" />} size="sm">+ <ItemMedia variant="icon">+ <Icon />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>{goal.title}</ItemTitle>+ <ItemDescription>{summaryFor(goal, triggers.data)}</ItemDescription>+ </ItemContent>+ <ItemActions>+ <IconChevronRight className="size-4 text-muted-foreground" />+ </ItemActions>+ </Item>+ );+}diff --git a/app/src/components/responsibilities/responsibility-dialog.tsx b/app/src/components/responsibilities/responsibility-dialog.tsxnew file mode 100644index 00000000..c75ccfdb--- /dev/null+++ b/app/src/components/responsibilities/responsibility-dialog.tsx@@ -0,0 +1,509 @@+import {+ IconChevronRight,+ IconCircleCheck,+ IconFlag,+ IconHistory,+ IconMessage,+ IconPlayerPause,+ IconPlayerPlay,+ IconProgress,+ IconTarget,+ IconWebhook,+} from "@tabler/icons-react";+import { useMutation, useQuery } from "@tanstack/react-query";+import { Link } from "@tanstack/react-router";+import { Fragment, useId, useState } from "react";+import { Streamdown } from "streamdown";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Field, FieldGroup, FieldLabel } from "@/components/ui/field";+import { Input } from "@/components/ui/input";+import {+ Item,+ ItemActions,+ ItemContent,+ ItemDescription,+ ItemFooter,+ ItemMedia,+ ItemTitle,+} from "@/components/ui/item";+import { Separator } from "@/components/ui/separator";+import { Switch } from "@/components/ui/switch";+import { Textarea } from "@/components/ui/textarea";+import { markdownComponents } from "@/lib/markdown";+import {+ type ResponsibilityRecord,+ responsibilityActionMutationOptions,+ responsibilityRunsQueryOptions,+ type TriggerRecord,+ triggersQueryOptions,+ updateResponsibilityMutationOptions,+} from "@/lib/responsibilities";+import { queryClient } from "@/query-client";+import { KIND_LABEL, Triggers } from "./triggers";++type Status = ResponsibilityRecord["status"];+type Source = ResponsibilityRecord["subscriptions"][number]["source"];++/** A responsibility's state, as a word and as the mark its row leads with. */+export const STATUS: Record<+ Status,+ { label: string; icon: typeof IconTarget }+> = {+ active: { label: "Active", icon: IconTarget },+ paused: { label: "Paused", icon: IconPlayerPause },+ completed: { label: "Completed", icon: IconCircleCheck },+};++const SOURCE_LABEL: Record<Source, string> = {+ manual: "Manual",+ slack: "Slack",+ github: "GitHub",+ schedule: "Schedule",+ connector: "Connected app",+ webhook: "Webhook",+ linear: "Linear",+ sentry: "Sentry",+ pagerduty: "PagerDuty",+ email: "Email",+};++/**+ * What a responsibility's row says under its title: its state, and while it is active, what starts+ * it. Computed from the queries on every render so it follows whatever the dialog just changed.+ *+ * `triggers` is undefined until they load, and then nothing is said about what starts it rather than+ * "Runs when asked", which would be a claim about triggers nobody has read yet.+ */+export function summaryFor(+ goal: ResponsibilityRecord,+ triggers: TriggerRecord[] | undefined,+): string {+ const status = STATUS[goal.status].label;+ if (goal.status === "completed") return status;+ if (goal.status === "paused")+ return `${status} · Nothing starts it until resumed`;+ const starts = [+ ...goal.subscriptions.map(+ (subscription) =>+ `${SOURCE_LABEL[subscription.source]} ${subscription.eventType}`,+ ),+ ...(triggers ?? [])+ .filter((trigger) => trigger.enabled)+ .map((trigger) => `${KIND_LABEL[trigger.kind]} trigger`),+ ];+ if (starts.length) return `${status} · Starts on ${starts.join(", ")}`;+ return triggers ? `${status} · Runs when asked` : status;+}++/**+ * Everything about one responsibility, opened from its row: what can be done to it now (pause, run,+ * complete — each immediate), its wording (a draft, saved by the footer), where it stands, what+ * starts it, and its runs.+ */+export function ResponsibilityDialog({+ goal,+ onClose,+}: {+ goal: ResponsibilityRecord;+ onClose: () => void;+}) {+ const formId = useId();+ const [showRuns, setShowRuns] = useState(false);+ const [title, setTitle] = useState(goal.title);+ const [instruction, setInstruction] = useState(goal.instruction);+ const [successCriteria, setSuccessCriteria] = useState(goal.successCriteria);+ const triggers = useQuery(triggersQueryOptions(goal.id));+ const action = useMutation(responsibilityActionMutationOptions(queryClient));+ const edit = useMutation(updateResponsibilityMutationOptions(queryClient));+ const standing = [+ goal.progress+ ? {+ key: "progress",+ label: "Progress",+ icon: IconProgress,+ text: goal.progress,+ }+ : null,+ goal.lastResult+ ? {+ key: "result",+ label: "Last result",+ icon: IconFlag,+ text: goal.lastResult,+ }+ : null,+ ].filter((entry) => entry !== null);++ return (+ <Dialog onOpenChange={(next) => !next && onClose()} open>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{goal.title}</DialogTitle>+ <DialogDescription>+ {summaryFor(goal, triggers.data)}+ </DialogDescription>+ </DialogHeader>+ <DialogBody className="mt-4 overflow-y-auto">+ <div className="overflow-hidden rounded-lg">+ {goal.status !== "completed" ? (+ <>+ <Item size="sm" variant="muted">+ <ItemMedia variant="icon">+ <IconTarget />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>Active</ItemTitle>+ <ItemDescription>+ {goal.status === "active"+ ? "Its events and triggers start runs."+ : "Paused. Its triggers are acknowledged but never run it."}+ </ItemDescription>+ </ItemContent>+ <ItemActions>+ <Switch+ aria-label="Active"+ checked={goal.status === "active"}+ disabled={action.isPending}+ onCheckedChange={(active) =>+ action.mutate({+ id: goal.id,+ action: active ? "resume" : "pause",+ })+ }+ />+ </ItemActions>+ </Item>+ <Separator />+ </>+ ) : null}+ {goal.status === "active" ? (+ <>+ <Item+ render={+ <button+ disabled={action.isPending}+ onClick={() => {+ setShowRuns(true);+ action.mutate({ id: goal.id, action: "run" });+ }}+ type="button"+ />+ }+ size="sm"+ variant="muted"+ >+ <ItemMedia variant="icon">+ <IconPlayerPlay />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>Run now (real run)</ItemTitle>+ <ItemDescription>+ Runs it for real, now: the Bot does the work and can post+ and act.+ </ItemDescription>+ </ItemContent>+ </Item>+ <Separator />+ </>+ ) : null}+ {goal.status !== "completed" ? (+ <>+ <Item+ render={+ <button+ disabled={action.isPending}+ onClick={() =>+ action.mutate({ id: goal.id, action: "complete" })+ }+ type="button"+ />+ }+ size="sm"+ variant="muted"+ >+ <ItemMedia variant="icon">+ <IconCircleCheck />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>Complete</ItemTitle>+ <ItemDescription>+ Mark it done. Nothing starts it after this.+ </ItemDescription>+ </ItemContent>+ </Item>+ <Separator />+ </>+ ) : null}+ <Item+ render={+ <Link+ params={{ channelId: goal.channelId }}+ to="/channel/$channelId"+ />+ }+ size="sm"+ variant="muted"+ >+ <ItemMedia variant="icon">+ <IconMessage />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>Open conversation</ItemTitle>+ </ItemContent>+ <ItemActions>+ <IconChevronRight className="size-4 text-muted-foreground" />+ </ItemActions>+ </Item>+ </div>+ {action.error || edit.error ? (+ <p role="alert" className="text-destructive text-sm">+ {action.error?.message ?? edit.error?.message}+ </p>+ ) : null}++ {/* The submit button is in the footer and reaches this form by id, so DialogBody stays a+ direct child of DialogContent and keeps scrolling. */}+ <form+ id={formId}+ onSubmit={(event) => {+ event.preventDefault();+ edit.mutate(+ {+ id: goal.id,+ patch: { title, instruction, successCriteria },+ },+ { onSuccess: onClose },+ );+ }}+ >+ <FieldGroup>+ <Field>+ <FieldLabel htmlFor={`${formId}-title`}>Title</FieldLabel>+ <Input+ id={`${formId}-title`}+ value={title}+ onChange={(event) => setTitle(event.target.value)}+ required+ maxLength={160}+ />+ </Field>+ <Field>+ <FieldLabel htmlFor={`${formId}-instruction`}>+ Instruction+ </FieldLabel>+ <Textarea+ id={`${formId}-instruction`}+ value={instruction}+ onChange={(event) => setInstruction(event.target.value)}+ required+ maxLength={6000}+ />+ </Field>+ <Field>+ <FieldLabel htmlFor={`${formId}-criteria`}>+ Success criteria+ </FieldLabel>+ <Textarea+ id={`${formId}-criteria`}+ value={successCriteria}+ onChange={(event) => setSuccessCriteria(event.target.value)}+ required+ maxLength={3000}+ />+ </Field>+ </FieldGroup>+ </form>++ {standing.length || goal.subscriptions.length ? (+ <div className="overflow-hidden rounded-lg">+ {standing.map(({ key, label, icon: Icon, text }, index) => (+ <Fragment key={key}>+ {index > 0 ? <Separator /> : null}+ <Item size="sm" variant="muted">+ <ItemMedia variant="icon">+ <Icon />+ </ItemMedia>+ <ItemContent className="min-w-0">+ <ItemTitle>{label}</ItemTitle>+ <RunMarkdown>{text}</RunMarkdown>+ </ItemContent>+ </Item>+ </Fragment>+ ))}+ {goal.subscriptions.length > 0 ? (+ <>+ {standing.length ? <Separator /> : null}+ <Item size="sm" variant="muted">+ <ItemMedia variant="icon">+ <IconWebhook />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>Events</ItemTitle>+ <ItemDescription className="line-clamp-none">+ {goal.subscriptions+ .map(+ (subscription) =>+ `${subscription.source} · ${subscription.eventType}`,+ )+ .join(", ")}+ </ItemDescription>+ </ItemContent>+ </Item>+ </>+ ) : null}+ </div>+ ) : null}++ <Triggers goal={goal} />+ <Runs+ channelId={goal.channelId}+ goalId={goal.id}+ onToggle={() => setShowRuns(!showRuns)}+ shown={showRuns}+ />+ </DialogBody>+ <DialogFooter className="mt-4">+ <Button onClick={onClose} size="sm" type="button" variant="outline">+ Cancel+ </Button>+ <Button+ disabled={edit.isPending}+ form={formId}+ size="sm"+ type="submit"+ >+ {edit.isPending ? "Saving…" : "Save"}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}++const RUN_LABEL: Record<string, string> = {+ queued: "Queued",+ running: "Running",+ waiting: "Waiting for you",+ succeeded: "Succeeded",+ failed: "Failed",+ skipped: "Skipped",+};+function runStatusClass(status: string) {+ return status === "failed"+ ? "text-destructive"+ : status === "succeeded"+ ? "text-emerald-600 dark:text-emerald-500"+ : "text-muted-foreground";+}++/**+ * The runs, fetched only once somebody asks for them — or presses Run now, which opens them so the+ * run it started is there to watch.+ */+function Runs({+ goalId,+ channelId,+ shown,+ onToggle,+}: {+ goalId: string;+ channelId: string;+ shown: boolean;+ onToggle: () => void;+}) {+ const runs = useQuery({+ ...responsibilityRunsQueryOptions(goalId),+ enabled: shown,+ });+ return (+ <section className="grid gap-2">+ <div className="flex items-center justify-between gap-2">+ <h3 className="font-medium text-sm">Runs</h3>+ <Button onClick={onToggle} size="sm" type="button" variant="ghost">+ {shown ? "Hide runs" : "View runs"}+ </Button>+ </div>+ {!shown ? null : runs.isPending ? null : runs.error ? (+ <p role="alert" className="text-destructive text-sm">+ {runs.error.message}+ </p>+ ) : runs.data.length ? (+ <div className="overflow-hidden rounded-lg">+ {runs.data.map((run, index) => (+ <Fragment key={run.id}>+ {index > 0 ? <Separator /> : null}+ <Item size="sm" variant="muted">+ <ItemMedia variant="icon">+ <IconHistory />+ </ItemMedia>+ <ItemContent>+ <ItemTitle className={runStatusClass(run.status)}>+ {RUN_LABEL[run.status]}+ </ItemTitle>+ <ItemDescription>+ {new Date(run.createdAt).toLocaleString()}+ </ItemDescription>+ </ItemContent>+ <ItemActions>+ <Link+ to="/channel/$channelId"+ params={{ channelId }}+ className="text-sm underline"+ >+ Open thread+ </Link>+ </ItemActions>+ {run.waiting || run.error || run.replyText ? (+ <ItemFooter className="min-w-0 flex-col items-stretch">+ {run.waiting && (+ <p>+ Waiting for {run.waiting.kind}. Respond at the top of+ this Bot's page, or in the conversation.+ </p>+ )}+ {run.error && (+ <p className="text-muted-foreground">{run.error}</p>+ )}+ {run.replyText && (+ <RunMarkdown>{run.replyText}</RunMarkdown>+ )}+ </ItemFooter>+ ) : null}+ </Item>+ </Fragment>+ ))}+ </div>+ ) : (+ <p className="text-muted-foreground text-sm">No runs yet.</p>+ )}+ </section>+ );+}++/**+ * A Bot's own words, drawn the way the conversation draws them.+ *+ * Progress, the last result and each run's reply are the Bot's markdown, and shown as plain text+ * they read as literal asterisks and backticks. Same renderer and components as the transcript, kept+ * to the row's size: no heading scale, tight paragraph and list spacing.+ */+function RunMarkdown({ children }: { children: string }) {+ return (+ <Streamdown+ className="min-w-0 text-sm [&_h1]:text-sm [&_h2]:text-sm [&_h3]:text-sm [&_li]:my-0 [&_ol]:my-1 [&_p]:my-1 [&_ul]:my-1 [&>*:first-child]:mt-0 [&>*:last-child]:mb-0"+ components={markdownComponents}+ mode="static"+ >+ {children}+ </Streamdown>+ );+}diff --git a/app/src/components/responsibilities/triggers.tsx b/app/src/components/responsibilities/triggers.tsxnew file mode 100644index 00000000..840e04f6--- /dev/null+++ b/app/src/components/responsibilities/triggers.tsx@@ -0,0 +1,756 @@+import {+ IconBellRinging,+ IconBrandGithub,+ IconBrandSlack,+ IconBug,+ IconListCheck,+ IconMail,+ IconPlus,+ IconWebhook,+} from "@tabler/icons-react";+import { useMutation, useQuery } from "@tanstack/react-query";+import { Fragment, useId, useState } from "react";+import { SharedAppNotice } from "@/components/plugins/shared-app-notice";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import {+ Field,+ FieldDescription,+ FieldGroup,+ FieldLabel,+} from "@/components/ui/field";+import { Input } from "@/components/ui/input";+import {+ Item,+ ItemActions,+ ItemContent,+ ItemDescription,+ ItemFooter,+ ItemMedia,+ ItemTitle,+} from "@/components/ui/item";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { Separator } from "@/components/ui/separator";+import { Switch } from "@/components/ui/switch";+import {+ createTriggerMutationOptions,+ type ResponsibilityRecord,+ removeTriggerMutationOptions,+ revealTriggerSecretMutationOptions,+ setTriggerEnabledMutationOptions,+ setTriggerSecretMutationOptions,+ type TriggerConfig,+ type TriggerKind,+ type TriggerRecord,+ triggersQueryOptions,+} from "@/lib/responsibilities";+import { queryClient } from "@/query-client";++export const KIND_LABEL: Record<TriggerKind, string> = {+ webhook: "Webhook",+ github: "GitHub",+ linear: "Linear",+ sentry: "Sentry",+ pagerduty: "PagerDuty",+ email: "Email",+ slack: "Slack",+};+const KIND_ICON: Record<TriggerKind, typeof IconWebhook> = {+ webhook: IconWebhook,+ github: IconBrandGithub,+ linear: IconListCheck,+ sentry: IconBug,+ pagerduty: IconBellRinging,+ email: IconMail,+ slack: IconBrandSlack,+};+const KIND_HELP: Record<TriggerKind, string> = {+ webhook:+ "POST JSON to the URL with the authorization header (or Standard Webhooks signature headers). 200 means accepted and queued, not finished.",+ github:+ "In the repository's Settings → Webhooks, set the payload URL to this URL, content type application/json, and the secret to the key.",+ linear:+ "In Linear, Settings → API → Webhooks: set the URL, then paste the signing secret Linear shows here.",+ sentry:+ "In a Sentry internal integration, set the webhook URL, then paste the integration's client secret here.",+ pagerduty:+ "In PagerDuty, Integrations → Generic Webhooks (v3): set the URL, then paste the secret shown on creation here.",+ email: "Send or forward mail to this address to start a run.",+ slack:+ "Fires from Slack events delivered through this Bot's Slack pairing. Messages from before the trigger existed are ignored.",+};+const VENDOR_SECRET: ReadonlySet<TriggerKind> = new Set([+ "linear",+ "sentry",+ "pagerduty",+]);+const SLACK_MODE = {+ mention: "The Bot is mentioned",+ phrase: "A message contains a phrase",+ reaction: "A reaction is added",+ message: "Any message",+} as const;+type SlackMode = keyof typeof SLACK_MODE;+const list = (value: string) =>+ value+ .split(",")+ .map((item) => item.trim())+ .filter(Boolean);++function CopyButton({ value, label }: { value: string; label: string }) {+ const [copied, setCopied] = useState(false);+ return (+ <Button+ size="sm"+ type="button"+ variant="outline"+ onClick={async () => {+ await navigator.clipboard.writeText(value);+ setCopied(true);+ setTimeout(() => setCopied(false), 1500);+ }}+ >+ {copied ? "Copied" : label}+ </Button>+ );+}++/** A value somebody copies into another product: a URL, an address, a key. */+function Copyable({ children }: { children: string }) {+ return (+ <code className="break-all rounded bg-background px-2 py-1 text-xs">+ {children}+ </code>+ );+}++function describeFilter(config: TriggerConfig) {+ if (config.kind === "slack") {+ const where = config.channels.length+ ? `in ${config.channels.join(", ")}`+ : "in every channel the Bot is in";+ const what =+ config.mode === "mention"+ ? "when the Bot is mentioned"+ : config.mode === "message"+ ? "on any message"+ : config.mode === "phrase"+ ? `on messages containing ${config.phrases.map((phrase) => `"${phrase}"`).join(" or ")}`+ : `on reactions${config.reactions.length ? ` :${config.reactions.join(": :")}:` : ""}`;+ return `${what} ${where} (workspace ${config.teamId})`;+ }+ const parts = [+ config.filter.eventTypes.length+ ? `events ${config.filter.eventTypes.join(", ")}`+ : "every event",+ ];+ if (config.filter.field)+ parts.push(+ `where ${config.filter.field.path} = ${config.filter.field.equals}`,+ );+ if (config.kind === "github" && config.repository)+ parts.push(`from ${config.repository}`);+ if (config.kind === "email" && config.allowedSenders.length)+ parts.push(`from ${config.allowedSenders.join(", ")} (authenticated)`);+ return parts.join(" ");+}++/**+ * What starts a responsibility from outside: one muted row per trigger inside the responsibility's+ * dialog, and a stacked dialog to add one. A fresh key is held here, keyed by trigger, so it survives+ * the list refetching after the write that produced it.+ */+export function Triggers({ goal }: { goal: ResponsibilityRecord }) {+ const triggers = useQuery(triggersQueryOptions(goal.id));+ const [adding, setAdding] = useState(false);+ const [freshSecret, setFreshSecret] = useState<{+ id: string;+ secret: string;+ } | null>(null);+ return (+ <section className="grid gap-2">+ <div className="flex items-center justify-between gap-2">+ <h3 className="font-medium text-sm">Triggers</h3>+ <Button+ size="sm"+ variant="outline"+ type="button"+ onClick={() => setAdding(true)}+ >+ <IconPlus />+ Add trigger+ </Button>+ </div>+ {goal.status !== "active" && (+ <p className="text-muted-foreground text-xs">+ This responsibility is {goal.status}, so its triggers are acknowledged+ but never run it.+ </p>+ )}+ {triggers.error && (+ <p role="alert" className="text-destructive text-sm">+ {triggers.error.message}+ </p>+ )}+ {triggers.data?.length === 0 && (+ <p className="text-muted-foreground text-xs">+ No triggers. It runs when you press Run now, or on the event+ subscriptions above.+ </p>+ )}+ {triggers.data?.length ? (+ <div className="overflow-hidden rounded-lg">+ {triggers.data.map((trigger, index) => (+ <Fragment key={trigger.id}>+ {index > 0 ? <Separator /> : null}+ <TriggerRow+ trigger={trigger}+ freshSecret={+ freshSecret?.id === trigger.id ? freshSecret.secret : null+ }+ onChanged={(secret) => {+ if (secret) setFreshSecret({ id: trigger.id, secret });+ }}+ />+ </Fragment>+ ))}+ </div>+ ) : null}+ {adding ? (+ <NewTriggerDialog+ goalId={goal.id}+ botId={goal.agentId}+ onClose={() => setAdding(false)}+ onCreated={(created) => {+ setAdding(false);+ if (created.secret)+ setFreshSecret({+ id: created.trigger.id,+ secret: created.secret,+ });+ }}+ />+ ) : null}+ </section>+ );+}++/**+ * One trigger. On or off is binary and immediate, so it is a Switch; what it takes to wire the+ * trigger up — its URL, its key, the vendor's signing secret — sits in the footer beneath, where it+ * has the row's whole width.+ */+function TriggerRow({+ trigger,+ freshSecret,+ onChanged,+}: {+ trigger: TriggerRecord;+ freshSecret: string | null;+ /** A write that produced a new key; the triggers list itself refetches from the write. */+ onChanged: (secret: string | null) => void;+}) {+ const [secret, setSecret] = useState<string | null>(freshSecret);+ const [pasted, setPasted] = useState("");+ const [confirmRemove, setConfirmRemove] = useState(false);+ const shown = freshSecret ?? secret;+ const reveal = useMutation(revealTriggerSecretMutationOptions());+ const rotate = useMutation(setTriggerSecretMutationOptions(queryClient));+ const remove = useMutation(removeTriggerMutationOptions(queryClient));+ const toggle = useMutation(setTriggerEnabledMutationOptions(queryClient));+ const rotateSecret = () =>+ rotate.mutate(+ {+ trigger,+ secret: VENDOR_SECRET.has(trigger.kind) ? pasted : undefined,+ },+ {+ onSuccess: (result) => {+ setPasted("");+ setSecret(result.secret);+ onChanged(result.secret);+ },+ },+ );+ const url = trigger.path ? `${window.location.origin}${trigger.path}` : null;+ const generated = trigger.kind === "webhook" || trigger.kind === "github";+ const Icon = KIND_ICON[trigger.kind];+ return (+ <Item size="sm" variant="muted">+ <ItemMedia variant="icon">+ <Icon />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>{KIND_LABEL[trigger.kind]}</ItemTitle>+ <ItemDescription className="line-clamp-none">+ {describeFilter(trigger.config)}+ {trigger.enabled ? "" : " · Paused"}+ </ItemDescription>+ </ItemContent>+ <ItemActions>+ {confirmRemove ? (+ <>+ <Button+ size="sm"+ variant="destructive"+ disabled={remove.isPending}+ onClick={() => remove.mutate(trigger)}+ >+ Remove for good+ </Button>+ <Button+ size="sm"+ variant="ghost"+ onClick={() => setConfirmRemove(false)}+ >+ Keep+ </Button>+ </>+ ) : (+ <>+ <Button+ size="sm"+ variant="ghost"+ onClick={() => setConfirmRemove(true)}+ >+ Remove+ </Button>+ <Switch+ aria-label={`Run on this ${KIND_LABEL[trigger.kind]} trigger`}+ checked={trigger.enabled}+ disabled={toggle.isPending}+ onCheckedChange={() =>+ toggle.mutate({ trigger, enabled: !trigger.enabled })+ }+ />+ </>+ )}+ </ItemActions>+ <ItemFooter className="flex-col items-stretch">+ <p className="text-muted-foreground text-xs">+ {KIND_HELP[trigger.kind]}+ </p>+ {url && (+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-xs">POST to</span>+ <Copyable>{url}</Copyable>+ <CopyButton value={url} label="Copy URL" />+ </div>+ )}+ {trigger.kind === "email" &&+ (trigger.address ? (+ <div className="flex flex-wrap items-center gap-2">+ <Copyable>{trigger.address}</Copyable>+ <CopyButton value={trigger.address} label="Copy address" />+ </div>+ ) : (+ <p className="text-amber-600 text-xs dark:text-amber-500">+ Inbound email is not configured on this deployment+ (OPENBOT_INBOUND_EMAIL_DOMAIN and+ OPENBOT_INBOUND_EMAIL_SNS_TOPIC_ARNS), so this address cannot+ receive mail yet.+ </p>+ ))}+ {generated && (+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-xs">Key</span>+ {shown ? (+ <>+ <Copyable>{shown}</Copyable>+ <CopyButton value={shown} label="Copy key" />+ {trigger.kind === "webhook" && (+ <CopyButton+ value={`Authorization: Bearer ${shown}`}+ label="Copy header"+ />+ )}+ </>+ ) : (+ <Button+ size="sm"+ variant="outline"+ disabled={reveal.isPending}+ onClick={() =>+ reveal.mutate(trigger.id, { onSuccess: setSecret })+ }+ >+ Show key+ </Button>+ )}+ <Button+ size="sm"+ variant="outline"+ disabled={rotate.isPending}+ onClick={rotateSecret}+ >+ Rotate key+ </Button>+ </div>+ )}+ {trigger.kind === "webhook" && shown && (+ <Copyable>{`Authorization: Bearer ${shown}`}</Copyable>+ )}+ {VENDOR_SECRET.has(trigger.kind) && (+ <form+ className="grid gap-2"+ onSubmit={(event) => {+ event.preventDefault();+ rotateSecret();+ }}+ >+ <span+ className={+ trigger.hasSecret+ ? "text-xs"+ : "text-amber-600 text-xs dark:text-amber-500"+ }+ >+ {trigger.hasSecret+ ? "Signing secret stored"+ : "Waiting for the signing secret"}+ </span>+ <div className="flex items-center gap-2">+ <Input+ aria-label="Signing secret"+ type="password"+ autoComplete="new-password"+ placeholder={+ trigger.hasSecret+ ? "Paste a new secret to rotate"+ : "Paste the signing secret"+ }+ value={pasted}+ onChange={(event) => setPasted(event.target.value)}+ required+ />+ <Button size="sm" type="submit" disabled={rotate.isPending}>+ Save secret+ </Button>+ </div>+ </form>+ )}+ {(reveal.error || rotate.error || remove.error || toggle.error) && (+ <p role="alert" className="text-destructive text-xs">+ {reveal.error?.message ??+ rotate.error?.message ??+ remove.error?.message ??+ toggle.error?.message}+ </p>+ )}+ </ItemFooter>+ </Item>+ );+}++/**+ * A new trigger, in a dialog stacked over the responsibility's own. The fields follow the kind: Slack+ * is a workspace, a mode and channels; every other kind is an event filter, plus a repository for+ * GitHub, senders for email, and a signing secret for the vendors that issue their own.+ */+function NewTriggerDialog({+ goalId,+ botId,+ onClose,+ onCreated,+}: {+ goalId: string;+ botId: string;+ onClose: () => void;+ onCreated: (created: {+ trigger: TriggerRecord;+ secret: string | null;+ }) => void;+}) {+ const id = useId();+ const [kind, setKind] = useState<TriggerKind>("webhook");+ const [eventTypes, setEventTypes] = useState("");+ const [fieldPath, setFieldPath] = useState("");+ const [fieldEquals, setFieldEquals] = useState("");+ const [repository, setRepository] = useState("");+ const [senders, setSenders] = useState("");+ const [secret, setSecret] = useState("");+ const [teamId, setTeamId] = useState("");+ const [mode, setMode] = useState<SlackMode>("mention");+ const [phrases, setPhrases] = useState("");+ const [reactions, setReactions] = useState("");+ const [channels, setChannels] = useState("");+ const config = (): TriggerConfig => {+ if (kind === "slack")+ return {+ kind,+ teamId: teamId.trim(),+ mode,+ phrases: list(phrases),+ reactions: list(reactions).map((reaction) =>+ reaction.replace(/:/g, ""),+ ),+ channels: list(channels),+ };+ const filter = {+ eventTypes: list(eventTypes),+ ...(fieldPath.trim() && fieldEquals.trim()+ ? { field: { path: fieldPath.trim(), equals: fieldEquals.trim() } }+ : {}),+ };+ if (kind === "github")+ return {+ kind,+ filter,+ ...(repository.trim() ? { repository: repository.trim() } : {}),+ };+ if (kind === "email")+ return { kind, filter, allowedSenders: list(senders) };+ return { kind, filter };+ };+ // The triggers list and the shared-app requests both refetch from the write itself.+ const create = useMutation(createTriggerMutationOptions(queryClient));+ const placeholder: Record<TriggerKind, string> = {+ webhook: "deploy.finished (blank: any)",+ github: "issues.opened, pull_request",+ linear: "Issue.create, Comment",+ sentry: "issue.created, event_alert.triggered",+ pagerduty: "incident.triggered",+ email: "received",+ slack: "",+ };+ return (+ <Dialog onOpenChange={(next) => !next && onClose()} open>+ {/* The heavier backdrop, forced: this stacks over the responsibility's dialog, and Base UI+ would otherwise render a nested dialog with no backdrop at all. */}+ <DialogContent overlayClassName="bg-black/20 supports-backdrop-filter:backdrop-blur-sm">+ <DialogHeader>+ <DialogTitle>Add trigger</DialogTitle>+ <DialogDescription>+ Something outside OpenBot that starts this responsibility.+ </DialogDescription>+ </DialogHeader>+ <DialogBody className="mt-4 overflow-y-auto">+ {/* The submit button is in the footer and reaches this form by id, so DialogBody stays a+ direct child of DialogContent and keeps scrolling. */}+ <form+ id={`${id}-form`}+ onSubmit={(event) => {+ event.preventDefault();+ create.mutate(+ {+ responsibilityId: goalId,+ input: {+ config: config(),+ ...(VENDOR_SECRET.has(kind) && secret ? { secret } : {}),+ },+ },+ { onSuccess: onCreated },+ );+ }}+ >+ <FieldGroup>+ <Field>+ <FieldLabel htmlFor={`${id}-kind`}>Trigger</FieldLabel>+ <Select+ items={KIND_LABEL}+ onValueChange={(value) => {+ if (value) setKind(value as TriggerKind);+ }}+ value={kind}+ >+ <SelectTrigger className="w-full" id={`${id}-kind`}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {(Object.keys(KIND_LABEL) as TriggerKind[]).map((value) => (+ <SelectItem key={value} value={value}>+ {KIND_LABEL[value]}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FieldDescription>{KIND_HELP[kind]}</FieldDescription>+ </Field>+ {kind === "slack" ? (+ <FieldGroup className="sm:grid sm:grid-cols-2">+ <Field>+ <FieldLabel htmlFor={`${id}-team`}>+ Slack team ID+ </FieldLabel>+ <Input+ id={`${id}-team`}+ required+ placeholder="T0123ABCD"+ value={teamId}+ onChange={(event) => setTeamId(event.target.value)}+ />+ </Field>+ <Field>+ <FieldLabel htmlFor={`${id}-mode`}>Fire on</FieldLabel>+ <Select+ items={SLACK_MODE}+ onValueChange={(value) => {+ if (value) setMode(value as SlackMode);+ }}+ value={mode}+ >+ <SelectTrigger className="w-full" id={`${id}-mode`}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {(Object.keys(SLACK_MODE) as SlackMode[]).map(+ (value) => (+ <SelectItem key={value} value={value}>+ {SLACK_MODE[value]}+ </SelectItem>+ ),+ )}+ </SelectContent>+ </Select>+ </Field>+ {mode === "phrase" && (+ <Field>+ <FieldLabel htmlFor={`${id}-phrases`}>+ Phrases (comma separated)+ </FieldLabel>+ <Input+ id={`${id}-phrases`}+ required+ value={phrases}+ onChange={(event) => setPhrases(event.target.value)}+ />+ </Field>+ )}+ {mode === "reaction" && (+ <Field>+ <FieldLabel htmlFor={`${id}-reactions`}>+ Reactions (blank: any)+ </FieldLabel>+ <Input+ id={`${id}-reactions`}+ placeholder="eyes, rotating_light"+ value={reactions}+ onChange={(event) => setReactions(event.target.value)}+ />+ </Field>+ )}+ <Field>+ <FieldLabel htmlFor={`${id}-channels`}>+ Channel IDs (blank: all the Bot is in)+ </FieldLabel>+ <Input+ id={`${id}-channels`}+ placeholder="C0123ABCD"+ value={channels}+ onChange={(event) => setChannels(event.target.value)}+ />+ </Field>+ </FieldGroup>+ ) : (+ <FieldGroup className="sm:grid sm:grid-cols-2">+ <Field className="sm:col-span-2">+ <FieldLabel htmlFor={`${id}-types`}>Event types</FieldLabel>+ <Input+ id={`${id}-types`}+ placeholder={placeholder[kind]}+ value={eventTypes}+ onChange={(event) => setEventTypes(event.target.value)}+ />+ </Field>+ <Field>+ <FieldLabel htmlFor={`${id}-path`}>+ Only when field+ </FieldLabel>+ <Input+ id={`${id}-path`}+ placeholder="data.team.key"+ value={fieldPath}+ onChange={(event) => setFieldPath(event.target.value)}+ />+ </Field>+ <Field>+ <FieldLabel htmlFor={`${id}-equals`}>equals</FieldLabel>+ <Input+ id={`${id}-equals`}+ placeholder="ENG"+ value={fieldEquals}+ onChange={(event) => setFieldEquals(event.target.value)}+ />+ </Field>+ {kind === "github" && (+ <Field className="sm:col-span-2">+ <FieldLabel htmlFor={`${id}-repo`}>+ Repository (optional)+ </FieldLabel>+ <Input+ id={`${id}-repo`}+ placeholder="owner/name"+ value={repository}+ onChange={(event) => setRepository(event.target.value)}+ />+ </Field>+ )}+ {kind === "email" && (+ <Field className="sm:col-span-2">+ <FieldLabel htmlFor={`${id}-senders`}>+ Allowed senders (blank: anyone)+ </FieldLabel>+ <Input+ id={`${id}-senders`}+ placeholder="[email protected], example.com"+ value={senders}+ onChange={(event) => setSenders(event.target.value)}+ />+ </Field>+ )}+ {VENDOR_SECRET.has(kind) && (+ <Field className="sm:col-span-2">+ <FieldLabel htmlFor={`${id}-secret`}>+ Signing secret (can be added later)+ </FieldLabel>+ <Input+ id={`${id}-secret`}+ type="password"+ autoComplete="new-password"+ value={secret}+ onChange={(event) => setSecret(event.target.value)}+ />+ </Field>+ )}+ </FieldGroup>+ )}+ </FieldGroup>+ </form>+ <SharedAppNotice botId={botId} reason="trigger" />+ {create.error && (+ <p role="alert" className="text-destructive text-sm">+ {create.error.message}+ </p>+ )}+ </DialogBody>+ <DialogFooter className="mt-4">+ <Button onClick={onClose} size="sm" type="button" variant="outline">+ Cancel+ </Button>+ <Button+ disabled={create.isPending}+ form={`${id}-form`}+ size="sm"+ type="submit"+ >+ {create.isPending ? "Adding…" : `Add ${KIND_LABEL[kind]} trigger`}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/app/src/components/routines/routines-list.tsx b/app/src/components/routines/routines-list.tsxindex dde704f5..07b1dd65 100644--- a/app/src/components/routines/routines-list.tsx+++ b/app/src/components/routines/routines-list.tsx@@ -1,31 +1,38 @@-import { IconHistory, IconPlayerPlay, IconTrash } from "@tabler/icons-react";+import {+ IconClock,+ IconHistory,+ IconPlayerPause,+ IconPlayerPlay,+ IconTrash,+} from "@tabler/icons-react";import { useMutation, useQuery } from "@tanstack/react-query";import { Link } from "@tanstack/react-router";-import { useState } from "react";-import { PageSection } from "@/components/layout/page-shell";+import { Fragment, useState } from "react";+import {+ PageEmpty,+ PageRows,+ PageSection,+} from "@/components/layout/page-shell";import { Button } from "@/components/ui/button";import {Dialog,+ DialogBody,DialogContent,DialogDescription,DialogFooter,DialogHeader,DialogTitle,} from "@/components/ui/dialog";-import {- Empty,- EmptyDescription,- EmptyHeader,- EmptyTitle,-} from "@/components/ui/empty";import {Item,ItemActions,ItemContent,ItemDescription,ItemFooter,+ ItemMedia,ItemTitle,} from "@/components/ui/item";+import { Separator } from "@/components/ui/separator";import { Switch } from "@/components/ui/switch";import { relativeTime } from "@/lib/relative-time";import {@@ -105,7 +112,7 @@ function lastRunLabel(lastRun: RoutineRecord["lastRun"]): {/*** One fact about a routine, worn as a small pill so the footer reads as a row of states rather- * than a sentence. On the muted item the pill's own background is what keeps it legible.+ * than a sentence.*/function Chip({className,@@ -152,8 +159,8 @@ const RUN_STATUS: Record</** Every firing of one routine, newest first, each linking to the thread it ran in. */function RoutineRuns({ routine }: { routine: RoutineRecord }) {const runs = useQuery(routineRunsQueryOptions(routine.id));- if (runs.isPending)- return <p className="text-muted-foreground text-xs">Loading runs…</p>;+ // Pending renders nothing: "No runs yet." would otherwise flash for the fetch.+ if (runs.isPending) return null;if (runs.error)return (<p className="text-destructive text-xs" role="alert">@@ -213,7 +220,7 @@ function RoutineRuns({ routine }: { routine: RoutineRecord }) {* The signed-in person's standing instructions: a switch to stop one taking effect, and a delete* that ends it for good.*- * Scoped by `agentId` on a Bot's own dialog, unscoped on the Routines page. One query either way —+ * Scoped by `agentId` on a Bot's Routines page, unscoped on the Routines page. One query either way —* the list is owner-scoped and small, so the scope is a filter here rather than a second endpoint.*/export function RoutinesList({@@ -222,7 +229,7 @@ export function RoutinesList({}: {/** Show only the routines this Bot carries out. Absent shows all of the person's. */agentId?: string;- /** Inside a dialog, where the page section's own top margin is somebody else's spacing. */+ /** Where the page section's own top margin is somebody else's spacing. */embedded?: boolean;} = {}) {const routines = useQuery(routinesQueryOptions());@@ -243,28 +250,21 @@ export function RoutinesList({return (<PageSection className={embedded ? "mt-0" : undefined}>{setEnabled.error || runNow.error ? (- <p className="text-destructive text-sm" role="alert">+ <p className="mt-4 text-destructive text-sm" role="alert">{setEnabled.error?.message ?? runNow.error?.message}</p>) : null}+ {/* A fact about the deployment rather than a row to act on, so said as a sentence. */}{noWorker ? (- <Item- variant="muted"- className="mb-2 border-amber-500/40 bg-amber-500/5"- role="alert"- >- <ItemContent>- <ItemTitle className="text-amber-600 dark:text-amber-500">- Nothing is running these- </ItemTitle>- <ItemDescription>- {sweep?.lastSweptAt- ? `The routines worker last checked ${relativeTime(sweep.lastSweptAt)}. Until it is running again, none of these will fire.`- : "No routines worker has ever checked in, so none of these will fire. A deployment needs one running to carry them out."}- </ItemDescription>- </ItemContent>- </Item>+ <p className="mt-4 text-muted-foreground text-sm" role="alert">+ <span className="font-medium text-amber-600 dark:text-amber-500">+ Nothing is running these.+ </span>{" "}+ {sweep?.lastSweptAt+ ? `The routines worker last checked ${relativeTime(sweep.lastSweptAt)}. Until it is running again, none of these will fire.`+ : "No routines worker has ever checked in, so none of these will fire. A deployment needs one running to carry them out."}+ </p>) : null}{/* Pending renders nothing: the empty-state sentence would otherwise flash for the fetch. */}@@ -273,40 +273,60 @@ export function RoutinesList({Your routines could not be loaded.</p>) : rows.length === 0 ? (- <Empty className="h-[180px] border border-dashed">- <EmptyHeader>- <EmptyTitle className="text-muted-foreground">- {agentId- ? "Nothing scheduled for this coworker"- : "Nothing scheduled"}- </EmptyTitle>- <EmptyDescription>- {agentId- ? 'Ask it in a channel — "every weekday at 9, …" — and it will appear here.'- : 'Ask a Bot — "every weekday at 9, …" — and it will appear here.'}- </EmptyDescription>- </EmptyHeader>- </Empty>+ <PageEmpty>+ {agentId+ ? 'Nothing scheduled for this coworker. Ask it in a channel — "every weekday at 9, …" — and it will appear here.'+ : 'Nothing scheduled. Ask a Bot — "every weekday at 9, …" — and it will appear here.'}+ </PageEmpty>) : (- <div className="flex flex-col gap-2">- {rows.map((routine) => {+ <PageRows>+ {rows.map((routine, index) => {const lastRun = lastRunLabel(routine.lastRun);return (- <Item key={routine.id} variant="muted">- {/* Paused reads at a glance: the content dims, and a chip below says the word. */}- <ItemContent className={routine.enabled ? "" : "opacity-60"}>- <ItemTitle>- {routine.schedule}- <span className="font-normal text-muted-foreground text-xs">- {routine.timezone}- </span>- </ItemTitle>- <ItemDescription className="line-clamp-2">- {routine.instruction}- </ItemDescription>- {/* A set, so it wraps onto its own line rather than crowding the title. */}- <ItemFooter>- <div className="flex flex-wrap items-center gap-1.5">+ <Fragment key={routine.id}>+ {index > 0 ? <Separator /> : null}+ <Item size="sm">+ <ItemMedia variant="icon">+ {routine.enabled ? <IconClock /> : <IconPlayerPause />}+ </ItemMedia>+ {/* Paused reads at a glance: the content dims, and a chip below says the word. */}+ <ItemContent className={routine.enabled ? "" : "opacity-60"}>+ <ItemTitle>+ {routine.schedule}+ <span className="font-normal text-muted-foreground text-xs">+ {routine.timezone}+ </span>+ </ItemTitle>+ <ItemDescription>{routine.instruction}</ItemDescription>+ </ItemContent>+ <ItemActions>+ {/*+ * Binary and immediate: it takes effect when switched, there is no save.+ * Disabled only while its own write is in flight, so switching one routine+ * does not freeze the rest of the list — the same idiom the per-tool plugins+ * page uses for its per-Bot grant switches.+ */}+ <Switch+ aria-label={`Enable the routine scheduled ${routine.schedule}`}+ checked={routine.enabled}+ disabled={+ setEnabled.isPending &&+ setEnabled.variables?.id === routine.id+ }+ onCheckedChange={(next) =>+ setEnabled.mutate({ id: routine.id, enabled: next })+ }+ />+ </ItemActions>+ {/* Two sets — where it stands, and what can be done to it — so they wrap onto a+ line of their own rather than crowding the title. */}+ <ItemFooter className="flex-wrap">+ <div+ className={cn(+ "flex flex-wrap items-center gap-1.5",+ routine.enabled ? "" : "opacity-60",+ )}+ >{routine.channel.gone ? (<Chip className="border-destructive/40 text-destructive">This channel is gone@@ -352,88 +372,75 @@ export function RoutinesList({</Chip>)}</div>+ <div className="flex items-center gap-1">+ {/*+ * Run now is the Test button, and it does real work: the Bot carries out the+ * instruction in the channel right away. Offered only while the routine is+ * on, because a paused routine never runs.+ */}+ <Button+ aria-label={`Run the routine scheduled ${routine.schedule} now`}+ disabled={+ !routine.enabled ||+ (runNow.isPending && runNow.variables === routine.id)+ }+ onClick={() =>+ runNow.mutate(routine.id, {+ onSuccess: () => setHistoryId(routine.id),+ })+ }+ size="sm"+ title={+ routine.enabled+ ? "Runs it for real, now: the Bot does the work and posts in the channel."+ : "Paused routines never run. Switch it on first."+ }+ type="button"+ variant="outline"+ >+ <IconPlayerPlay />+ Run now+ </Button>+ <Button+ aria-expanded={historyId === routine.id}+ aria-label={`Run history for the routine scheduled ${routine.schedule}`}+ onClick={() =>+ setHistoryId(+ historyId === routine.id ? null : routine.id,+ )+ }+ size="sm"+ type="button"+ variant="ghost"+ >+ <IconHistory />+ History+ </Button>+ <Button+ aria-label={`Delete the routine scheduled ${routine.schedule}`}+ onClick={() => {+ deleteRoutine.reset();+ setConfirmingId(routine.id);+ }}+ size="sm"+ type="button"+ variant="ghost"+ >+ <IconTrash />+ Delete+ </Button>+ </div></ItemFooter>{historyId === routine.id ? (- <div className="mt-2 border-border border-t pt-2">+ <div className="basis-full border-border border-t pt-2"><RoutineRuns routine={routine} /></div>) : null}- </ItemContent>- <ItemActions>- {/*- * Run now is the Test button, and it does real work: the Bot carries out the- * instruction in the channel right away. Offered only while the routine is on,- * because a paused routine never runs.- */}- <Button- aria-label={`Run the routine scheduled ${routine.schedule} now`}- disabled={- !routine.enabled ||- (runNow.isPending && runNow.variables === routine.id)- }- onClick={() =>- runNow.mutate(routine.id, {- onSuccess: () => setHistoryId(routine.id),- })- }- size="sm"- title={- routine.enabled- ? "Runs it for real, now: the Bot does the work and posts in the channel."- : "Paused routines never run. Switch it on first."- }- type="button"- variant="outline"- >- <IconPlayerPlay />- Run now- </Button>- <Button- aria-expanded={historyId === routine.id}- aria-label={`Run history for the routine scheduled ${routine.schedule}`}- onClick={() =>- setHistoryId(historyId === routine.id ? null : routine.id)- }- size="icon-sm"- type="button"- variant="ghost"- >- <IconHistory />- </Button>- {/*- * Binary and immediate: it takes effect when switched, there is no save.- * Disabled only while its own write is in flight, so switching one routine- * does not freeze the rest of the list — the same idiom the per-tool plugins- * page uses for its per-Bot grant switches.- */}- <Switch- aria-label={`Enable the routine scheduled ${routine.schedule}`}- checked={routine.enabled}- disabled={- setEnabled.isPending &&- setEnabled.variables?.id === routine.id- }- onCheckedChange={(next) =>- setEnabled.mutate({ id: routine.id, enabled: next })- }- />- <Button- aria-label={`Delete the routine scheduled ${routine.schedule}`}- onClick={() => {- deleteRoutine.reset();- setConfirmingId(routine.id);- }}- size="icon-sm"- type="button"- variant="ghost"- >- <IconTrash />- </Button>- </ItemActions>- </Item>+ </Item>+ </Fragment>);})}- </div>+ </PageRows>)}{/*@@ -459,15 +466,18 @@ export function RoutinesList({</DialogDescription></DialogHeader>{deleteRoutine.error ? (- <p className="text-destructive text-sm" role="alert">- {deleteRoutine.error.message}- </p>+ <DialogBody className="mt-4">+ <p className="text-destructive text-sm" role="alert">+ {deleteRoutine.error.message}+ </p>+ </DialogBody>) : null}- <DialogFooter>+ <DialogFooter className="mt-4"><ButtononClick={() => setConfirmingId(null)}size="sm"- variant="ghost"+ type="button"+ variant="outline">Cancel</Button>@@ -480,6 +490,7 @@ export function RoutinesList({});}}size="sm"+ type="button"variant="destructive">{deleteRoutine.isPending ? "Deleting…" : "Delete"}diff --git a/app/src/components/settings/devices.tsx b/app/src/components/settings/devices.tsxnew file mode 100644index 00000000..4419a9f5--- /dev/null+++ b/app/src/components/settings/devices.tsx@@ -0,0 +1,122 @@+import { IconDeviceMobile, IconSend } from "@tabler/icons-react";+import { useMutation, useQuery } from "@tanstack/react-query";+import { Fragment } from "react";+import {+ PageEmpty,+ PageRows,+ PageSection,+} from "@/components/layout/page-shell";+import { Button } from "@/components/ui/button";+import {+ Item,+ ItemActions,+ ItemContent,+ ItemDescription,+ ItemMedia,+ ItemTitle,+} from "@/components/ui/item";+import { Separator } from "@/components/ui/separator";+import {+ deliveryQueryOptions,+ removePushDeviceMutationOptions,+} from "@/lib/delivery";+import { queryClient } from "@/query-client";++const PLATFORM: Record<"ios" | "android", string> = {+ ios: "iOS",+ android: "Android",+};++/** The phones that receive push notifications for every one of the person's Bots. */+export function NativeDevices() {+ const reach = useQuery(deliveryQueryOptions());+ const remove = useMutation(removePushDeviceMutationOptions(queryClient));+ const error = reach.error ?? remove.error;+ return (+ <PageSection+ description="Sign in to the OpenBot app on your phone and turn on notifications to add it here."+ title="Your devices"+ >+ {error ? (+ <p className="mt-4 text-destructive text-sm" role="alert">+ {error.message}+ </p>+ ) : null}+ {reach.isPending || !reach.data ? null : reach.data.devices.length ===+ 0 ? (+ <PageEmpty>No devices yet.</PageEmpty>+ ) : (+ <PageRows>+ {reach.data.devices.map((device, index) => (+ <Fragment key={device.id}>+ {index > 0 ? <Separator /> : null}+ <Item size="sm">+ <ItemMedia variant="icon">+ <IconDeviceMobile />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>{PLATFORM[device.platform]}</ItemTitle>+ </ItemContent>+ <ItemActions>+ <Button+ disabled={remove.isPending}+ onClick={() => remove.mutate(device.id)}+ size="sm"+ variant="outline"+ >+ Remove+ </Button>+ </ItemActions>+ </Item>+ </Fragment>+ ))}+ </PageRows>+ )}+ </PageSection>+ );+}++/** What was sent to the person outside the web app, most recent first, with any failure. */+export function RecentDeliveries() {+ const reach = useQuery(deliveryQueryOptions());+ return (+ <PageSection title="Recent deliveries">+ {reach.error ? (+ <p className="mt-4 text-destructive text-sm" role="alert">+ {reach.error.message}+ </p>+ ) : null}+ {reach.isPending || !reach.data ? null : reach.data.deliveries.length ===+ 0 ? (+ <PageEmpty>No deliveries yet.</PageEmpty>+ ) : (+ <PageRows>+ {reach.data.deliveries.map((delivery, index) => (+ <Fragment key={delivery.id}>+ {index > 0 ? <Separator /> : null}+ <Item size="sm">+ <ItemMedia variant="icon">+ <IconSend />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>+ {delivery.transport} · {delivery.kind}+ </ItemTitle>+ <ItemDescription>+ {delivery.state} ·{" "}+ {new Date(delivery.createdAt).toLocaleString()}+ </ItemDescription>+ {delivery.error ? (+ <ItemDescription className="line-clamp-none text-destructive">+ {delivery.error}+ </ItemDescription>+ ) : null}+ </ItemContent>+ </Item>+ </Fragment>+ ))}+ </PageRows>+ )}+ </PageSection>+ );+}diff --git a/app/src/components/settings/github-sources.tsx b/app/src/components/settings/github-sources.tsxnew file mode 100644index 00000000..39e2b919--- /dev/null+++ b/app/src/components/settings/github-sources.tsx@@ -0,0 +1,190 @@+import { IconBrandGithub, IconPlus } from "@tabler/icons-react";+import { useMutation, useQuery } from "@tanstack/react-query";+import { Fragment, useId, useState } from "react";+import {+ PageEmpty,+ PageRows,+ PageSection,+} from "@/components/layout/page-shell";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Field, FieldGroup, FieldLabel } from "@/components/ui/field";+import { Input } from "@/components/ui/input";+import {+ Item,+ ItemActions,+ ItemContent,+ ItemDescription,+ ItemMedia,+ ItemTitle,+} from "@/components/ui/item";+import { Separator } from "@/components/ui/separator";+import {+ createGithubBindingMutationOptions,+ githubBindingsQueryOptions,+ removeGithubBindingMutationOptions,+} from "@/lib/responsibilities";+import { queryClient } from "@/query-client";++/**+ * The repositories whose GitHub events can start this person's responsibilities. One per person, not+ * per Bot: an event reaches every responsibility subscribed to it, whichever Bot holds it.+ *+ * Each repository is a row carrying the webhook address to paste into GitHub. Adding one is two+ * inputs, so it is a dialog opened from the section's action.+ */+export function GithubSources() {+ const bindings = useQuery(githubBindingsQueryOptions());+ const remove = useMutation(removeGithubBindingMutationOptions(queryClient));+ const [adding, setAdding] = useState(false);+ const error = bindings.error ?? remove.error;+ return (+ <PageSection+ action={+ <Button onClick={() => setAdding(true)} size="sm" variant="ghost">+ <IconPlus />+ Add a repository+ </Button>+ }+ description="Register a repository, then add its webhook in GitHub using the address below and the same secret. A responsibility can then start on one of its events, such as issues.opened."+ title="GitHub events"+ >+ {error ? (+ <p className="mt-4 text-destructive text-sm" role="alert">+ {error.message}+ </p>+ ) : null}+ {bindings.isPending || !bindings.data ? null : bindings.data.length ===+ 0 ? (+ <PageEmpty>No repositories connected.</PageEmpty>+ ) : (+ <PageRows>+ {bindings.data.map((binding, index) => (+ <Fragment key={binding.id}>+ {index > 0 ? <Separator /> : null}+ <Item size="sm">+ <ItemMedia variant="icon">+ <IconBrandGithub />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>{binding.repository}</ItemTitle>+ <ItemDescription className="line-clamp-none break-all font-mono text-xs">+ {window.location.origin}/api/events/github/{binding.id}+ </ItemDescription>+ </ItemContent>+ <ItemActions>+ <Button+ disabled={remove.isPending}+ onClick={() => remove.mutate(binding.id)}+ size="sm"+ variant="outline"+ >+ Disconnect+ </Button>+ </ItemActions>+ </Item>+ </Fragment>+ ))}+ </PageRows>+ )}+ {adding ? <AddRepositoryDialog onClose={() => setAdding(false)} /> : null}+ </PageSection>+ );+}++/**+ * A repository and the webhook secret GitHub will sign its events with.+ */+function AddRepositoryDialog({ onClose }: { onClose: () => void }) {+ const formId = useId();+ const [repository, setRepository] = useState("");+ const [secret, setSecret] = useState("");+ const create = useMutation(createGithubBindingMutationOptions(queryClient));+ return (+ <Dialog onOpenChange={(next) => !next && onClose()} open>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Add a repository</DialogTitle>+ <DialogDescription>+ Use the same secret when you add the webhook in GitHub.+ </DialogDescription>+ </DialogHeader>+ <DialogBody className="mt-4">+ {/* The submit button is in the footer and reaches this form by id, so DialogBody stays a+ direct child of DialogContent and keeps scrolling. */}+ <form+ id={formId}+ onSubmit={(event) => {+ event.preventDefault();+ create.mutate(+ { repository, secret },+ {+ onSuccess: () => {+ setSecret("");+ setRepository("");+ onClose();+ },+ },+ );+ }}+ >+ <FieldGroup>+ <Field>+ <FieldLabel htmlFor={`${formId}-repository`}>+ Repository+ </FieldLabel>+ <Input+ autoFocus+ id={`${formId}-repository`}+ onChange={(event) => setRepository(event.target.value)}+ placeholder="owner/repository"+ required+ value={repository}+ />+ </Field>+ <Field>+ <FieldLabel htmlFor={`${formId}-secret`}>+ Webhook secret+ </FieldLabel>+ <Input+ autoComplete="new-password"+ id={`${formId}-secret`}+ onChange={(event) => setSecret(event.target.value)}+ required+ type="password"+ value={secret}+ />+ </Field>+ </FieldGroup>+ </form>+ {create.error ? (+ <p className="text-destructive text-sm" role="alert">+ {create.error.message}+ </p>+ ) : null}+ </DialogBody>+ <DialogFooter className="mt-4">+ <Button onClick={onClose} size="sm" variant="outline">+ Cancel+ </Button>+ <Button+ disabled={create.isPending}+ form={formId}+ size="sm"+ type="submit"+ >+ Connect events+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/app/src/components/settings/settings-sidebar.tsx b/app/src/components/settings/settings-sidebar.tsxindex 90266de5..76979685 100644--- a/app/src/components/settings/settings-sidebar.tsx+++ b/app/src/components/settings/settings-sidebar.tsx@@ -1,5 +1,8 @@import {IconArrowLeft,+ IconBell,+ IconBrain,+ IconChecks,IconKey,IconLayoutGrid,IconPlug,@@ -39,6 +42,24 @@ const ITEMS: {exact: true,linkOptions: { to: "/settings" },},+ {+ /* Where updates go for every Bot at once; how much each Bot sends is on that Bot's page. */+ title: "Notifications",+ icon: IconBell,+ linkOptions: { to: "/settings/notifications" },+ },+ {+ /* Whether Bots ask first, and rules for every Bot. Team settings are an administrator's. */+ title: "Approvals",+ icon: IconChecks,+ linkOptions: { to: "/settings/approvals" },+ },+ {+ /* What your Bots know about you, across all of them. */+ title: "Memory",+ icon: IconBrain,+ linkOptions: { to: "/settings/memory" },+ },{/** The same subject as Admin's Plugins, from the other side: there an administrator decides whatdiff --git a/app/src/components/settings/update-routing.tsx b/app/src/components/settings/update-routing.tsxnew file mode 100644index 00000000..1bf932b3--- /dev/null+++ b/app/src/components/settings/update-routing.tsx@@ -0,0 +1,137 @@+import { IconRoute } from "@tabler/icons-react";+import { useMutation, useQuery } from "@tanstack/react-query";+import { Fragment } from "react";+import { PageRows, PageSection } from "@/components/layout/page-shell";+import {+ Item,+ ItemContent,+ ItemDescription,+ ItemFooter,+ ItemMedia,+ ItemTitle,+} from "@/components/ui/item";+import { Separator } from "@/components/ui/separator";+import { Switch } from "@/components/ui/switch";+import { setUpdateRoutingMutationOptions } from "@/lib/bot-lifecycle/mutations";+import { deliveryQueryOptions } from "@/lib/delivery";+import {+ type UpdateKind,+ type UpdateTransport,+ updateRoutingQueryOptions,+} from "@/lib/bot-lifecycle/queries";+import { queryClient } from "@/query-client";++const KIND_LABEL: Record<UpdateKind, { title: string; description: string }> = {+ progress: {+ title: "Progress",+ description: "Replies and results from work you were not watching.",+ },+ decision: {+ title: "Decisions",+ description: "Approvals a Bot needs before it acts.",+ },+ question: {+ title: "Questions",+ description: "Things a Bot asked you and is waiting on.",+ },+};++const TRANSPORTS: { id: UpdateTransport; label: string }[] = [+ { id: "push", label: "Push" },+ { id: "slack", label: "Slack" },+ { id: "teams", label: "Microsoft Teams" },+ { id: "sms", label: "SMS" },+];++/**+ * Which channels each kind of update may use, for every one of the person's Bots at once. How much+ * a given Bot sends is that Bot's own Notifications setting, on its page.+ */+export function UpdateRoutingSection() {+ const routing = useQuery(updateRoutingQueryOptions());+ const reach = useQuery(deliveryQueryOptions());+ const save = useMutation(setUpdateRoutingMutationOptions(queryClient));+ /*+ * A channel this deployment has not set up can carry nothing, so its switch is off and disabled+ * whatever the stored preference says, rather than on beside a channel that delivers nothing. The+ * preference itself is left alone: an administrator who configures Slack later finds it as the+ * person last set it. When the deployment's channels could not be read, the preference is shown+ * as it is rather than every channel claimed unavailable.+ */+ const configured = (transport: UpdateTransport) =>+ reach.data ? reach.data.available[transport] : true;+ return (+ <PageSection+ description="Where each kind of update goes when you are not looking. The web always shows everything."+ title="Where updates go"+ >+ {routing.isPending || reach.isPending ? null : routing.error ? (+ <p className="mt-4 text-destructive text-sm" role="alert">+ Could not load where your updates go.+ </p>+ ) : (+ <PageRows>+ {(Object.keys(KIND_LABEL) as UpdateKind[]).map((kind, index) => {+ const current = routing.data[kind];+ const allowed = (transport: UpdateTransport) =>+ current === "all" || current.includes(transport);+ return (+ <Fragment key={kind}>+ {index > 0 ? <Separator /> : null}+ <Item size="sm">+ <ItemMedia variant="icon">+ <IconRoute />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>{KIND_LABEL[kind].title}</ItemTitle>+ <ItemDescription>+ {KIND_LABEL[kind].description}+ </ItemDescription>+ </ItemContent>+ <ItemFooter className="flex-wrap justify-start gap-x-6 gap-y-3 pl-8">+ {TRANSPORTS.map((transport) => (+ <div+ className="flex items-center gap-2 text-sm"+ key={transport.id}+ >+ <Switch+ aria-label={`${KIND_LABEL[kind].title} by ${transport.label}`}+ checked={+ configured(transport.id) && allowed(transport.id)+ }+ disabled={save.isPending || !configured(transport.id)}+ onCheckedChange={(checked) => {+ const next = TRANSPORTS.map((t) => t.id).filter(+ (id) =>+ id === transport.id ? checked : allowed(id),+ );+ save.mutate({+ kind,+ transports:+ next.length === TRANSPORTS.length+ ? "all"+ : next,+ });+ }}+ size="sm"+ />+ <span className="flex flex-col leading-tight whitespace-nowrap">+ {transport.label}+ {configured(transport.id) ? null : (+ <span className="text-muted-foreground text-xs">+ Not set up+ </span>+ )}+ </span>+ </div>+ ))}+ </ItemFooter>+ </Item>+ </Fragment>+ );+ })}+ </PageRows>+ )}+ </PageSection>+ );+}diff --git a/app/src/components/suggestions/proactive-panel.tsx b/app/src/components/suggestions/proactive-panel.tsxindex 39f2582d..0517e987 100644--- a/app/src/components/suggestions/proactive-panel.tsx+++ b/app/src/components/suggestions/proactive-panel.tsx@@ -1,134 +1,251 @@+import {+ IconBulb,+ IconChevronRight,+ IconClock,+ IconPlus,+ IconRadar,+} from "@tabler/icons-react";import { useInfiniteQuery, useMutation, useQuery } from "@tanstack/react-query";-import { useId, useState } from "react";+import { Fragment, useId, useState } from "react";+import {+ PageEmpty,+ PageRows,+ PageSection,+} from "@/components/layout/page-shell";import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Field, FieldGroup, FieldLabel } from "@/components/ui/field";import { Input } from "@/components/ui/input";+import {+ Item,+ ItemActions,+ ItemContent,+ ItemDescription,+ ItemFooter,+ ItemMedia,+ ItemTitle,+} from "@/components/ui/item";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { Separator } from "@/components/ui/separator";import { agentListQueryOptions } from "@/lib/agents/queries";import { conversationLabel } from "@/lib/channels/label";import { channelListQueryOptions } from "@/lib/channels/queries";import {- createProactiveSetting,+ changeProactiveSettingMutationOptions,+ createProactiveSettingMutationOptions,type ProactiveSetting,- proactiveKeys,proactiveSettingsQueryOptions,proactiveSuggestionsQueryOptions,- removeProactiveSetting,- resolveSuggestion,- runProactiveNow,- updateProactiveSetting,+ resolveSuggestionMutationOptions,} from "@/lib/proactive";import { queryClient } from "@/query-client";-const field = "grid gap-1 text-sm";-const select = "h-9 rounded-md border bg-background px-3 text-sm";const intervals = [{ minutes: 60, label: "Every hour" },{ minutes: 240, label: "Every 4 hours" },{ minutes: 720, label: "Twice a day" },{ minutes: 1440, label: "Once a day" },];-async function refresh() {- await Promise.all([- queryClient.invalidateQueries({ queryKey: proactiveKeys.settings }),- queryClient.invalidateQueries({ queryKey: proactiveKeys.suggestions }),- ]);-}-+/** The label map, so a closed trigger says "Every 4 hours" rather than 240. */+const intervalItems = intervals.map((interval) => ({+ value: interval.minutes,+ label: interval.label,+}));+const intervalLabel = (minutes: number) =>+ intervals.find((interval) => interval.minutes === minutes)?.label ??+ `Every ${minutes} minutes`;/** Next steps a Bot proposed from background research: start one as a task, or dismiss it. */-export function SuggestionsInbox() {+export function SuggestionsInbox({+ agentId,+}: {+ /** Only this Bot's suggestions, and nothing at all when it has none. */+ agentId?: string;+} = {}) {const suggestions = useQuery(proactiveSuggestionsQueryOptions());+ const shown = (suggestions.data ?? []).filter(+ (suggestion) => agentId === undefined || suggestion.agentId === agentId,+ );const bots = useQuery(agentListQueryOptions());- const act = useMutation({- mutationFn: ({ id, action }: { id: string; action: "start" | "dismiss" }) =>- resolveSuggestion(id, action),- onSuccess: refresh,- });+ const act = useMutation(resolveSuggestionMutationOptions(queryClient));const botName = (id: string) =>bots.data?.find((bot) => bot.id === id)?.name ?? "Your Bot";+ if (agentId !== undefined && shown.length === 0) return null;return (- <section className="grid gap-3">- <h2 className="font-semibold">Suggested next steps</h2>- {suggestions.isPending ? (- <p>Loading suggestions…</p>- ) : suggestions.error ? (- <p role="alert" className="text-destructive">+ <PageSection title="Suggested next steps">+ {suggestions.isPending ? null : suggestions.error ? (+ <p role="alert" className="mt-4 text-destructive text-sm">{suggestions.error.message}</p>- ) : suggestions.data?.length ? (- suggestions.data.map((suggestion) => (- <article- key={suggestion.id}- className="grid gap-2 rounded-lg border p-4"- >- <div className="flex flex-wrap justify-between gap-2">- <strong>{suggestion.title}</strong>- <span className="text-xs text-muted-foreground">- {botName(suggestion.agentId)} ·{" "}- {new Date(suggestion.createdAt).toLocaleString()}- </span>- </div>- <p className="text-sm whitespace-pre-wrap">{suggestion.detail}</p>- {(suggestion.sourceApp || suggestion.sourceLink) && (- <p className="text-xs text-muted-foreground">- From {suggestion.sourceApp ?? "a connected app"}- {suggestion.sourceLink && (- <>- {" · "}- <a- className="underline"- href={suggestion.sourceLink}- target="_blank"- rel="noreferrer"- >- Open record- </a>- </>- )}- </p>- )}- <div className="flex flex-wrap gap-2">- <Button- size="sm"- disabled={act.isPending}- onClick={() =>- act.mutate({ id: suggestion.id, action: "start" })- }- >- Start as task- </Button>- <Button- size="sm"- variant="outline"- disabled={act.isPending}- onClick={() =>- act.mutate({ id: suggestion.id, action: "dismiss" })- }- >- Dismiss- </Button>- </div>- </article>- ))+ ) : shown.length ? (+ <PageRows>+ {shown.map((suggestion, index) => (+ <Fragment key={suggestion.id}>+ {index > 0 ? <Separator /> : null}+ <Item size="sm">+ <ItemMedia variant="icon">+ <IconBulb />+ </ItemMedia>+ <ItemContent>+ <ItemTitle className="line-clamp-none">+ {suggestion.title}+ </ItemTitle>+ {suggestion.detail ? (+ <ItemDescription className="line-clamp-none whitespace-pre-wrap text-foreground">+ {suggestion.detail}+ </ItemDescription>+ ) : null}+ <ItemDescription className="line-clamp-none">+ {botName(suggestion.agentId)} ·{" "}+ {new Date(suggestion.createdAt).toLocaleString()}+ {suggestion.sourceApp || suggestion.sourceLink ? (+ <>+ {" · "}From {suggestion.sourceApp ?? "a connected app"}+ {suggestion.sourceLink && (+ <>+ {" · "}+ <a+ href={suggestion.sourceLink}+ target="_blank"+ rel="noreferrer"+ >+ Open record+ </a>+ </>+ )}+ </>+ ) : null}+ </ItemDescription>+ {/* A set, so it wraps onto its own line rather than crowding the title. */}+ <ItemFooter>+ <div className="flex flex-wrap gap-2">+ <Button+ size="sm"+ disabled={act.isPending}+ onClick={() =>+ act.mutate({ id: suggestion.id, action: "start" })+ }+ >+ Start as task+ </Button>+ <Button+ size="sm"+ variant="outline"+ disabled={act.isPending}+ onClick={() =>+ act.mutate({ id: suggestion.id, action: "dismiss" })+ }+ >+ Dismiss+ </Button>+ </div>+ </ItemFooter>+ </ItemContent>+ </Item>+ </Fragment>+ ))}+ </PageRows>) : (- <p className="text-muted-foreground">+ <PageEmpty>No suggestions right now. Bots with background research on willsuggest next steps here.- </p>+ </PageEmpty>)}{act.error && (- <p role="alert" className="text-destructive">+ <p role="alert" className="mt-4 text-destructive text-sm">{act.error.message}</p>)}- </section>+ </PageSection>);}-/** Opt a Bot in to read-only background research of the apps it can already read. */-export function ProactiveResearchSettings() {+/**+ * Opt a Bot in to read-only background research of the apps it can already read.+ *+ * Each opt-in is a row stating its current answer; it opens a dialog to change how often, run it,+ * turn it off or remove it. Opting in is a dialog behind the section's action.+ */+export function ProactiveResearchSettings({+ agentId: fixedBot,+}: {+ /** Only this Bot's research, and a new one is this Bot's without asking. */+ agentId?: string;+} = {}) {const settings = useQuery(proactiveSettingsQueryOptions());+ const bots = useQuery(agentListQueryOptions());+ const [adding, setAdding] = useState(false);+ const shown = (settings.data ?? []).filter(+ (setting) => fixedBot === undefined || setting.agentId === fixedBot,+ );+ return (+ <PageSection+ action={+ <Button onClick={() => setAdding(true)} size="sm" variant="ghost">+ <IconPlus />+ Turn on research+ </Button>+ }+ description="A Bot you opt in looks through the apps it can already read, forms memories for you to review and suggests next steps. It can only read: it cannot send messages, change anything in an app, or use a browser or computer."+ title="Background research"+ >+ {settings.isPending ? null : settings.error ? (+ <p role="alert" className="mt-4 text-destructive text-sm">+ {settings.error.message}+ </p>+ ) : shown.length === 0 ? (+ <PageEmpty>Background research is off.</PageEmpty>+ ) : (+ <PageRows>+ {shown.map((setting, index) => (+ <Fragment key={setting.id}>+ {index > 0 ? <Separator /> : null}+ <SettingRow+ setting={setting}+ botName={+ bots.data?.find((bot) => bot.id === setting.agentId)?.name ??+ setting.agentId+ }+ />+ </Fragment>+ ))}+ </PageRows>+ )}+ {adding ? (+ <TurnOnResearchDialog+ fixedBot={fixedBot}+ onClose={() => setAdding(false)}+ />+ ) : null}+ </PageSection>+ );+}++/** Which Bot, where its suggestions go, how often, and what to look for. */+function TurnOnResearchDialog({+ fixedBot,+ onClose,+}: {+ fixedBot?: string;+ onClose: () => void;+}) {const bots = useQuery(agentListQueryOptions());const channels = useInfiniteQuery(channelListQueryOptions());- const [agentId, setAgentId] = useState("");+ const [pickedBot, setAgentId] = useState("");+ const agentId = fixedBot ?? pickedBot;const [channelId, setChannelId] = useState("");const [focus, setFocus] = useState("");const [intervalMinutes, setIntervalMinutes] = useState(240);@@ -136,124 +253,160 @@ export function ProactiveResearchSettings() {const eligibleChannels = (channels.data ?? []).filter((channel) => channel.active && channel.agentIds.includes(agentId),);- const add = useMutation({- mutationFn: createProactiveSetting,- onSuccess: async () => {- setFocus("");- await refresh();- },- });+ const add = useMutation(createProactiveSettingMutationOptions(queryClient));return (- <section className="grid gap-3">- <h2 className="font-semibold">Background research</h2>- <p className="text-sm text-muted-foreground">- A Bot you opt in looks through the apps it can already read, forms- memories for you to review and suggests next steps. It can only read: it- cannot send messages, change anything in an app, or use a browser or- computer.- </p>- <form- className="grid gap-3 rounded-lg border p-4"- onSubmit={(event) => {- event.preventDefault();- add.mutate({ agentId, channelId, focus, intervalMinutes });- }}- >- <div className="grid gap-3 sm:grid-cols-3">- <label className={field}>- Bot- <select- required- className={select}- value={agentId}- onChange={(event) => {- setAgentId(event.target.value);- setChannelId("");- }}- >- <option value="">Choose a Bot</option>- {bots.data?.map((bot) => (- <option key={bot.id} value={bot.id}>- {bot.name}- </option>- ))}- </select>- </label>- <label className={field}>- Deliver suggestions to- <select- required- className={select}- value={channelId}- onChange={(event) => setChannelId(event.target.value)}- >- <option value="">Choose a channel</option>- {eligibleChannels.map((channel) => (- <option key={channel.id} value={channel.id}>- {conversationLabel(channel)}- </option>- ))}- </select>- </label>- <label className={field}>- How often- <select- className={select}- value={intervalMinutes}- onChange={(event) =>- setIntervalMinutes(Number(event.target.value))- }- >- {intervals.map((interval) => (- <option key={interval.minutes} value={interval.minutes}>- {interval.label}- </option>- ))}- </select>- </label>- </div>- <label className={field} htmlFor={`${id}-focus`}>- What to look for (optional)- <Input- id={`${id}-focus`}- maxLength={1000}- value={focus}- onChange={(event) => setFocus(event.target.value)}- placeholder="Open issues assigned to me and questions waiting on me"- />- </label>- <Button- type="submit"- className="justify-self-start"- disabled={add.isPending || !agentId || !channelId}- >- Turn on background research- </Button>- {add.error && (- <p role="alert" className="text-destructive">- {add.error.message}- </p>- )}- </form>- {settings.error && (- <p role="alert" className="text-destructive">- {settings.error.message}- </p>- )}- {settings.data?.map((setting) => (- <SettingRow- key={setting.id}- setting={setting}- botName={- bots.data?.find((bot) => bot.id === setting.agentId)?.name ??- setting.agentId- }- />- ))}- </section>+ <Dialog onOpenChange={(next) => !next && onClose()} open>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Turn on background research</DialogTitle>+ <DialogDescription>+ It reads on a schedule and delivers what it suggests to a channel it+ is in.+ </DialogDescription>+ </DialogHeader>+ <DialogBody className="mt-4 overflow-y-auto">+ {/* The submit button is in the footer and reaches this form by id, so DialogBody stays a+ direct child of DialogContent and keeps scrolling. */}+ <form+ id={id}+ onSubmit={(event) => {+ event.preventDefault();+ add.mutate(+ { agentId, channelId, focus, intervalMinutes },+ { onSuccess: onClose },+ );+ }}+ >+ <FieldGroup>+ {fixedBot === undefined ? (+ <Field>+ <FieldLabel htmlFor={`${id}-bot`}>Bot</FieldLabel>+ <Select+ items={bots.data?.map((bot) => ({+ value: bot.id,+ label: bot.name,+ }))}+ onValueChange={(value) => {+ setAgentId(value ?? "");+ setChannelId("");+ }}+ required+ value={agentId || null}+ >+ <SelectTrigger className="w-full" id={`${id}-bot`}>+ <SelectValue placeholder="Choose a Bot" />+ </SelectTrigger>+ <SelectContent>+ {bots.data?.map((bot) => (+ <SelectItem key={bot.id} value={bot.id}>+ {bot.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>+ ) : null}+ <Field>+ <FieldLabel htmlFor={`${id}-channel`}>+ Deliver suggestions to+ </FieldLabel>+ <Select+ items={eligibleChannels.map((channel) => ({+ value: channel.id,+ label: conversationLabel(channel),+ }))}+ onValueChange={(value) => setChannelId(value ?? "")}+ required+ value={channelId || null}+ >+ <SelectTrigger className="w-full" id={`${id}-channel`}>+ <SelectValue placeholder="Choose a channel" />+ </SelectTrigger>+ <SelectContent>+ {eligibleChannels.map((channel) => (+ <SelectItem key={channel.id} value={channel.id}>+ {conversationLabel(channel)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>+ <Field>+ <FieldLabel htmlFor={`${id}-interval`}>How often</FieldLabel>+ <Select+ items={intervalItems}+ onValueChange={(value) => {+ if (value !== null) setIntervalMinutes(value);+ }}+ value={intervalMinutes}+ >+ <SelectTrigger className="w-full" id={`${id}-interval`}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {intervals.map((interval) => (+ <SelectItem+ key={interval.minutes}+ value={interval.minutes}+ >+ {interval.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>+ <Field>+ <FieldLabel htmlFor={`${id}-focus`}>+ What to look for (optional)+ </FieldLabel>+ <Input+ id={`${id}-focus`}+ maxLength={1000}+ value={focus}+ onChange={(event) => setFocus(event.target.value)}+ placeholder="Open issues assigned to me and questions waiting on me"+ />+ </Field>+ </FieldGroup>+ </form>+ {add.error && (+ <p role="alert" className="text-destructive text-sm">+ {add.error.message}+ </p>+ )}+ </DialogBody>+ <DialogFooter className="mt-4">+ <Button onClick={onClose} size="sm" variant="outline">+ Cancel+ </Button>+ <Button+ disabled={add.isPending || !agentId || !channelId}+ form={id}+ size="sm"+ type="submit"+ >+ Turn on background research+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>);}+/** Whether it is on, and when it runs next. Stated rather than captured, so it follows the query. */+function researchStatus(setting: ProactiveSetting) {+ return !setting.enabled+ ? "Off"+ : setting.lastStatus === "running"+ ? "Researching now"+ : `Next ${new Date(setting.nextRunAt).toLocaleString()}`;+}++/**+ * One Bot's research: a summary of its current answer and a chevron, opening a dialog that changes+ * it. The dialog is the row's sibling, not its child, so a click inside it does not bubble back to+ * the row and reopen it.+ */function SettingRow({setting,botName,@@ -261,98 +414,148 @@ function SettingRow({setting: ProactiveSetting;botName: string;}) {- const change = useMutation({- mutationFn: (- action:- | { kind: "toggle" }- | { kind: "run" }- | { kind: "remove" }- | { kind: "interval"; minutes: number },- ) =>- action.kind === "run"- ? runProactiveNow(setting.id)- : action.kind === "remove"- ? removeProactiveSetting(setting.id)- : updateProactiveSetting(- setting.id,- action.kind === "toggle"- ? { enabled: !setting.enabled }- : { intervalMinutes: action.minutes },- ),- onSuccess: refresh,- });+ const [open, setOpen] = useState(false);+ const id = useId();+ const change = useMutation(+ changeProactiveSettingMutationOptions(queryClient),+ );+ const summary = [+ setting.focus,+ intervalLabel(setting.intervalMinutes),+ researchStatus(setting),+ ]+ .filter(Boolean)+ .join(" · ");return (- <article className="grid gap-2 rounded-lg border p-4">- <div className="flex flex-wrap justify-between gap-2">- <strong>{botName}</strong>- <span className="text-sm text-muted-foreground">- {!setting.enabled- ? "Off"- : setting.lastStatus === "running"- ? "Researching now"- : `Next ${new Date(setting.nextRunAt).toLocaleString()}`}- </span>- </div>- {setting.focus && <p className="text-sm">{setting.focus}</p>}- {setting.lastRunAt && (- <p className="text-xs text-muted-foreground">- Last ran {new Date(setting.lastRunAt).toLocaleString()}- {setting.lastStatus === "succeeded" ? "" : ` (${setting.lastStatus})`}- </p>- )}- {setting.lastError && (- <p role="alert" className="text-destructive">- {setting.lastError}- </p>- )}- <div className="flex flex-wrap items-center gap-2">- <select- aria-label="How often"- className={select}- value={setting.intervalMinutes}- onChange={(event) =>- change.mutate({- kind: "interval",- minutes: Number(event.target.value),- })- }- >- {intervals.map((interval) => (- <option key={interval.minutes} value={interval.minutes}>- {interval.label}- </option>- ))}- </select>- <Button- size="sm"- variant="outline"- disabled={!setting.enabled || change.isPending}- onClick={() => change.mutate({ kind: "run" })}- >- Run now- </Button>- <Button- size="sm"- variant="outline"- disabled={change.isPending}- onClick={() => change.mutate({ kind: "toggle" })}- >- {setting.enabled ? "Turn off" : "Turn on"}- </Button>- <Button- size="sm"- variant="outline"- disabled={change.isPending}- onClick={() => change.mutate({ kind: "remove" })}- >- Remove- </Button>- </div>- {change.error && (- <p role="alert" className="text-destructive">- {change.error.message}- </p>- )}- </article>+ <>+ <Item+ render={+ <button+ onClick={() => {+ // Opening starts clean: the last change's failure is not this visit's.+ change.reset();+ setOpen(true);+ }}+ type="button"+ />+ }+ size="sm"+ >+ <ItemMedia variant="icon">+ <IconRadar />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>{botName}</ItemTitle>+ <ItemDescription>{summary}</ItemDescription>+ {setting.lastError ? (+ <ItemDescription className="text-destructive">+ {setting.lastError}+ </ItemDescription>+ ) : null}+ </ItemContent>+ <ItemActions>+ <IconChevronRight className="size-4 text-muted-foreground" />+ </ItemActions>+ </Item>+ <Dialog onOpenChange={setOpen} open={open}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Background research</DialogTitle>+ <DialogDescription>+ {setting.focus ? `${botName} · ${setting.focus}` : botName}+ </DialogDescription>+ </DialogHeader>+ <DialogBody className="mt-4">+ <Item size="sm" variant="muted">+ <ItemMedia variant="icon">+ <IconClock />+ </ItemMedia>+ <ItemContent>+ <ItemTitle>{researchStatus(setting)}</ItemTitle>+ {setting.lastRunAt && (+ <ItemDescription>+ Last ran {new Date(setting.lastRunAt).toLocaleString()}+ {setting.lastStatus === "succeeded"+ ? ""+ : ` (${setting.lastStatus})`}+ </ItemDescription>+ )}+ </ItemContent>+ </Item>+ {setting.lastError && (+ <p role="alert" className="text-destructive text-sm">+ {setting.lastError}+ </p>+ )}+ <Field>+ <FieldLabel htmlFor={`${id}-interval`}>How often</FieldLabel>+ {/* Writes on pick: one value, no draft worth holding. */}+ <Select+ disabled={change.isPending}+ items={intervalItems}+ onValueChange={(minutes) => {+ if (minutes !== null && minutes !== setting.intervalMinutes)+ change.mutate({+ setting,+ change: { kind: "interval", minutes },+ });+ }}+ value={setting.intervalMinutes}+ >+ <SelectTrigger className="w-full" id={`${id}-interval`}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {intervals.map((interval) => (+ <SelectItem key={interval.minutes} value={interval.minutes}>+ {interval.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>+ {change.error && (+ <p role="alert" className="text-destructive text-sm">+ {change.error.message}+ </p>+ )}+ </DialogBody>+ <DialogFooter className="mt-4">+ <Button+ size="sm"+ variant="outline"+ disabled={change.isPending}+ onClick={() =>+ change.mutate(+ { setting, change: { kind: "remove" } },+ { onSuccess: () => setOpen(false) },+ )+ }+ >+ Remove+ </Button>+ <Button+ size="sm"+ variant="outline"+ disabled={change.isPending}+ onClick={() =>+ change.mutate({ setting, change: { kind: "toggle" } })+ }+ >+ {setting.enabled ? "Turn off" : "Turn on"}+ </Button>+ <Button+ size="sm"+ disabled={!setting.enabled || change.isPending}+ onClick={() =>+ change.mutate({ setting, change: { kind: "run" } })+ }+ >+ Run now+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </>);}diff --git a/app/src/components/ui/combobox.tsx b/app/src/components/ui/combobox.tsxindex 93cc871e..1d7fa032 100644--- a/app/src/components/ui/combobox.tsx+++ b/app/src/components/ui/combobox.tsx@@ -239,9 +239,12 @@ function ComboboxChip({className,children,showRemove = true,+ removeLabel,...props}: ComboboxPrimitive.Chip.Props & {showRemove?: boolean;+ /** What the remove button is called to a screen reader, e.g. "Remove Knowledge". */+ removeLabel?: string;}) {return (<ComboboxPrimitive.Chip@@ -255,8 +258,9 @@ function ComboboxChip({{children}{showRemove && (<ComboboxPrimitive.ChipRemove+ aria-label={removeLabel}render={<Button variant="ghost" size="icon-xs" />}- className="-ml-1 opacity-50 hover:opacity-100"+ className="mr-0.5 -ml-0.5 size-4 rounded-sm opacity-50 hover:opacity-100"data-slot="combobox-chip-remove"><IconX className="pointer-events-none" />diff --git a/app/src/components/ui/item.tsx b/app/src/components/ui/item.tsxindex 01e9d13b..a8e2852a 100644--- a/app/src/components/ui/item.tsx+++ b/app/src/components/ui/item.tsx@@ -35,7 +35,7 @@ function ItemSeparator({}const itemVariants = cva(- "group/item flex w-full flex-wrap items-center rounded-lg border dark:border-transparent text-sm transition-colors duration-100 outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 [a]:transition-colors [a]:hover:bg-muted",+ "group/item flex w-full flex-wrap items-center rounded-lg border dark:border-transparent text-sm transition-colors duration-100 outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 [a]:transition-colors [a]:hover:bg-muted",{variants: {variant: {diff --git a/app/src/lib/agents/bot-summaries.ts b/app/src/lib/agents/bot-summaries.tsnew file mode 100644index 00000000..b414056e--- /dev/null+++ b/app/src/lib/agents/bot-summaries.ts@@ -0,0 +1,77 @@+/**+ * The current answer each "Settings for this Bot" row states, computed from its query on every+ * render so it updates itself when the page behind it changes something.+ */++export function countLabel(+ count: number,+ one: string,+ many: string,+ none: string,+): string {+ if (count === 0) return none;+ return `${count} ${count === 1 ? one : many}`;+}++export function accessSummary(skills: number, apps: number): string {+ const parts = [+ skills ? countLabel(skills, "skill", "skills", "") : "",+ apps ? countLabel(apps, "app", "apps", "") : "",+ ].filter(Boolean);+ return parts.length ? parts.join(", ") : "Nothing granted";+}++/**+ * Who else can use it. Publishing and visibility are separate records: a public Bot nobody published+ * is still open to everyone in the deployment.+ */+export function sharingSummary(+ published: { audience: "team" | "people" } | undefined,+ visibility: "public" | "private",+): string {+ if (!published) {+ return visibility === "public" ? "Everyone (public)" : "Not shared";+ }+ return published.audience === "team"+ ? "Whole team"+ : "Specific people and groups";+}++export function setupSummary(agent: {+ builtIn: boolean;+ endpoint: string | null;+}): string {+ if (agent.builtIn || !agent.endpoint) return "Built in";+ try {+ return new URL(agent.endpoint).host;+ } catch {+ return agent.endpoint;+ }+}++const TRANSPORT_LABEL: Record<string, string> = {+ slack: "Slack",+ teams: "Microsoft Teams",+ sms: "SMS",+};++/** Where this Bot's conversations continue outside OpenBot, each place once. */+export function reachSummary(transports: readonly string[]): string {+ const places = [...new Set(transports)]+ .map((transport) => TRANSPORT_LABEL[transport] ?? transport)+ .sort((a, b) => a.localeCompare(b));+ return places.length ? places.join(", ") : "Only in OpenBot";+}++/** The apps feeding this Bot facts, and whether it researches in the background. */+export function memorySummary(sources: number, research: boolean): string {+ const parts = [+ sources ? countLabel(sources, "source", "sources", "") : "",+ research+ ? sources+ ? "background research on"+ : "Background research on"+ : "",+ ].filter(Boolean);+ return parts.length ? parts.join(", ") : "Nothing connected";+}diff --git a/app/src/lib/agents/form.ts b/app/src/lib/agents/form.tsindex b08fa6a7..48d25faa 100644--- a/app/src/lib/agents/form.ts+++ b/app/src/lib/agents/form.ts@@ -1,4 +1,5 @@import { z } from "zod";+import type { AgentProfile } from "./queries";/*** Browser-side coworker form contract. Limits match the server parser so validation errors can be@@ -64,3 +65,27 @@ export function agentInputFrom(values: AgentFormValues) {: {}),};}++/**+ * The full update body for changing one or two fields of a Bot.+ *+ * The update endpoint takes the whole profile, so unchanged fields ride along as stored. Not a+ * built-in Bot's endpoint: that is the managed Bot's own address, which nobody typed, and the route+ * checks any endpoint it is sent as one somebody did — on a deployment whose Bot is on localhost it+ * refused every edit. Empty leaves the stored one where it is, and the empty key keeps the current+ * one.+ */+export function profileUpdateInput(+ profile: AgentProfile,+ patch: Partial<AgentFormValues>,+) {+ return agentInputFrom({+ name: profile.name,+ title: profile.title,+ roleDescription: profile.roleDescription,+ visibility: profile.visibility,+ endpoint: profile.builtIn ? "" : (profile.endpoint ?? ""),+ authValue: "",+ ...patch,+ });+}diff --git a/app/src/lib/agents/legacy-routes.ts b/app/src/lib/agents/legacy-routes.tsnew file mode 100644index 00000000..c2352836--- /dev/null+++ b/app/src/lib/agents/legacy-routes.ts@@ -0,0 +1,32 @@+/**+ * Where an old `/agents` link goes now that the roster and each Bot's page replaced it.+ *+ * Old links are not only bookmarks: the model was told a new Bot's profile is at+ * `/agents?agent=<id>`, and that sentence is in conversations people still scroll back through.+ */+export function legacyAgentsTarget(search: { new?: boolean; agent?: string }) {+ if (search.new === true) {+ return { to: "/bots", search: { new: true }, replace: true } as const;+ }+ if (search.agent) {+ return {+ to: "/bots/$agentId",+ params: { agentId: search.agent },+ replace: true,+ } as const;+ }+ return { to: "/bots", replace: true } as const;+}++/**+ * The pages that left the sidebar, and where their contents went. What was about one Bot is on that+ * Bot's page; what was the person's own is in Settings.+ */+export const LEGACY_PAGES = {+ "/approvals": "/settings/approvals",+ "/memory": "/settings/memory",+ "/reachability": "/settings/notifications",+ "/responsibilities": "/bots",+ // A group is started from the new-conversation screen by putting two or more Bots in To:.+ "/group/new": "/channel/new",+} as const;diff --git a/app/src/lib/agents/proposal.ts b/app/src/lib/agents/proposal.tsindex cbc4568d..910334ba 100644--- a/app/src/lib/agents/proposal.ts+++ b/app/src/lib/agents/proposal.ts@@ -59,7 +59,7 @@ export const botCardAnswer = {}parts.push("It was granted no connector, no tool and no address. Tell the person that anything it needs to reach is granted on its profile, that it can be talked to now, and that its profile is at",- `/agents?agent=${input.agentId}.`,+ `/bots/${input.agentId}.`,);return parts.join(" ");},@@ -90,7 +90,8 @@ export function wasCreated(result: string): boolean {* say why.*/export function createdBotIdIn(result: string): string | null {- return /agent=([A-Za-z0-9_-]+)/.exec(result)?.[1] ?? null;+ // `/bots/<id>` now; `/agents?agent=<id>` in answers written before Bots had their own pages.+ return /(?:\/bots\/|agent=)([A-Za-z0-9_-]+)/.exec(result)?.[1] ?? null;}/**diff --git a/app/src/lib/agents/queries.ts b/app/src/lib/agents/queries.tsindex 1ad3953f..326d0064 100644--- a/app/src/lib/agents/queries.ts+++ b/app/src/lib/agents/queries.ts@@ -37,9 +37,9 @@ export type AgentProfile = {*/hasCallbackToken: boolean;hidden: boolean;- /** Whether the signed-in person pinned it to the top of their agents list. Nobody else's. */+ /** Whether the signed-in person pinned it to the top of their Bots list. Nobody else's. */pinned: boolean;- /** A Team Bot an administrator assigned to this person; the sidebar always lists it. */+ /** A Team Bot an administrator assigned to this person; their Bots list always pins it. */assignedToMe?: boolean;systemOwned: boolean;canManage: boolean;@@ -55,8 +55,8 @@ export type AgentProfile = {/*** Whether this is an agent shared with you: made public by somebody else, not your own.*- * Written once so the roster (`/`) and the browse screen (`/agents`) can't drift apart on what- * "shared with you" means — both filter their list through this, not a copy of the rule.+ * Written once so every list of "shared with you" — the home screen's carousel among them — filters+ * through this rule rather than a copy of it.*/export function isSharedWithYou(agent: AgentProfile): boolean {return !agent.mine && agent.visibility === "public";diff --git a/app/src/lib/agents/roster.ts b/app/src/lib/agents/roster.tsnew file mode 100644index 00000000..4ae39154--- /dev/null+++ b/app/src/lib/agents/roster.ts@@ -0,0 +1,34 @@+import type { AgentProfile } from "./queries";++/**+ * The sections of the Bots roster, from the visible list (`agentListQueryOptions()`).+ *+ * A Bot appears in exactly one section. A Bot with something waiting on the person — a question, an+ * approval, a stalled hand-off — comes first, under Needs you: that is where the sidebar's badge+ * leads. Then Pinned, where a Team Bot an administrator assigned to the person also sits: it used to+ * be in their sidebar where they could not hide it, and the top of the roster is where that promise+ * now lives. The rest split on `mine`, never on `canManage`, which is true for an administrator on+ * everybody's Bots.+ */+export function groupRoster(+ agents: readonly AgentProfile[],+ /** How many things this Bot has waiting on the person. */+ waiting: (agentId: string) => number = () => 0,+): {+ needsYou: AgentProfile[];+ pinned: AgentProfile[];+ yours: AgentProfile[];+ shared: AgentProfile[];+} {+ const needsYou = agents.filter((agent) => waiting(agent.id) > 0);+ const quiet = agents.filter((agent) => waiting(agent.id) === 0);+ const isPinned = (agent: AgentProfile) =>+ agent.pinned || agent.assignedToMe === true;+ const rest = quiet.filter((agent) => !isPinned(agent));+ return {+ needsYou,+ pinned: quiet.filter(isPinned),+ yours: rest.filter((agent) => agent.mine),+ shared: rest.filter((agent) => !agent.mine),+ };+}diff --git a/app/src/lib/approvals.ts b/app/src/lib/approvals.tsindex 8994c316..720777cd 100644--- a/app/src/lib/approvals.ts+++ b/app/src/lib/approvals.ts@@ -1,4 +1,8 @@-import { queryOptions } from "@tanstack/react-query";+import {+ mutationOptions,+ type QueryClient,+ queryOptions,+} from "@tanstack/react-query";import { client } from "@/lib/client";export type ApprovalDecision =| "allow_once"@@ -60,6 +64,8 @@ export type ApprovalInboxData = {questions: {id: string;botId: string;+ /** The Bot whose conversation this belongs to: for a hand-off, the Bot that handed it on. */+ conversationBotId?: string;threadId: string;question: string;why?: string;@@ -151,3 +157,83 @@ export const updateTeamApprovalRule = (body: input,fallback: "The team rule could not be changed.",});++const approvalsKey = ["approvals"] as const;+const settle = (queryClient: QueryClient) => () =>+ queryClient.invalidateQueries({ queryKey: approvalsKey });++export const approvalPreferencesMutationOptions = (queryClient: QueryClient) =>+ mutationOptions({+ mutationFn: setApprovalPreferences,+ onSettled: settle(queryClient),+ });+export const createApprovalRuleMutationOptions = (queryClient: QueryClient) =>+ mutationOptions({+ mutationFn: createApprovalRule,+ onSettled: settle(queryClient),+ });+export const updateApprovalRuleMutationOptions = (queryClient: QueryClient) =>+ mutationOptions({+ mutationFn: ({ id, behaviour }: { id: string; behaviour: RuleBehaviour }) =>+ updateApprovalRule(id, { behaviour }),+ onSettled: settle(queryClient),+ });+export const revokeApprovalRuleMutationOptions = (queryClient: QueryClient) =>+ mutationOptions({+ mutationFn: revokeApprovalRule,+ onSettled: settle(queryClient),+ });+export const teamApprovalSettingsMutationOptions = (queryClient: QueryClient) =>+ mutationOptions({+ mutationFn: setTeamApprovalSettings,+ onSettled: settle(queryClient),+ });+export const createTeamApprovalRuleMutationOptions = (+ queryClient: QueryClient,+) =>+ mutationOptions({+ mutationFn: createTeamApprovalRule,+ onSettled: settle(queryClient),+ });+export const updateTeamApprovalRuleMutationOptions = (+ queryClient: QueryClient,+) =>+ mutationOptions({+ mutationFn: ({ id, behaviour }: { id: string; behaviour: RuleBehaviour }) =>+ updateTeamApprovalRule(id, { behaviour }),+ onSettled: settle(queryClient),+ });+export const revokeTeamApprovalRuleMutationOptions = (+ queryClient: QueryClient,+) =>+ mutationOptions({+ mutationFn: revokeTeamApprovalRule,+ onSettled: settle(queryClient),+ });+/** Allow once, always allow, deny, or "I did it myself" on one waiting action. */+export const decideApprovalMutationOptions = (queryClient: QueryClient) =>+ mutationOptions({+ mutationFn: ({ id, choice }: { id: string; choice: ApprovalDecision }) =>+ decideApproval(id, choice),+ onSuccess: settle(queryClient),+ });+/** Answer a question a Bot asked mid-run; the run resumes with the answer. */+export const answerPersonQuestionMutationOptions = (queryClient: QueryClient) =>+ mutationOptions({+ mutationFn: ({ id, response }: { id: string; response: string }) =>+ answerPersonQuestion(id, response),+ onSuccess: settle(queryClient),+ });++/**+ * Whether a rule's Bot field covers this Bot, matched the way the server matches it (`policy.ts`):+ * `*` is anything, and a `*` inside a value is any run of characters.+ */+export function ruleCoversBot(pattern: string, agentId: string): boolean {+ if (pattern === "*") return true;+ const source = pattern+ .split("*")+ .map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&"))+ .join(".*");+ return new RegExp(`^${source}$`, "s").test(agentId);+}diff --git a/app/src/lib/channels/mark-read.ts b/app/src/lib/channels/mark-read.tsnew file mode 100644index 00000000..2cf86591--- /dev/null+++ b/app/src/lib/channels/mark-read.ts@@ -0,0 +1,30 @@+import {+ useInfiniteQuery,+ useMutation,+ useQueryClient,+} from "@tanstack/react-query";+import { useEffect } from "react";+import { hasUnseenActivity } from "@/components/app-sidebar/app-sidebar";+import { markChannelReadMutationOptions } from "./mutations";+import { channelListQueryOptions } from "./queries";++/**+ * Opening a conversation marks it read; a Bot replying while it is open marks it read again. Used by+ * every screen that shows one conversation, one Bot or several.+ *+ * Read off the roster the sidebar renders, since the socket keeps its lastMessageAt live: it is the+ * one honest source for "has something new been said". Keyed on primitives, deliberately: the+ * optimistic patch changes the row OBJECT without changing these values, so an object dependency+ * would re-fire on its own write — and with lastMessageAt ahead of this browser's clock, loop.+ */+export function useMarkOpenChannelRead(channelId: string) {+ const queryClient = useQueryClient();+ const markRead = useMutation(markChannelReadMutationOptions(queryClient));+ const roster = useInfiniteQuery(channelListQueryOptions());+ const summary = roster.data?.find((row) => row.id === channelId);+ const unseen = summary !== undefined && hasUnseenActivity(summary);+ const markReadMutate = markRead.mutate;+ useEffect(() => {+ if (unseen) markReadMutate(channelId);+ }, [channelId, unseen, markReadMutate]);+}diff --git a/app/src/lib/channels/mutations.ts b/app/src/lib/channels/mutations.tsindex d9cae872..7665c9b8 100644--- a/app/src/lib/channels/mutations.ts+++ b/app/src/lib/channels/mutations.ts@@ -3,6 +3,7 @@ import {mutationOptions,type QueryClient,} from "@tanstack/react-query";+import { botLifecycleKeys } from "@/lib/bot-lifecycle/queries";import { client, tryClient } from "@/lib/client";import { type AgentChannel, type ChannelPage, channelKeys } from "./queries";@@ -95,9 +96,11 @@ export function setChannelPinnedMutationOptions(queryClient: QueryClient) {* Stamp a channel read for this member, patching the cache before the wire answers.** Patched in onMutate rather than refetched on success: the dot must clear the instant the channel- * opens, not a round-trip later. No rollback on failure and no invalidation — a mark-read that did- * not land is a dot that returns on the next refetch, which is the truth reasserting itself, and a- * refetch here would race the socket's own patches for nothing.+ * opens, not a round-trip later. No rollback on failure and no roster invalidation — a mark-read+ * that did not land is a dot that returns on the next refetch, which is the truth reasserting+ * itself, and a roster refetch here would race the socket's own patches for nothing. The Bots+ * badge counts unread on the server, so once the mark lands its count is asked for again rather+ * than left lit until its next poll.*/export function markChannelReadMutationOptions(queryClient: QueryClient) {return mutationOptions({@@ -107,6 +110,8 @@ export function markChannelReadMutationOptions(queryClient: QueryClient) {fallback: "Could not mark this channel read",});},+ onSuccess: () =>+ queryClient.invalidateQueries({ queryKey: botLifecycleKeys.attention }),onMutate: (channelId) => {const now = new Date().toISOString();queryClient.setQueryData(diff --git a/app/src/lib/channels/start.ts b/app/src/lib/channels/start.tsindex 4d3a6d23..caa4a618 100644--- a/app/src/lib/channels/start.ts+++ b/app/src/lib/channels/start.ts@@ -1,7 +1,19 @@-import { useMutation, useQueryClient } from "@tanstack/react-query";+import {+ MutationObserver,+ useMutation,+ useQueryClient,+} from "@tanstack/react-query";import { useNavigate } from "@tanstack/react-router";import { stashFirstMessage } from "@/components/channels/transcript-messages";-import { createChannelMutationOptions } from "./mutations";+import {+ createGroupMutationOptions,+ sendGroupMessageMutationOptions,+} from "@/lib/groups";+import { newId } from "@/lib/new-id";+import {+ createChannelMutationOptions,+ deleteChannelMutationOptions,+} from "./mutations";import { channelKeys } from "./queries";import { routeMessage } from "./route";@@ -29,6 +41,34 @@ export async function startWithChosen(input: {await input.start(input.agentId, input.text);}+/**+ * Start a group from a just-submitted first message: create it with the Bots in the order they were+ * picked, give it the message, then open it. Pure so the order can be tested; nothing is sent or+ * opened when the group could not be made.+ *+ * A group exists to hold that first message, so one whose message did not send is discarded rather+ * than left in everybody's roster as an empty conversation. The send's own error is what the caller+ * sees (the composer keeps the draft for another try); a failed discard is swallowed, because the+ * person's problem is the message, and an empty group is the lesser leftover.+ */+export async function startGroupWith(input: {+ agentIds: string[];+ text: string;+ create: (agentIds: string[]) => Promise<{ id: string }>;+ send: (channelId: string, text: string) => Promise<void>;+ discard: (channelId: string) => Promise<void>;+ open: (channelId: string) => Promise<void>;+}): Promise<void> {+ const group = await input.create(input.agentIds);+ try {+ await input.send(group.id, input.text);+ } catch (error) {+ await input.discard(group.id).catch(() => undefined);+ throw error;+ }+ await input.open(group.id);+}+/*** Start a channel from a just-submitted first message, then navigate there.*@@ -39,6 +79,8 @@ export function useStartChannel() {const queryClient = useQueryClient();const navigate = useNavigate();const createChannel = useMutation(createChannelMutationOptions(queryClient));+ const createGroup = useMutation(createGroupMutationOptions(queryClient));+ const deleteChannel = useMutation(deleteChannelMutationOptions(queryClient));const start = async (agentId: string, text: string) => {const channel = await createChannel.mutateAsync([agentId]);@@ -51,8 +93,37 @@ export function useStartChannel() {});};+ const startGroup = (agentIds: string[], text: string) =>+ startGroupWith({+ agentIds,+ text,+ create: async (ids) => {+ const channel = await createGroup.mutateAsync(ids);+ queryClient.setQueryData(channelKeys.detail(channel.id), channel);+ return channel;+ },+ // The group's id only exists once it is made, so the send's factory is bound here, per+ // group, and run through an observer rather than a hook created ahead of time.+ send: (channelId, message) =>+ new MutationObserver(+ queryClient,+ sendGroupMessageMutationOptions(queryClient, channelId),+ ).mutate({ id: newId(), text: message, agentId: null }),+ discard: async (channelId) => {+ await deleteChannel.mutateAsync(channelId);+ },+ open: (channelId) =>+ navigate({+ params: { channelId },+ replace: true,+ to: "/group/$channelId",+ }),+ });+return {- pending: createChannel.isPending,+ pending: createChannel.isPending || createGroup.isPending,+ /** Two or more Bots: a group, answering in the order given. */+ startGroup,start,/** `start`, for a coworker the person chose: the choice is recorded first. */startChosen: (agentId: string, text: string) =>diff --git a/app/src/lib/delivery.ts b/app/src/lib/delivery.tsindex ebc8fa8c..7707de8c 100644--- a/app/src/lib/delivery.ts+++ b/app/src/lib/delivery.ts@@ -1,4 +1,8 @@-import { queryOptions } from "@tanstack/react-query";+import {+ mutationOptions,+ type QueryClient,+ queryOptions,+} from "@tanstack/react-query";import { client } from "./client";export type Reachability = {bindings: {@@ -85,3 +89,46 @@ export function removePushDevice(id: string) {fallback: "Could not remove this device",});}++export function removePushDeviceMutationOptions(queryClient: QueryClient) {+ return mutationOptions({+ mutationFn: removePushDevice,+ onSettled: () => queryClient.invalidateQueries({ queryKey: deliveryKey }),+ });+}++export function removeDeliveryBindingMutationOptions(queryClient: QueryClient) {+ return mutationOptions({+ mutationFn: removeDeliveryBinding,+ onSuccess: () => queryClient.invalidateQueries({ queryKey: deliveryKey }),+ });+}++/**+ * Ask for a one-time `link <code>` message. No `queryClient`: nothing is linked until the code is+ * sent from Slack or Teams, so nothing cached has changed yet and there is nothing to invalidate.+ */+export function startChatLinkMutationOptions() {+ return mutationOptions({ mutationFn: startChatLink });+}++/**+ * Text a verification code to a phone. No `queryClient`, for the same reason as a link message: the+ * phone is not connected until the code comes back through `confirmSms`.+ */+export function startSmsMutationOptions() {+ return mutationOptions({ mutationFn: startSms });+}++export function confirmSmsMutationOptions(queryClient: QueryClient) {+ return mutationOptions({+ mutationFn: ({+ challengeId,+ code,+ }: {+ challengeId: string;+ code: string;+ }) => confirmSms(challengeId, code),+ onSuccess: () => queryClient.invalidateQueries({ queryKey: deliveryKey }),+ });+}diff --git a/app/src/lib/groups.ts b/app/src/lib/groups.tsindex ac21b87c..e2ea516e 100644--- a/app/src/lib/groups.ts+++ b/app/src/lib/groups.ts@@ -116,7 +116,10 @@ export function createGroupMutationOptions(queryClient: QueryClient) {}/** Add a person who has signed in here to a group this person is in. */-export function addGroupMemberMutationOptions(channelId: string) {+export function addGroupMemberMutationOptions(+ queryClient: QueryClient,+ channelId: string,+) {return mutationOptions({mutationFn: async (email: string) => {await client(`/api/groups/${encodeURIComponent(channelId)}/members`, {@@ -125,6 +128,9 @@ export function addGroupMemberMutationOptions(channelId: string) {fallback: "That person could not be added.",});},+ // So the list of people shows them straight away.+ onSettled: () =>+ queryClient.invalidateQueries({ queryKey: groupKeys.detail(channelId) }),});}diff --git a/app/src/lib/memory.ts b/app/src/lib/memory.tsindex 509eeacd..18add053 100644--- a/app/src/lib/memory.ts+++ b/app/src/lib/memory.ts@@ -1,4 +1,8 @@-import { queryOptions } from "@tanstack/react-query";+import {+ mutationOptions,+ type QueryClient,+ queryOptions,+} from "@tanstack/react-query";import { client } from "@/lib/client";export type MemoryRecord = {id: string;@@ -107,3 +111,48 @@ export const memorySourceAction = (fallback: "Could not change this source",},);++const settleMemory = (queryClient: QueryClient) => () =>+ queryClient.invalidateQueries({ queryKey: memoryKeys.all });++export const createMemoryMutationOptions = (queryClient: QueryClient) =>+ mutationOptions({+ mutationFn: createMemory,+ onSettled: settleMemory(queryClient),+ });+export const updateMemoryMutationOptions = (queryClient: QueryClient) =>+ mutationOptions({+ mutationFn: ({+ id,+ input,+ }: {+ id: string;+ input: { content?: string; enabled?: boolean; reviewState?: "confirmed" };+ }) => updateMemory(id, input),+ onSettled: settleMemory(queryClient),+ });+export const deleteMemoryMutationOptions = (queryClient: QueryClient) =>+ mutationOptions({+ mutationFn: deleteMemory,+ onSettled: settleMemory(queryClient),+ });++/** Opt a Bot in to reading one of its connected apps' actions as a memory source. */+export const addMemorySourceMutationOptions = (queryClient: QueryClient) =>+ mutationOptions({+ mutationFn: addMemorySource,+ onSuccess: settleMemory(queryClient),+ });++/** Sync, remove, enable or disable one memory source. */+export const memorySourceActionMutationOptions = (queryClient: QueryClient) =>+ mutationOptions({+ mutationFn: ({+ sourceId,+ name,+ }: {+ sourceId: string;+ name: "sync" | "remove" | "enable" | "disable";+ }) => memorySourceAction(sourceId, name),+ onSuccess: settleMemory(queryClient),+ });diff --git a/app/src/lib/proactive.ts b/app/src/lib/proactive.tsindex 9ccf4287..af9805c3 100644--- a/app/src/lib/proactive.ts+++ b/app/src/lib/proactive.ts@@ -1,4 +1,8 @@-import { queryOptions } from "@tanstack/react-query";+import {+ mutationOptions,+ type QueryClient,+ queryOptions,+} from "@tanstack/react-query";import { client } from "@/lib/client";export type ProactiveSetting = {@@ -85,3 +89,57 @@ export const resolveSuggestion = (id: string, action: "start" | "dismiss") =>? "Could not start this suggestion": "Could not dismiss this suggestion",});++/** A setting's research produces suggestions, so a change to either refreshes both. */+const settleProactive = (queryClient: QueryClient) => () =>+ Promise.all([+ queryClient.invalidateQueries({ queryKey: proactiveKeys.settings }),+ queryClient.invalidateQueries({ queryKey: proactiveKeys.suggestions }),+ ]);++/** Start a suggested next step as a task, or dismiss it. */+export const resolveSuggestionMutationOptions = (queryClient: QueryClient) =>+ mutationOptions({+ mutationFn: ({ id, action }: { id: string; action: "start" | "dismiss" }) =>+ resolveSuggestion(id, action),+ onSuccess: settleProactive(queryClient),+ });++export const createProactiveSettingMutationOptions = (+ queryClient: QueryClient,+) =>+ mutationOptions({+ mutationFn: createProactiveSetting,+ onSuccess: settleProactive(queryClient),+ });++/** What can be done to one background-research setting from its row. */+export type ProactiveChange =+ | { kind: "toggle" }+ | { kind: "run" }+ | { kind: "remove" }+ | { kind: "interval"; minutes: number };++export const changeProactiveSettingMutationOptions = (+ queryClient: QueryClient,+) =>+ mutationOptions({+ mutationFn: ({+ setting,+ change,+ }: {+ setting: Pick<ProactiveSetting, "id" | "enabled">;+ change: ProactiveChange;+ }) =>+ change.kind === "run"+ ? runProactiveNow(setting.id)+ : change.kind === "remove"+ ? removeProactiveSetting(setting.id)+ : updateProactiveSetting(+ setting.id,+ change.kind === "toggle"+ ? { enabled: !setting.enabled }+ : { intervalMinutes: change.minutes },+ ),+ onSuccess: settleProactive(queryClient),+ });diff --git a/app/src/lib/responsibilities.ts b/app/src/lib/responsibilities.tsindex c40fa461..e9bb37b3 100644--- a/app/src/lib/responsibilities.ts+++ b/app/src/lib/responsibilities.ts@@ -1,5 +1,10 @@-import { queryOptions } from "@tanstack/react-query";+import {+ mutationOptions,+ type QueryClient,+ queryOptions,+} from "@tanstack/react-query";import { client } from "@/lib/client";+import { sharedUseKeys } from "@/lib/plugins/shared-use";export type ResponsibilityRecord = {id: string;@@ -240,3 +245,137 @@ export function setTriggerEnabled(triggerId: string, enabled: boolean) {},);}++const settleGithub = (queryClient: QueryClient) => () =>+ queryClient.invalidateQueries({ queryKey: responsibilityKeys.bindings });++export function createGithubBindingMutationOptions(queryClient: QueryClient) {+ return mutationOptions({+ mutationFn: ({+ repository,+ secret,+ }: {+ repository: string;+ secret: string;+ }) => createGithubBinding(repository, secret),+ onSettled: settleGithub(queryClient),+ });+}+export function removeGithubBindingMutationOptions(queryClient: QueryClient) {+ return mutationOptions({+ mutationFn: removeGithubBinding,+ onSettled: settleGithub(queryClient),+ });+}++const settleResponsibilities = (queryClient: QueryClient) => () =>+ queryClient.invalidateQueries({ queryKey: responsibilityKeys.all });++export function createResponsibilityMutationOptions(queryClient: QueryClient) {+ return mutationOptions({+ mutationFn: createResponsibility,+ onSuccess: settleResponsibilities(queryClient),+ });+}++export function updateResponsibilityMutationOptions(queryClient: QueryClient) {+ return mutationOptions({+ mutationFn: ({+ id,+ patch,+ }: {+ id: string;+ patch: { title: string; instruction: string; successCriteria: string };+ }) => updateResponsibility(id, patch),+ onSuccess: settleResponsibilities(queryClient),+ });+}++/** Pause, resume, complete or run a responsibility now. */+export function responsibilityActionMutationOptions(queryClient: QueryClient) {+ return mutationOptions({+ mutationFn: ({+ id,+ action,+ }: {+ id: string;+ action: "pause" | "resume" | "complete" | "run";+ }) => responsibilityAction(id, action),+ onSuccess: settleResponsibilities(queryClient),+ });+}++const settleTriggers = (queryClient: QueryClient, responsibilityId: string) =>+ queryClient.invalidateQueries({+ queryKey: responsibilityKeys.triggers(responsibilityId),+ });++/**+ * Add a trigger. A new trigger is a new way a shared app gets called, so the approval it needs may+ * have changed: the shared-use requests are refreshed alongside the triggers.+ */+export function createTriggerMutationOptions(queryClient: QueryClient) {+ return mutationOptions({+ mutationFn: ({+ responsibilityId,+ input,+ }: {+ responsibilityId: string;+ input: { config: TriggerConfig; secret?: string };+ }) => createTrigger(responsibilityId, input),+ onSuccess: async (_created, { responsibilityId }) => {+ await settleTriggers(queryClient, responsibilityId);+ await queryClient.invalidateQueries({+ queryKey: sharedUseKeys.requests(),+ });+ },+ });+}++/**+ * Read a trigger's write-only secret on demand. No `queryClient` and no `onSuccess`: it changes+ * nothing and caches nothing, so there is nothing to invalidate, and the secret lives only in the+ * row that asked for it.+ */+export function revealTriggerSecretMutationOptions() {+ return mutationOptions({ mutationFn: revealTriggerSecret });+}++/** Rotate a generated secret, or store the provider's newly pasted one. */+export function setTriggerSecretMutationOptions(queryClient: QueryClient) {+ return mutationOptions({+ mutationFn: ({+ trigger,+ secret,+ }: {+ trigger: Pick<TriggerRecord, "id" | "responsibilityId">;+ secret?: string;+ }) => setTriggerSecret(trigger.id, secret),+ onSuccess: (_result, { trigger }) =>+ settleTriggers(queryClient, trigger.responsibilityId),+ });+}++export function removeTriggerMutationOptions(queryClient: QueryClient) {+ return mutationOptions({+ mutationFn: (trigger: Pick<TriggerRecord, "id" | "responsibilityId">) =>+ removeTrigger(trigger.id),+ onSuccess: (_result, trigger) =>+ settleTriggers(queryClient, trigger.responsibilityId),+ });+}++/** Switch a trigger on or off; a paused trigger acknowledges deliveries but never starts a run. */+export function setTriggerEnabledMutationOptions(queryClient: QueryClient) {+ return mutationOptions({+ mutationFn: ({+ trigger,+ enabled,+ }: {+ trigger: Pick<TriggerRecord, "id" | "responsibilityId">;+ enabled: boolean;+ }) => setTriggerEnabled(trigger.id, enabled),+ onSuccess: (_result, { trigger }) =>+ settleTriggers(queryClient, trigger.responsibilityId),+ });+}diff --git a/app/src/routeTree.gen.ts b/app/src/routeTree.gen.tsindex 6b5eb9d3..ca53f4c0 100644--- a/app/src/routeTree.gen.ts+++ b/app/src/routeTree.gen.ts@@ -25,6 +25,7 @@ import { Route as AuthedAppRoutinesRouteImport } from './routes/_authed/_app/rouimport { Route as AuthedAppSkillsRouteImport } from './routes/_authed/_app/skills'import { Route as AuthedAppTeamBotsRouteImport } from './routes/_authed/_app/team-bots'import { Route as AuthedAdminIndexRouteImport } from './routes/_authed/admin/index'+import { Route as AuthedAdminApprovalsRouteImport } from './routes/_authed/admin/approvals'import { Route as AuthedAdminAuditRouteImport } from './routes/_authed/admin/audit'import { Route as AuthedAdminBoundariesRouteImport } from './routes/_authed/admin/boundaries'import { Route as AuthedAdminComputersRouteImport } from './routes/_authed/admin/computers'@@ -36,11 +37,13 @@ import { Route as AuthedAdminPeopleRouteImport } from './routes/_authed/admin/peimport { Route as AuthedAdminPlaygroundRouteImport } from './routes/_authed/admin/playground'import { Route as AuthedAdminSkillsRouteImport } from './routes/_authed/admin/skills'import { Route as AuthedSettingsIndexRouteImport } from './routes/_authed/settings/index'+import { Route as AuthedSettingsApprovalsRouteImport } from './routes/_authed/settings/approvals'+import { Route as AuthedSettingsMemoryRouteImport } from './routes/_authed/settings/memory'+import { Route as AuthedSettingsNotificationsRouteImport } from './routes/_authed/settings/notifications'import { Route as AuthedSettingsPasswordsRouteImport } from './routes/_authed/settings/passwords'import { Route as AuthedSignInRequestIdRouteImport } from './routes/_authed/sign-in/$requestId'import { Route as AuthedAppAgentsIndexRouteImport } from './routes/_authed/_app/agents/index'import { Route as AuthedAppBotsIndexRouteImport } from './routes/_authed/_app/bots.index'-import { Route as AuthedAppBotsAgentIdRouteImport } from './routes/_authed/_app/bots.$agentId'import { Route as AuthedAppChannelChannelIdRouteImport } from './routes/_authed/_app/channel/$channelId'import { Route as AuthedAppChannelNewRouteImport } from './routes/_authed/_app/channel/new'import { Route as AuthedAppGroupChannelIdRouteImport } from './routes/_authed/_app/group/$channelId'@@ -54,6 +57,15 @@ import { Route as AuthedSettingsComponentsGalleryIndexRouteImport } from './routimport { Route as AuthedSettingsComponentsGalleryNameRouteImport } from './routes/_authed/settings/components-gallery/$name'import { Route as AuthedSettingsConnectedAccountsIndexRouteImport } from './routes/_authed/settings/connected-accounts/index'import { Route as AuthedSettingsConnectedAccountsKeyRouteImport } from './routes/_authed/settings/connected-accounts/$key'+import { Route as AuthedAppBotsAgentIdIndexRouteImport } from './routes/_authed/_app/bots.$agentId.index'+import { Route as AuthedAppBotsAgentIdAccessRouteImport } from './routes/_authed/_app/bots.$agentId.access'+import { Route as AuthedAppBotsAgentIdApprovalsRouteImport } from './routes/_authed/_app/bots.$agentId.approvals'+import { Route as AuthedAppBotsAgentIdMemoryRouteImport } from './routes/_authed/_app/bots.$agentId.memory'+import { Route as AuthedAppBotsAgentIdReachRouteImport } from './routes/_authed/_app/bots.$agentId.reach'+import { Route as AuthedAppBotsAgentIdResponsibilitiesRouteImport } from './routes/_authed/_app/bots.$agentId.responsibilities'+import { Route as AuthedAppBotsAgentIdRoutinesRouteImport } from './routes/_authed/_app/bots.$agentId.routines'+import { Route as AuthedAppBotsAgentIdSetupRouteImport } from './routes/_authed/_app/bots.$agentId.setup'+import { Route as AuthedAppBotsAgentIdSharingRouteImport } from './routes/_authed/_app/bots.$agentId.sharing'import { Route as AuthedAdminPluginsKeyBotsAgentIdRouteImport } from './routes/_authed/admin/plugins/$key_.bots.$agentId'import { Route as AuthedAdminPluginsKeyToolsToolRouteImport } from './routes/_authed/admin/plugins/$key_.tools.$tool'@@ -136,6 +148,11 @@ const AuthedAdminIndexRoute = AuthedAdminIndexRouteImport.update({path: '/',getParentRoute: () => AuthedAdminRouteRoute,} as any)+const AuthedAdminApprovalsRoute = AuthedAdminApprovalsRouteImport.update({+ id: '/approvals',+ path: '/approvals',+ getParentRoute: () => AuthedAdminRouteRoute,+} as any)const AuthedAdminAuditRoute = AuthedAdminAuditRouteImport.update({id: '/audit',path: '/audit',@@ -192,6 +209,22 @@ const AuthedSettingsIndexRoute = AuthedSettingsIndexRouteImport.update({path: '/',getParentRoute: () => AuthedSettingsRouteRoute,} as any)+const AuthedSettingsApprovalsRoute = AuthedSettingsApprovalsRouteImport.update({+ id: '/approvals',+ path: '/approvals',+ getParentRoute: () => AuthedSettingsRouteRoute,+} as any)+const AuthedSettingsMemoryRoute = AuthedSettingsMemoryRouteImport.update({+ id: '/memory',+ path: '/memory',+ getParentRoute: () => AuthedSettingsRouteRoute,+} as any)+const AuthedSettingsNotificationsRoute =+ AuthedSettingsNotificationsRouteImport.update({+ id: '/notifications',+ path: '/notifications',+ getParentRoute: () => AuthedSettingsRouteRoute,+ } as any)const AuthedSettingsPasswordsRoute = AuthedSettingsPasswordsRouteImport.update({id: '/passwords',path: '/passwords',@@ -212,11 +245,6 @@ const AuthedAppBotsIndexRoute = AuthedAppBotsIndexRouteImport.update({path: '/bots/',getParentRoute: () => AuthedAppRoute,} as any)-const AuthedAppBotsAgentIdRoute = AuthedAppBotsAgentIdRouteImport.update({- id: '/bots/$agentId',- path: '/bots/$agentId',- getParentRoute: () => AuthedAppRoute,-} as any)const AuthedAppChannelChannelIdRoute =AuthedAppChannelChannelIdRouteImport.update({id: '/channel/$channelId',@@ -290,6 +318,60 @@ const AuthedSettingsConnectedAccountsKeyRoute =path: '/connected-accounts/$key',getParentRoute: () => AuthedSettingsRouteRoute,} as any)+const AuthedAppBotsAgentIdIndexRoute =+ AuthedAppBotsAgentIdIndexRouteImport.update({+ id: '/bots/$agentId/',+ path: '/bots/$agentId/',+ getParentRoute: () => AuthedAppRoute,+ } as any)+const AuthedAppBotsAgentIdAccessRoute =+ AuthedAppBotsAgentIdAccessRouteImport.update({+ id: '/bots/$agentId/access',+ path: '/bots/$agentId/access',+ getParentRoute: () => AuthedAppRoute,+ } as any)+const AuthedAppBotsAgentIdApprovalsRoute =+ AuthedAppBotsAgentIdApprovalsRouteImport.update({+ id: '/bots/$agentId/approvals',+ path: '/bots/$agentId/approvals',+ getParentRoute: () => AuthedAppRoute,+ } as any)+const AuthedAppBotsAgentIdMemoryRoute =+ AuthedAppBotsAgentIdMemoryRouteImport.update({+ id: '/bots/$agentId/memory',+ path: '/bots/$agentId/memory',+ getParentRoute: () => AuthedAppRoute,+ } as any)+const AuthedAppBotsAgentIdReachRoute =+ AuthedAppBotsAgentIdReachRouteImport.update({+ id: '/bots/$agentId/reach',+ path: '/bots/$agentId/reach',+ getParentRoute: () => AuthedAppRoute,+ } as any)+const AuthedAppBotsAgentIdResponsibilitiesRoute =+ AuthedAppBotsAgentIdResponsibilitiesRouteImport.update({+ id: '/bots/$agentId/responsibilities',+ path: '/bots/$agentId/responsibilities',+ getParentRoute: () => AuthedAppRoute,+ } as any)+const AuthedAppBotsAgentIdRoutinesRoute =+ AuthedAppBotsAgentIdRoutinesRouteImport.update({+ id: '/bots/$agentId/routines',+ path: '/bots/$agentId/routines',+ getParentRoute: () => AuthedAppRoute,+ } as any)+const AuthedAppBotsAgentIdSetupRoute =+ AuthedAppBotsAgentIdSetupRouteImport.update({+ id: '/bots/$agentId/setup',+ path: '/bots/$agentId/setup',+ getParentRoute: () => AuthedAppRoute,+ } as any)+const AuthedAppBotsAgentIdSharingRoute =+ AuthedAppBotsAgentIdSharingRouteImport.update({+ id: '/bots/$agentId/sharing',+ path: '/bots/$agentId/sharing',+ getParentRoute: () => AuthedAppRoute,+ } as any)const AuthedAdminPluginsKeyBotsAgentIdRoute =AuthedAdminPluginsKeyBotsAgentIdRouteImport.update({id: '/plugins/$key_/bots/$agentId',@@ -317,6 +399,7 @@ export interface FileRoutesByFullPath {'/routines': typeof AuthedAppRoutinesRoute'/skills': typeof AuthedAppSkillsRoute'/team-bots': typeof AuthedAppTeamBotsRoute+ '/admin/approvals': typeof AuthedAdminApprovalsRoute'/admin/audit': typeof AuthedAdminAuditRoute'/admin/boundaries': typeof AuthedAdminBoundariesRoute'/admin/computers': typeof AuthedAdminComputersRoute@@ -327,11 +410,13 @@ export interface FileRoutesByFullPath {'/admin/people': typeof AuthedAdminPeopleRoute'/admin/playground': typeof AuthedAdminPlaygroundRoute'/admin/skills': typeof AuthedAdminSkillsRoute+ '/settings/approvals': typeof AuthedSettingsApprovalsRoute+ '/settings/memory': typeof AuthedSettingsMemoryRoute+ '/settings/notifications': typeof AuthedSettingsNotificationsRoute'/settings/passwords': typeof AuthedSettingsPasswordsRoute'/sign-in/$requestId': typeof AuthedSignInRequestIdRoute'/admin/': typeof AuthedAdminIndexRoute'/settings/': typeof AuthedSettingsIndexRoute- '/bots/$agentId': typeof AuthedAppBotsAgentIdRoute'/channel/$channelId': typeof AuthedAppChannelChannelIdRoute'/channel/new': typeof AuthedAppChannelNewRoute'/group/$channelId': typeof AuthedAppGroupChannelIdRoute@@ -347,6 +432,15 @@ export interface FileRoutesByFullPath {'/admin/plugins/': typeof AuthedAdminPluginsIndexRoute'/settings/components-gallery/': typeof AuthedSettingsComponentsGalleryIndexRoute'/settings/connected-accounts/': typeof AuthedSettingsConnectedAccountsIndexRoute+ '/bots/$agentId/access': typeof AuthedAppBotsAgentIdAccessRoute+ '/bots/$agentId/approvals': typeof AuthedAppBotsAgentIdApprovalsRoute+ '/bots/$agentId/memory': typeof AuthedAppBotsAgentIdMemoryRoute+ '/bots/$agentId/reach': typeof AuthedAppBotsAgentIdReachRoute+ '/bots/$agentId/responsibilities': typeof AuthedAppBotsAgentIdResponsibilitiesRoute+ '/bots/$agentId/routines': typeof AuthedAppBotsAgentIdRoutinesRoute+ '/bots/$agentId/setup': typeof AuthedAppBotsAgentIdSetupRoute+ '/bots/$agentId/sharing': typeof AuthedAppBotsAgentIdSharingRoute+ '/bots/$agentId/': typeof AuthedAppBotsAgentIdIndexRoute'/admin/plugins/$key/bots/$agentId': typeof AuthedAdminPluginsKeyBotsAgentIdRoute'/admin/plugins/$key/tools/$tool': typeof AuthedAdminPluginsKeyToolsToolRoute}@@ -362,6 +456,7 @@ export interface FileRoutesByTo {'/routines': typeof AuthedAppRoutinesRoute'/skills': typeof AuthedAppSkillsRoute'/team-bots': typeof AuthedAppTeamBotsRoute+ '/admin/approvals': typeof AuthedAdminApprovalsRoute'/admin/audit': typeof AuthedAdminAuditRoute'/admin/boundaries': typeof AuthedAdminBoundariesRoute'/admin/computers': typeof AuthedAdminComputersRoute@@ -372,11 +467,13 @@ export interface FileRoutesByTo {'/admin/people': typeof AuthedAdminPeopleRoute'/admin/playground': typeof AuthedAdminPlaygroundRoute'/admin/skills': typeof AuthedAdminSkillsRoute+ '/settings/approvals': typeof AuthedSettingsApprovalsRoute+ '/settings/memory': typeof AuthedSettingsMemoryRoute+ '/settings/notifications': typeof AuthedSettingsNotificationsRoute'/settings/passwords': typeof AuthedSettingsPasswordsRoute'/sign-in/$requestId': typeof AuthedSignInRequestIdRoute'/admin': typeof AuthedAdminIndexRoute'/settings': typeof AuthedSettingsIndexRoute- '/bots/$agentId': typeof AuthedAppBotsAgentIdRoute'/channel/$channelId': typeof AuthedAppChannelChannelIdRoute'/channel/new': typeof AuthedAppChannelNewRoute'/group/$channelId': typeof AuthedAppGroupChannelIdRoute@@ -392,6 +489,15 @@ export interface FileRoutesByTo {'/admin/plugins': typeof AuthedAdminPluginsIndexRoute'/settings/components-gallery': typeof AuthedSettingsComponentsGalleryIndexRoute'/settings/connected-accounts': typeof AuthedSettingsConnectedAccountsIndexRoute+ '/bots/$agentId/access': typeof AuthedAppBotsAgentIdAccessRoute+ '/bots/$agentId/approvals': typeof AuthedAppBotsAgentIdApprovalsRoute+ '/bots/$agentId/memory': typeof AuthedAppBotsAgentIdMemoryRoute+ '/bots/$agentId/reach': typeof AuthedAppBotsAgentIdReachRoute+ '/bots/$agentId/responsibilities': typeof AuthedAppBotsAgentIdResponsibilitiesRoute+ '/bots/$agentId/routines': typeof AuthedAppBotsAgentIdRoutinesRoute+ '/bots/$agentId/setup': typeof AuthedAppBotsAgentIdSetupRoute+ '/bots/$agentId/sharing': typeof AuthedAppBotsAgentIdSharingRoute+ '/bots/$agentId': typeof AuthedAppBotsAgentIdIndexRoute'/admin/plugins/$key/bots/$agentId': typeof AuthedAdminPluginsKeyBotsAgentIdRoute'/admin/plugins/$key/tools/$tool': typeof AuthedAdminPluginsKeyToolsToolRoute}@@ -411,6 +517,7 @@ export interface FileRoutesById {'/_authed/_app/routines': typeof AuthedAppRoutinesRoute'/_authed/_app/skills': typeof AuthedAppSkillsRoute'/_authed/_app/team-bots': typeof AuthedAppTeamBotsRoute+ '/_authed/admin/approvals': typeof AuthedAdminApprovalsRoute'/_authed/admin/audit': typeof AuthedAdminAuditRoute'/_authed/admin/boundaries': typeof AuthedAdminBoundariesRoute'/_authed/admin/computers': typeof AuthedAdminComputersRoute@@ -421,12 +528,14 @@ export interface FileRoutesById {'/_authed/admin/people': typeof AuthedAdminPeopleRoute'/_authed/admin/playground': typeof AuthedAdminPlaygroundRoute'/_authed/admin/skills': typeof AuthedAdminSkillsRoute+ '/_authed/settings/approvals': typeof AuthedSettingsApprovalsRoute+ '/_authed/settings/memory': typeof AuthedSettingsMemoryRoute+ '/_authed/settings/notifications': typeof AuthedSettingsNotificationsRoute'/_authed/settings/passwords': typeof AuthedSettingsPasswordsRoute'/_authed/sign-in/$requestId': typeof AuthedSignInRequestIdRoute'/_authed/_app/': typeof AuthedAppIndexRoute'/_authed/admin/': typeof AuthedAdminIndexRoute'/_authed/settings/': typeof AuthedSettingsIndexRoute- '/_authed/_app/bots/$agentId': typeof AuthedAppBotsAgentIdRoute'/_authed/_app/channel/$channelId': typeof AuthedAppChannelChannelIdRoute'/_authed/_app/channel/new': typeof AuthedAppChannelNewRoute'/_authed/_app/group/$channelId': typeof AuthedAppGroupChannelIdRoute@@ -442,6 +551,15 @@ export interface FileRoutesById {'/_authed/admin/plugins/': typeof AuthedAdminPluginsIndexRoute'/_authed/settings/components-gallery/': typeof AuthedSettingsComponentsGalleryIndexRoute'/_authed/settings/connected-accounts/': typeof AuthedSettingsConnectedAccountsIndexRoute+ '/_authed/_app/bots/$agentId/access': typeof AuthedAppBotsAgentIdAccessRoute+ '/_authed/_app/bots/$agentId/approvals': typeof AuthedAppBotsAgentIdApprovalsRoute+ '/_authed/_app/bots/$agentId/memory': typeof AuthedAppBotsAgentIdMemoryRoute+ '/_authed/_app/bots/$agentId/reach': typeof AuthedAppBotsAgentIdReachRoute+ '/_authed/_app/bots/$agentId/responsibilities': typeof AuthedAppBotsAgentIdResponsibilitiesRoute+ '/_authed/_app/bots/$agentId/routines': typeof AuthedAppBotsAgentIdRoutinesRoute+ '/_authed/_app/bots/$agentId/setup': typeof AuthedAppBotsAgentIdSetupRoute+ '/_authed/_app/bots/$agentId/sharing': typeof AuthedAppBotsAgentIdSharingRoute+ '/_authed/_app/bots/$agentId/': typeof AuthedAppBotsAgentIdIndexRoute'/_authed/admin/plugins/$key_/bots/$agentId': typeof AuthedAdminPluginsKeyBotsAgentIdRoute'/_authed/admin/plugins/$key_/tools/$tool': typeof AuthedAdminPluginsKeyToolsToolRoute}@@ -461,6 +579,7 @@ export interface FileRouteTypes {| '/routines'| '/skills'| '/team-bots'+ | '/admin/approvals'| '/admin/audit'| '/admin/boundaries'| '/admin/computers'@@ -471,11 +590,13 @@ export interface FileRouteTypes {| '/admin/people'| '/admin/playground'| '/admin/skills'+ | '/settings/approvals'+ | '/settings/memory'+ | '/settings/notifications'| '/settings/passwords'| '/sign-in/$requestId'| '/admin/'| '/settings/'- | '/bots/$agentId'| '/channel/$channelId'| '/channel/new'| '/group/$channelId'@@ -491,6 +612,15 @@ export interface FileRouteTypes {| '/admin/plugins/'| '/settings/components-gallery/'| '/settings/connected-accounts/'+ | '/bots/$agentId/access'+ | '/bots/$agentId/approvals'+ | '/bots/$agentId/memory'+ | '/bots/$agentId/reach'+ | '/bots/$agentId/responsibilities'+ | '/bots/$agentId/routines'+ | '/bots/$agentId/setup'+ | '/bots/$agentId/sharing'+ | '/bots/$agentId/'| '/admin/plugins/$key/bots/$agentId'| '/admin/plugins/$key/tools/$tool'fileRoutesByTo: FileRoutesByTo@@ -506,6 +636,7 @@ export interface FileRouteTypes {| '/routines'| '/skills'| '/team-bots'+ | '/admin/approvals'| '/admin/audit'| '/admin/boundaries'| '/admin/computers'@@ -516,11 +647,13 @@ export interface FileRouteTypes {| '/admin/people'| '/admin/playground'| '/admin/skills'+ | '/settings/approvals'+ | '/settings/memory'+ | '/settings/notifications'| '/settings/passwords'| '/sign-in/$requestId'| '/admin'| '/settings'- | '/bots/$agentId'| '/channel/$channelId'| '/channel/new'| '/group/$channelId'@@ -536,6 +669,15 @@ export interface FileRouteTypes {| '/admin/plugins'| '/settings/components-gallery'| '/settings/connected-accounts'+ | '/bots/$agentId/access'+ | '/bots/$agentId/approvals'+ | '/bots/$agentId/memory'+ | '/bots/$agentId/reach'+ | '/bots/$agentId/responsibilities'+ | '/bots/$agentId/routines'+ | '/bots/$agentId/setup'+ | '/bots/$agentId/sharing'+ | '/bots/$agentId'| '/admin/plugins/$key/bots/$agentId'| '/admin/plugins/$key/tools/$tool'id:@@ -554,6 +696,7 @@ export interface FileRouteTypes {| '/_authed/_app/routines'| '/_authed/_app/skills'| '/_authed/_app/team-bots'+ | '/_authed/admin/approvals'| '/_authed/admin/audit'| '/_authed/admin/boundaries'| '/_authed/admin/computers'@@ -564,12 +707,14 @@ export interface FileRouteTypes {| '/_authed/admin/people'| '/_authed/admin/playground'| '/_authed/admin/skills'+ | '/_authed/settings/approvals'+ | '/_authed/settings/memory'+ | '/_authed/settings/notifications'| '/_authed/settings/passwords'| '/_authed/sign-in/$requestId'| '/_authed/_app/'| '/_authed/admin/'| '/_authed/settings/'- | '/_authed/_app/bots/$agentId'| '/_authed/_app/channel/$channelId'| '/_authed/_app/channel/new'| '/_authed/_app/group/$channelId'@@ -585,6 +730,15 @@ export interface FileRouteTypes {| '/_authed/admin/plugins/'| '/_authed/settings/components-gallery/'| '/_authed/settings/connected-accounts/'+ | '/_authed/_app/bots/$agentId/access'+ | '/_authed/_app/bots/$agentId/approvals'+ | '/_authed/_app/bots/$agentId/memory'+ | '/_authed/_app/bots/$agentId/reach'+ | '/_authed/_app/bots/$agentId/responsibilities'+ | '/_authed/_app/bots/$agentId/routines'+ | '/_authed/_app/bots/$agentId/setup'+ | '/_authed/_app/bots/$agentId/sharing'+ | '/_authed/_app/bots/$agentId/'| '/_authed/admin/plugins/$key_/bots/$agentId'| '/_authed/admin/plugins/$key_/tools/$tool'fileRoutesById: FileRoutesById@@ -708,6 +862,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof AuthedAdminIndexRouteImportparentRoute: typeof AuthedAdminRouteRoute}+ '/_authed/admin/approvals': {+ id: '/_authed/admin/approvals'+ path: '/approvals'+ fullPath: '/admin/approvals'+ preLoaderRoute: typeof AuthedAdminApprovalsRouteImport+ parentRoute: typeof AuthedAdminRouteRoute+ }'/_authed/admin/audit': {id: '/_authed/admin/audit'path: '/audit'@@ -785,6 +946,27 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof AuthedSettingsIndexRouteImportparentRoute: typeof AuthedSettingsRouteRoute}+ '/_authed/settings/approvals': {+ id: '/_authed/settings/approvals'+ path: '/approvals'+ fullPath: '/settings/approvals'+ preLoaderRoute: typeof AuthedSettingsApprovalsRouteImport+ parentRoute: typeof AuthedSettingsRouteRoute+ }+ '/_authed/settings/memory': {+ id: '/_authed/settings/memory'+ path: '/memory'+ fullPath: '/settings/memory'+ preLoaderRoute: typeof AuthedSettingsMemoryRouteImport+ parentRoute: typeof AuthedSettingsRouteRoute+ }+ '/_authed/settings/notifications': {+ id: '/_authed/settings/notifications'+ path: '/notifications'+ fullPath: '/settings/notifications'+ preLoaderRoute: typeof AuthedSettingsNotificationsRouteImport+ parentRoute: typeof AuthedSettingsRouteRoute+ }'/_authed/settings/passwords': {id: '/_authed/settings/passwords'path: '/passwords'@@ -813,13 +995,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof AuthedAppBotsIndexRouteImportparentRoute: typeof AuthedAppRoute}- '/_authed/_app/bots/$agentId': {- id: '/_authed/_app/bots/$agentId'- path: '/bots/$agentId'- fullPath: '/bots/$agentId'- preLoaderRoute: typeof AuthedAppBotsAgentIdRouteImport- parentRoute: typeof AuthedAppRoute- }'/_authed/_app/channel/$channelId': {id: '/_authed/_app/channel/$channelId'path: '/channel/$channelId'@@ -911,6 +1086,69 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof AuthedSettingsConnectedAccountsKeyRouteImportparentRoute: typeof AuthedSettingsRouteRoute}+ '/_authed/_app/bots/$agentId/': {+ id: '/_authed/_app/bots/$agentId/'+ path: '/bots/$agentId'+ fullPath: '/bots/$agentId/'+ preLoaderRoute: typeof AuthedAppBotsAgentIdIndexRouteImport+ parentRoute: typeof AuthedAppRoute+ }+ '/_authed/_app/bots/$agentId/access': {+ id: '/_authed/_app/bots/$agentId/access'+ path: '/bots/$agentId/access'+ fullPath: '/bots/$agentId/access'+ preLoaderRoute: typeof AuthedAppBotsAgentIdAccessRouteImport+ parentRoute: typeof AuthedAppRoute+ }+ '/_authed/_app/bots/$agentId/approvals': {+ id: '/_authed/_app/bots/$agentId/approvals'+ path: '/bots/$agentId/approvals'+ fullPath: '/bots/$agentId/approvals'+ preLoaderRoute: typeof AuthedAppBotsAgentIdApprovalsRouteImport+ parentRoute: typeof AuthedAppRoute+ }+ '/_authed/_app/bots/$agentId/memory': {+ id: '/_authed/_app/bots/$agentId/memory'+ path: '/bots/$agentId/memory'+ fullPath: '/bots/$agentId/memory'+ preLoaderRoute: typeof AuthedAppBotsAgentIdMemoryRouteImport+ parentRoute: typeof AuthedAppRoute+ }+ '/_authed/_app/bots/$agentId/reach': {+ id: '/_authed/_app/bots/$agentId/reach'+ path: '/bots/$agentId/reach'+ fullPath: '/bots/$agentId/reach'+ preLoaderRoute: typeof AuthedAppBotsAgentIdReachRouteImport+ parentRoute: typeof AuthedAppRoute+ }+ '/_authed/_app/bots/$agentId/responsibilities': {+ id: '/_authed/_app/bots/$agentId/responsibilities'+ path: '/bots/$agentId/responsibilities'+ fullPath: '/bots/$agentId/responsibilities'+ preLoaderRoute: typeof AuthedAppBotsAgentIdResponsibilitiesRouteImport+ parentRoute: typeof AuthedAppRoute+ }+ '/_authed/_app/bots/$agentId/routines': {+ id: '/_authed/_app/bots/$agentId/routines'+ path: '/bots/$agentId/routines'+ fullPath: '/bots/$agentId/routines'+ preLoaderRoute: typeof AuthedAppBotsAgentIdRoutinesRouteImport+ parentRoute: typeof AuthedAppRoute+ }+ '/_authed/_app/bots/$agentId/setup': {+ id: '/_authed/_app/bots/$agentId/setup'+ path: '/bots/$agentId/setup'+ fullPath: '/bots/$agentId/setup'+ preLoaderRoute: typeof AuthedAppBotsAgentIdSetupRouteImport+ parentRoute: typeof AuthedAppRoute+ }+ '/_authed/_app/bots/$agentId/sharing': {+ id: '/_authed/_app/bots/$agentId/sharing'+ path: '/bots/$agentId/sharing'+ fullPath: '/bots/$agentId/sharing'+ preLoaderRoute: typeof AuthedAppBotsAgentIdSharingRouteImport+ parentRoute: typeof AuthedAppRoute+ }'/_authed/admin/plugins/$key_/bots/$agentId': {id: '/_authed/admin/plugins/$key_/bots/$agentId'path: '/plugins/$key/bots/$agentId'@@ -929,6 +1167,7 @@ declare module '@tanstack/react-router' {}interface AuthedAdminRouteRouteChildren {+ AuthedAdminApprovalsRoute: typeof AuthedAdminApprovalsRouteAuthedAdminAuditRoute: typeof AuthedAdminAuditRouteAuthedAdminBoundariesRoute: typeof AuthedAdminBoundariesRouteAuthedAdminComputersRoute: typeof AuthedAdminComputersRoute@@ -950,6 +1189,7 @@ interface AuthedAdminRouteRouteChildren {}const AuthedAdminRouteRouteChildren: AuthedAdminRouteRouteChildren = {+ AuthedAdminApprovalsRoute: AuthedAdminApprovalsRoute,AuthedAdminAuditRoute: AuthedAdminAuditRoute,AuthedAdminBoundariesRoute: AuthedAdminBoundariesRoute,AuthedAdminComputersRoute: AuthedAdminComputersRoute,@@ -974,6 +1214,9 @@ const AuthedAdminRouteRouteWithChildren =AuthedAdminRouteRoute._addFileChildren(AuthedAdminRouteRouteChildren)interface AuthedSettingsRouteRouteChildren {+ AuthedSettingsApprovalsRoute: typeof AuthedSettingsApprovalsRoute+ AuthedSettingsMemoryRoute: typeof AuthedSettingsMemoryRoute+ AuthedSettingsNotificationsRoute: typeof AuthedSettingsNotificationsRouteAuthedSettingsPasswordsRoute: typeof AuthedSettingsPasswordsRouteAuthedSettingsIndexRoute: typeof AuthedSettingsIndexRouteAuthedSettingsComponentsGalleryNameRoute: typeof AuthedSettingsComponentsGalleryNameRoute@@ -983,6 +1226,9 @@ interface AuthedSettingsRouteRouteChildren {}const AuthedSettingsRouteRouteChildren: AuthedSettingsRouteRouteChildren = {+ AuthedSettingsApprovalsRoute: AuthedSettingsApprovalsRoute,+ AuthedSettingsMemoryRoute: AuthedSettingsMemoryRoute,+ AuthedSettingsNotificationsRoute: AuthedSettingsNotificationsRoute,AuthedSettingsPasswordsRoute: AuthedSettingsPasswordsRoute,AuthedSettingsIndexRoute: AuthedSettingsIndexRoute,AuthedSettingsComponentsGalleryNameRoute:@@ -1008,13 +1254,21 @@ interface AuthedAppRouteChildren {AuthedAppSkillsRoute: typeof AuthedAppSkillsRouteAuthedAppTeamBotsRoute: typeof AuthedAppTeamBotsRouteAuthedAppIndexRoute: typeof AuthedAppIndexRoute- AuthedAppBotsAgentIdRoute: typeof AuthedAppBotsAgentIdRouteAuthedAppChannelChannelIdRoute: typeof AuthedAppChannelChannelIdRouteAuthedAppChannelNewRoute: typeof AuthedAppChannelNewRouteAuthedAppGroupChannelIdRoute: typeof AuthedAppGroupChannelIdRouteAuthedAppGroupNewRoute: typeof AuthedAppGroupNewRouteAuthedAppAgentsIndexRoute: typeof AuthedAppAgentsIndexRouteAuthedAppBotsIndexRoute: typeof AuthedAppBotsIndexRoute+ AuthedAppBotsAgentIdAccessRoute: typeof AuthedAppBotsAgentIdAccessRoute+ AuthedAppBotsAgentIdApprovalsRoute: typeof AuthedAppBotsAgentIdApprovalsRoute+ AuthedAppBotsAgentIdMemoryRoute: typeof AuthedAppBotsAgentIdMemoryRoute+ AuthedAppBotsAgentIdReachRoute: typeof AuthedAppBotsAgentIdReachRoute+ AuthedAppBotsAgentIdResponsibilitiesRoute: typeof AuthedAppBotsAgentIdResponsibilitiesRoute+ AuthedAppBotsAgentIdRoutinesRoute: typeof AuthedAppBotsAgentIdRoutinesRoute+ AuthedAppBotsAgentIdSetupRoute: typeof AuthedAppBotsAgentIdSetupRoute+ AuthedAppBotsAgentIdSharingRoute: typeof AuthedAppBotsAgentIdSharingRoute+ AuthedAppBotsAgentIdIndexRoute: typeof AuthedAppBotsAgentIdIndexRoute}const AuthedAppRouteChildren: AuthedAppRouteChildren = {@@ -1027,13 +1281,22 @@ const AuthedAppRouteChildren: AuthedAppRouteChildren = {AuthedAppSkillsRoute: AuthedAppSkillsRoute,AuthedAppTeamBotsRoute: AuthedAppTeamBotsRoute,AuthedAppIndexRoute: AuthedAppIndexRoute,- AuthedAppBotsAgentIdRoute: AuthedAppBotsAgentIdRoute,AuthedAppChannelChannelIdRoute: AuthedAppChannelChannelIdRoute,AuthedAppChannelNewRoute: AuthedAppChannelNewRoute,AuthedAppGroupChannelIdRoute: AuthedAppGroupChannelIdRoute,AuthedAppGroupNewRoute: AuthedAppGroupNewRoute,AuthedAppAgentsIndexRoute: AuthedAppAgentsIndexRoute,AuthedAppBotsIndexRoute: AuthedAppBotsIndexRoute,+ AuthedAppBotsAgentIdAccessRoute: AuthedAppBotsAgentIdAccessRoute,+ AuthedAppBotsAgentIdApprovalsRoute: AuthedAppBotsAgentIdApprovalsRoute,+ AuthedAppBotsAgentIdMemoryRoute: AuthedAppBotsAgentIdMemoryRoute,+ AuthedAppBotsAgentIdReachRoute: AuthedAppBotsAgentIdReachRoute,+ AuthedAppBotsAgentIdResponsibilitiesRoute:+ AuthedAppBotsAgentIdResponsibilitiesRoute,+ AuthedAppBotsAgentIdRoutinesRoute: AuthedAppBotsAgentIdRoutinesRoute,+ AuthedAppBotsAgentIdSetupRoute: AuthedAppBotsAgentIdSetupRoute,+ AuthedAppBotsAgentIdSharingRoute: AuthedAppBotsAgentIdSharingRoute,+ AuthedAppBotsAgentIdIndexRoute: AuthedAppBotsAgentIdIndexRoute,}const AuthedAppRouteWithChildren = AuthedAppRoute._addFileChildren(diff --git a/app/src/routes/_authed/_app/agents/index.tsx b/app/src/routes/_authed/_app/agents/index.tsxindex cd1f7b06..c7c04fcb 100644--- a/app/src/routes/_authed/_app/agents/index.tsx+++ b/app/src/routes/_authed/_app/agents/index.tsx@@ -1,248 +1,14 @@-import { IconChevronDown, IconPlus } from "@tabler/icons-react";-import { useQuery } from "@tanstack/react-query";-import { createFileRoute, Link } from "@tanstack/react-router";+import { createFileRoute, redirect } from "@tanstack/react-router";import { z } from "zod";-import { AgentCard } from "@/components/agents/agent-card";-import { AgentDialog } from "@/components/agents/agent-dialog";-import { CreateAgentDialog } from "@/components/agents/create-agent-dialog";-import { SidebarToggleBar } from "@/components/layout/sidebar-toggle";-import { StaggerItem } from "@/components/layout/stagger";-import { Button } from "@/components/ui/button";-import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";-import { Skeleton } from "@/components/ui/skeleton";-import { agentListQueryOptions, isSharedWithYou } from "@/lib/agents/queries";--/**- * Creating and inspecting a coworker are search-parameter states so the roster remains mounted and- * Back closes the dialog.- */-const agentsSearchSchema = z.object({- new: z.boolean().optional(),- agent: z.string().optional(),-});+import { legacyAgentsTarget } from "@/lib/agents/legacy-routes";+/** `/agents` was the coworker screen. The Bots roster and each Bot's own page replaced it. */export const Route = createFileRoute("/_authed/_app/agents/")({- validateSearch: agentsSearchSchema,- component: AgentsScreen,+ validateSearch: z.object({+ new: z.boolean().optional(),+ agent: z.string().optional(),+ }),+ beforeLoad: ({ search }) => {+ throw redirect(legacyAgentsTarget(search));+ },});--// Two equal columns let cards fill the available width at a consistent height.-function AgentsScreen() {- const { new: isCreating, agent: selectedAgentId } = Route.useSearch();- const navigate = Route.useNavigate();- /*- * The two empty states below must not fire while the list is still arriving. `skills.tsx` learned- * this first: an empty state standing there saying somebody has created nothing is a claim the- * screen has not yet earned, and on a slow connection it is the first thing they read.- *- * `isPending` rather than `agents === undefined`, and the difference is the whole point on a- * screen whose job is to say when there is nothing. `data` is also undefined when the query- * FAILED, so deriving the flag from it holds the screen in its loading branch forever on an- * error — two headings over nothing, which is the exact shape this task exists to remove.- * `isPending` goes false either way, so a failure falls through to the empty state.- */- const {- data: agents,- isPending: loading,- isError: failed,- } = useQuery(agentListQueryOptions());- /*- * A pinned coworker moves up into its own section rather than appearing twice. The two rosters- * below then say so when pinning emptied them, instead of claiming there is nothing at all.- */- const pinned = agents?.filter((a) => a.pinned);- const mine = agents?.filter((a) => a.mine && !a.pinned);- const explore = agents?.filter((a) => isSharedWithYou(a) && !a.pinned);- const minePinned = agents?.some((a) => a.mine && a.pinned);- const explorePinned = agents?.some((a) => isSharedWithYou(a) && a.pinned);- /*- * Hiding takes a coworker off both lists above, and Unhide lives in its dialog, which only a card- * opens. Without this section a hidden coworker had no way back onto the screen short of typing- * its id into the address bar. Nothing while loading, failed or empty: it is a way back for- * somebody who hid something, not a third roster everybody has to read past.- */- const { data: hiddenAgents } = useQuery(agentListQueryOptions(true));-- // Creating wins if both are somehow set: it is the more recent intent.- const showCreate = isCreating === true;- const showProfile = !showCreate && selectedAgentId !== undefined;- const close = () => navigate({ search: {} });-- return (- <>- <SidebarToggleBar />- <div className="max-w-2xl px-4 w-full mx-auto">- {pinned?.length ? (- <div className="mt-12 w-full max-w-2xl">- <h2 className="font-bold text-lg">Pinned</h2>- <div className="mt-4 grid grid-cols-2 gap-4">- {pinned.map((agent, index) => (- <StaggerItem className="min-w-0" index={index} key={agent.id}>- <AgentCard agent={agent} />- </StaggerItem>- ))}- </div>- </div>- ) : null}- <div- className={`${pinned?.length ? "mt-8" : "mt-12"} w-full max-w-2xl`}- >- <div className="flex flex-row w-full items-center justify-between">- <h2 className="font-bold text-lg">Your agents</h2>- <Button- variant="ghost"- size="sm"- render={(props) => (- <Link to="/agents" search={{ new: true }} {...props} />- )}- >- <IconPlus />- New agent- </Button>- </div>- {loading ? (- // Approximate one row of cards while the roster loads.- <Skeleton className="mt-4 h-[180px]" />- ) : mine?.length ? (- // Wins over `failed`: TanStack Query keeps the last good `data` across a failed- // background refetch (see query-core's error action — it spreads `...state` and- // never clears `data`), so `isError` and a still-populated roster are an ordinary- // combination, not a contradiction. A stale roster beats an error card claiming- // there is nothing, which would be false here.- <div className="mt-4 grid grid-cols-2 gap-4">- {mine.map((agent, index) => {- return (- <StaggerItem className="min-w-0" index={index} key={agent.id}>- <AgentCard agent={agent} />- </StaggerItem>- );- })}- </div>- ) : minePinned ? (- <Empty className="mt-4 h-[180px] border border-dashed">- <EmptyHeader>- <EmptyTitle className="text-muted-foreground">- Your agents are all pinned above.- </EmptyTitle>- </EmptyHeader>- </Empty>- ) : failed && agents === undefined ? (- // `agents === undefined` narrows this to "the query has never once returned- // successfully" — not merely "the last request errored". `?.length` alone can't- // tell that apart from a slice that loaded and is genuinely empty: TanStack Query- // never clears `data` on a failed background refetch, so once the query has- // resolved even one response, `agents` stays defined and `mine`'s emptiness is a- // fact about that response, not a symptom of the failure. Rendering the destructive- // card there would say the opposite of what "Explore agents" beside it (or this- // section itself, on a different roster) proves by rendering real cards from the- // same query.- <Empty className="mt-4 h-[180px] border border-dashed border-destructive">- <EmptyHeader>- <EmptyTitle className="text-destructive">- Your agents couldn't be loaded.- </EmptyTitle>- </EmptyHeader>- </Empty>- ) : (- // Reached both when the query never failed and `mine` is genuinely empty, and when- // it failed but `agents` is defined — a loaded, empty slice either way. Same plain- // copy for both: an empty roster is a fact, not an error.- <Empty className="mt-4 h-[180px] border border-dashed">- <EmptyHeader>- <EmptyTitle className="text-muted-foreground">- You don't have any agents created.- </EmptyTitle>- </EmptyHeader>- </Empty>- )}- </div>- <div className="mt-8 w-full max-w-2xl">- <h2 className="font-bold text-lg">Explore agents</h2>- {loading ? (- // Approximate one row of cards while the roster loads.- <Skeleton className="mt-4 h-[180px]" />- ) : explore?.length ? (- // Wins over `failed` for the same reason the "Your agents" section above does: a- // failed background refetch does not clear TanStack Query's cached `data`.- <div className="mt-4 grid grid-cols-2 gap-4">- {explore.map((agent, index) => {- return (- <StaggerItem className="min-w-0" index={index} key={agent.id}>- <AgentCard agent={agent} />- </StaggerItem>- );- })}- </div>- ) : explorePinned ? (- <Empty className="mt-4 h-[180px] border border-dashed">- <EmptyHeader>- <EmptyTitle className="text-muted-foreground">- The agents shared with you are all pinned above.- </EmptyTitle>- </EmptyHeader>- </Empty>- ) : failed && agents === undefined ? (- // `agents === undefined` narrows this to "the query has never once returned- // successfully" — not merely "the last request errored". `?.length` alone can't- // tell that apart from a slice that loaded and is genuinely empty: TanStack Query- // never clears `data` on a failed background refetch, so once the query has- // resolved even one response, `agents` stays defined and `explore`'s emptiness is a- // fact about that response, not a symptom of the failure. Rendering the destructive- // card there would say the opposite of what "Your agents" beside it (or this- // section itself, on a different roster) proves by rendering real cards from the- // same query.- <Empty className="mt-4 h-[180px] border border-dashed border-destructive">- <EmptyHeader>- <EmptyTitle className="text-destructive">- Agents shared with you couldn't be loaded.- </EmptyTitle>- </EmptyHeader>- </Empty>- ) : (- // Reached both when the query never failed and `explore` is genuinely empty, and- // when it failed but `agents` is defined — a loaded, empty slice either way. Same- // plain copy for both: an empty roster is a fact, not an error.- <Empty className="mt-4 h-[180px] border border-dashed">- <EmptyHeader>- <EmptyTitle className="text-muted-foreground">- Nobody has shared an agent with you yet.- </EmptyTitle>- </EmptyHeader>- </Empty>- )}- </div>- {hiddenAgents?.length ? (- <details className="group mt-8 mb-12 w-full max-w-2xl">- <summary className="flex cursor-pointer list-none items-center gap-2 [&::-webkit-details-marker]:hidden">- <h2 className="font-bold text-lg">Hidden</h2>- <span className="text-sm text-muted-foreground">- {hiddenAgents.length}- </span>- <IconChevronDown- aria-hidden="true"- className="size-4 text-muted-foreground transition-transform group-open:rotate-180 motion-reduce:transition-none"- />- </summary>- <div className="mt-4 grid grid-cols-2 gap-4">- {hiddenAgents.map((agent) => (- <div className="min-w-0" key={agent.id}>- <AgentCard agent={agent} />- </div>- ))}- </div>- </details>- ) : null}- </div>- <CreateAgentDialog- onClose={close}- onCreated={(agentId) => navigate({ search: { agent: agentId } })}- open={showCreate}- />- <AgentDialog- agentId={selectedAgentId ?? null}- onClose={close}- open={showProfile}- />- </>- );-}diff --git a/app/src/routes/_authed/_app/approvals.tsx b/app/src/routes/_authed/_app/approvals.tsxindex c49f7c73..30edca71 100644--- a/app/src/routes/_authed/_app/approvals.tsx+++ b/app/src/routes/_authed/_app/approvals.tsx@@ -1,16 +1,9 @@-import { createFileRoute } from "@tanstack/react-router";-import { ApprovalInbox } from "@/components/approvals/inbox";-import { PageShell } from "@/components/layout/page-shell";+import { createFileRoute, redirect } from "@tanstack/react-router";+import { LEGACY_PAGES } from "@/lib/agents/legacy-routes";++/** `/approvals` left the sidebar. What waits on you is on each Bot's page; preferences and rules for every Bot are in Settings. */export const Route = createFileRoute("/_authed/_app/approvals")({- component: ApprovalsPage,+ beforeLoad: () => {+ throw redirect({ to: LEGACY_PAGES["/approvals"], replace: true });+ },});-function ApprovalsPage() {- return (- <PageShell- title="Approvals"- description="Choose what your Bots may do, and review actions waiting for you."- >- <ApprovalInbox />- </PageShell>- );-}diff --git a/app/src/routes/_authed/_app/bots.$agentId.access.tsx b/app/src/routes/_authed/_app/bots.$agentId.access.tsxnew file mode 100644index 00000000..1c859119--- /dev/null+++ b/app/src/routes/_authed/_app/bots.$agentId.access.tsx@@ -0,0 +1,20 @@+import { createFileRoute } from "@tanstack/react-router";+import { AccessSections } from "@/components/bot-profile/access";+import { BotSubpage } from "@/components/bot-profile/bot-subpage";++export const Route = createFileRoute("/_authed/_app/bots/$agentId/access")({+ component: AccessPage,+});++function AccessPage() {+ const { agentId } = Route.useParams();+ return (+ <BotSubpage+ agentId={agentId}+ description="The skills, apps and other Bots this Bot may use."+ title="Skills and access"+ >+ {(agent) => <AccessSections agent={agent} />}+ </BotSubpage>+ );+}diff --git a/app/src/routes/_authed/_app/bots.$agentId.approvals.tsx b/app/src/routes/_authed/_app/bots.$agentId.approvals.tsxnew file mode 100644index 00000000..94f2fa87--- /dev/null+++ b/app/src/routes/_authed/_app/bots.$agentId.approvals.tsx@@ -0,0 +1,20 @@+import { createFileRoute } from "@tanstack/react-router";+import { BotApprovalRules } from "@/components/approvals/bot-rules";+import { BotSubpage } from "@/components/bot-profile/bot-subpage";++export const Route = createFileRoute("/_authed/_app/bots/$agentId/approvals")({+ component: ApprovalRulesPage,+});++function ApprovalRulesPage() {+ const { agentId } = Route.useParams();+ return (+ <BotSubpage+ agentId={agentId}+ description="What this Bot may do without asking you first."+ title="Approval rules"+ >+ {(agent) => <BotApprovalRules agentId={agent.id} />}+ </BotSubpage>+ );+}diff --git a/app/src/routes/_authed/_app/bots.$agentId.index.tsx b/app/src/routes/_authed/_app/bots.$agentId.index.tsxnew file mode 100644index 00000000..410eb5d1--- /dev/null+++ b/app/src/routes/_authed/_app/bots.$agentId.index.tsx@@ -0,0 +1,49 @@+import { useQuery } from "@tanstack/react-query";+import { createFileRoute, useNavigate } from "@tanstack/react-router";+import { ManageSection } from "@/components/bot-profile/manage";+import { BotProfile } from "@/components/bot-profile/profile";+import { BotSettingsRows } from "@/components/bot-profile/settings-rows";+import { PageShell } from "@/components/layout/page-shell";+import { agentQueryOptions } from "@/lib/agents/queries";++export const Route = createFileRoute("/_authed/_app/bots/$agentId/")({+ component: BotProfilePage,+});++function BotProfilePage() {+ const { agentId } = Route.useParams();+ const navigate = useNavigate();+ const agent = useQuery(agentQueryOptions(agentId));+ const toRoster = () => void navigate({ to: "/bots" });+ return (+ <PageShell+ backButton={{ label: "Bots", linkProps: { to: "/bots" } }}+ description="What this Bot is doing for you, and how it is set up."+ title={agent.data?.name ?? "Bot"}+ >+ {agent.isPending ? null : agent.error ? (+ <p className="mt-6 text-destructive text-sm" role="alert">+ This Bot is not one you can reach.+ </p>+ ) : (+ <BotProfile+ agent={agent.data}+ manage={+ <ManageSection+ agent={agent.data}+ onDeleted={toRoster}+ onDuplicated={(copyId) =>+ void navigate({+ params: { agentId: copyId },+ to: "/bots/$agentId",+ })+ }+ onHidden={toRoster}+ />+ }+ settings={<BotSettingsRows agent={agent.data} />}+ />+ )}+ </PageShell>+ );+}diff --git a/app/src/routes/_authed/_app/bots.$agentId.memory.tsx b/app/src/routes/_authed/_app/bots.$agentId.memory.tsxnew file mode 100644index 00000000..f1446edd--- /dev/null+++ b/app/src/routes/_authed/_app/bots.$agentId.memory.tsx@@ -0,0 +1,36 @@+import { createFileRoute, Link } from "@tanstack/react-router";+import { BotSubpage } from "@/components/bot-profile/bot-subpage";+import { MemorySources } from "@/components/memory/sources";+import { ProactiveResearchSettings } from "@/components/suggestions/proactive-panel";++export const Route = createFileRoute("/_authed/_app/bots/$agentId/memory")({+ component: MemoryPage,+});++function MemoryPage() {+ const { agentId } = Route.useParams();+ return (+ <BotSubpage+ agentId={agentId}+ description="Which connected apps feed this Bot facts, and the background research it does for you."+ title="Memory"+ >+ {(agent) => (+ <>+ <p className="mt-6 text-muted-foreground text-sm">+ What your Bots remember about you is in{" "}+ <Link+ className="underline underline-offset-4"+ to="/settings/memory"+ >+ Settings → Memory+ </Link>+ .+ </p>+ <MemorySources agentId={agent.id} />+ <ProactiveResearchSettings agentId={agent.id} />+ </>+ )}+ </BotSubpage>+ );+}diff --git a/app/src/routes/_authed/_app/bots.$agentId.reach.tsx b/app/src/routes/_authed/_app/bots.$agentId.reach.tsxnew file mode 100644index 00000000..0c60d3cd--- /dev/null+++ b/app/src/routes/_authed/_app/bots.$agentId.reach.tsx@@ -0,0 +1,20 @@+import { createFileRoute } from "@tanstack/react-router";+import { BotSubpage } from "@/components/bot-profile/bot-subpage";+import { ReachingYou } from "@/components/delivery/reaching-you";++export const Route = createFileRoute("/_authed/_app/bots/$agentId/reach")({+ component: ReachPage,+});++function ReachPage() {+ const { agentId } = Route.useParams();+ return (+ <BotSubpage+ agentId={agentId}+ description="Continue a conversation with this Bot in Slack, Microsoft Teams, or by text message."+ title="Reaching you"+ >+ {(agent) => <ReachingYou agentId={agent.id} />}+ </BotSubpage>+ );+}diff --git a/app/src/routes/_authed/_app/bots.$agentId.responsibilities.tsx b/app/src/routes/_authed/_app/bots.$agentId.responsibilities.tsxnew file mode 100644index 00000000..ec612945--- /dev/null+++ b/app/src/routes/_authed/_app/bots.$agentId.responsibilities.tsx@@ -0,0 +1,22 @@+import { createFileRoute } from "@tanstack/react-router";+import { BotSubpage } from "@/components/bot-profile/bot-subpage";+import { BotResponsibilities } from "@/components/responsibilities/responsibilities";++export const Route = createFileRoute(+ "/_authed/_app/bots/$agentId/responsibilities",+)({+ component: ResponsibilitiesPage,+});++function ResponsibilitiesPage() {+ const { agentId } = Route.useParams();+ return (+ <BotSubpage+ agentId={agentId}+ description="Lasting goals this Bot works on for you, what started each run, and what it found."+ title="Responsibilities"+ >+ {(agent) => <BotResponsibilities agentId={agent.id} />}+ </BotSubpage>+ );+}diff --git a/app/src/routes/_authed/_app/bots.$agentId.routines.tsx b/app/src/routes/_authed/_app/bots.$agentId.routines.tsxnew file mode 100644index 00000000..b2cc6584--- /dev/null+++ b/app/src/routes/_authed/_app/bots.$agentId.routines.tsx@@ -0,0 +1,20 @@+import { createFileRoute } from "@tanstack/react-router";+import { BotSubpage } from "@/components/bot-profile/bot-subpage";+import { RoutinesList } from "@/components/routines/routines-list";++export const Route = createFileRoute("/_authed/_app/bots/$agentId/routines")({+ component: RoutinesPage,+});++function RoutinesPage() {+ const { agentId } = Route.useParams();+ return (+ <BotSubpage+ agentId={agentId}+ description="What this Bot does for you on a schedule. Switch one off, run it now, or delete it."+ title="Routines"+ >+ {(agent) => <RoutinesList agentId={agent.id} />}+ </BotSubpage>+ );+}diff --git a/app/src/routes/_authed/_app/bots.$agentId.setup.tsx b/app/src/routes/_authed/_app/bots.$agentId.setup.tsxnew file mode 100644index 00000000..ab394a04--- /dev/null+++ b/app/src/routes/_authed/_app/bots.$agentId.setup.tsx@@ -0,0 +1,20 @@+import { createFileRoute } from "@tanstack/react-router";+import { BotSubpage } from "@/components/bot-profile/bot-subpage";+import { SetupSections } from "@/components/bot-profile/setup";++export const Route = createFileRoute("/_authed/_app/bots/$agentId/setup")({+ component: SetupPage,+});++function SetupPage() {+ const { agentId } = Route.useParams();+ return (+ <BotSubpage+ agentId={agentId}+ description="Who this Bot is, who can find it, and where it runs."+ title="Setup"+ >+ {(agent) => <SetupSections agent={agent} />}+ </BotSubpage>+ );+}diff --git a/app/src/routes/_authed/_app/bots.$agentId.sharing.tsx b/app/src/routes/_authed/_app/bots.$agentId.sharing.tsxnew file mode 100644index 00000000..69243d32--- /dev/null+++ b/app/src/routes/_authed/_app/bots.$agentId.sharing.tsx@@ -0,0 +1,20 @@+import { createFileRoute } from "@tanstack/react-router";+import { BotSubpage } from "@/components/bot-profile/bot-subpage";+import { SharingSections } from "@/components/bot-profile/sharing";++export const Route = createFileRoute("/_authed/_app/bots/$agentId/sharing")({+ component: SharingPage,+});++function SharingPage() {+ const { agentId } = Route.useParams();+ return (+ <BotSubpage+ agentId={agentId}+ description="Who else can use this Bot. Each chat with it is private to the person having it."+ title="Sharing"+ >+ {(agent) => <SharingSections agent={agent} />}+ </BotSubpage>+ );+}diff --git a/app/src/routes/_authed/_app/bots.$agentId.tsx b/app/src/routes/_authed/_app/bots.$agentId.tsxdeleted file mode 100644index e754b70d..00000000--- a/app/src/routes/_authed/_app/bots.$agentId.tsx+++ /dev/null@@ -1,29 +0,0 @@-import { useQuery } from "@tanstack/react-query";-import { createFileRoute } from "@tanstack/react-router";-import { BotProfile } from "@/components/bot-profile/profile";-import { PageShell } from "@/components/layout/page-shell";-import { agentQueryOptions } from "@/lib/agents/queries";--export const Route = createFileRoute("/_authed/_app/bots/$agentId")({- component: BotProfilePage,-});--function BotProfilePage() {- const { agentId } = Route.useParams();- const agent = useQuery(agentQueryOptions(agentId));- return (- <PageShell- backButton={{ label: "Bots", linkProps: { to: "/bots" } }}- description="What this Bot is doing for you, and how it runs."- title={agent.data?.name ?? "Bot"}- >- {agent.isPending ? null : agent.error ? (- <p className="mt-6 text-destructive text-sm" role="alert">- This Bot is not one you can reach.- </p>- ) : (- <BotProfile agent={agent.data} />- )}- </PageShell>- );-}diff --git a/app/src/routes/_authed/_app/bots.index.tsx b/app/src/routes/_authed/_app/bots.index.tsxindex 21974f41..63394c05 100644--- a/app/src/routes/_authed/_app/bots.index.tsx+++ b/app/src/routes/_authed/_app/bots.index.tsx@@ -1,88 +1,48 @@-import { IconChevronRight } from "@tabler/icons-react";-import { useQuery } from "@tanstack/react-query";+import { IconPlus } from "@tabler/icons-react";import { createFileRoute, Link } from "@tanstack/react-router";-import { Fragment } from "react";-import { AbstractAvatar } from "@/components/agents/abstract-avatar";-import {- attentionSummary,- needsInput,-} from "@/components/bot-profile/attention";-import { PageEmpty, PageRows, PageShell } from "@/components/layout/page-shell";-import {- Item,- ItemActions,- ItemContent,- ItemDescription,- ItemMedia,- ItemTitle,-} from "@/components/ui/item";-import { Separator } from "@/components/ui/separator";-import { agentListQueryOptions } from "@/lib/agents/queries";-import { botAttentionQueryOptions } from "@/lib/bot-lifecycle/queries";+import { z } from "zod";+import { CreateAgentDialog } from "@/components/agents/create-agent-dialog";+import { BotRoster } from "@/components/bots/bot-roster";+import { PageShell } from "@/components/layout/page-shell";+import { Button } from "@/components/ui/button";+/** Creating a Bot is a search-parameter state, so the roster stays mounted and Back closes it. */export const Route = createFileRoute("/_authed/_app/bots/")({+ validateSearch: z.object({ new: z.boolean().optional() }),component: BotsPage,});-/** Every Bot the person can reach, with what each needs from them, each opening its profile. */function BotsPage() {- const agents = useQuery(agentListQueryOptions());- const attention = useQuery(botAttentionQueryOptions());- const byId = new Map((attention.data ?? []).map((bot) => [bot.agentId, bot]));+ const { new: creating } = Route.useSearch();+ const navigate = Route.useNavigate();return (<PageShell- description="What each of your Bots is doing, what it needs from you, and whether it is paused."+ action={+ <Button+ render={(props) => (+ <Link {...props} search={{ new: true }} to="/bots" />+ )}+ size="lg"+ >+ <IconPlus />+ New Bot+ </Button>+ }+ description="Every Bot you can reach: what each is doing, what it needs from you, and whether it is paused."title="Bots">- {agents.isPending ? null : agents.error ? (- <p className="mt-6 text-destructive text-sm" role="alert">- Could not load your Bots.- </p>- ) : agents.data.length === 0 ? (- <PageEmpty>You have no Bots yet.</PageEmpty>- ) : (- <PageRows className="mt-6">- {agents.data.map((agent, index) => {- const state = byId.get(agent.id);- const summary = state- ? [state.paused ? "Paused" : "", attentionSummary(state)]- .filter(Boolean)- .join(" · ")- : "";- return (- <Fragment key={agent.id}>- {index > 0 ? <Separator /> : null}- <Item- render={- <Link params={{ agentId: agent.id }} to="/bots/$agentId" />- }- size="sm"- >- <ItemMedia>- <AbstractAvatar- name={agent.name}- seed={agent.avatarSeed}- size={28}- />- </ItemMedia>- <ItemContent>- <ItemTitle>{agent.name}</ItemTitle>- <ItemDescription>{summary || agent.title}</ItemDescription>- </ItemContent>- <ItemActions>- {state && needsInput(state) > 0 ? (- <span className="rounded-full bg-primary px-1.5 text-[11px] font-medium text-primary-foreground tabular-nums">- {needsInput(state)}- </span>- ) : null}- <IconChevronRight className="size-4 text-muted-foreground" />- </ItemActions>- </Item>- </Fragment>- );- })}- </PageRows>- )}+ <BotRoster />+ <CreateAgentDialog+ onClose={() => void navigate({ search: {} })}+ onCreated={(agentId) =>+ void navigate({+ params: { agentId },+ search: {},+ to: "/bots/$agentId",+ })+ }+ open={creating === true}+ /></PageShell>);}diff --git a/app/src/routes/_authed/_app/channel/$channelId.tsx b/app/src/routes/_authed/_app/channel/$channelId.tsxindex f54589b9..5bc28436 100644--- a/app/src/routes/_authed/_app/channel/$channelId.tsx+++ b/app/src/routes/_authed/_app/channel/$channelId.tsx@@ -1,30 +1,20 @@import { IconSettings } from "@tabler/icons-react";-import {- useInfiniteQuery,- useMutation,- useQuery,- useQueryClient,-} from "@tanstack/react-query";+import { useQuery } from "@tanstack/react-query";import { createFileRoute, Navigate } from "@tanstack/react-router";import { motion, useReducedMotion } from "motion/react";import { useEffect, useRef } from "react";import { z } from "zod";import { AgentProfile } from "@/components/agents/agent-profile";-import { hasUnseenActivity } from "@/components/app-sidebar/app-sidebar";-import { ChannelAvatar } from "@/components/channels/avatar";import { BotPausedBanner } from "@/components/bot-profile/pause-banner";+import { ChannelAvatar } from "@/components/channels/avatar";import { ChannelChat } from "@/components/channels/channel-chat";import { ComputerChatControls } from "@/components/computer/computer-controls";import { ComputerViewPanel } from "@/components/computer/computer-panel";import { DetailPanel } from "@/components/layout/detail-panel";import { SidebarToggle } from "@/components/layout/sidebar-toggle";import { Button } from "@/components/ui/button";-import { markChannelReadMutationOptions } from "@/lib/channels/mutations";-import {- type AgentChannel,- channelListQueryOptions,- channelQueryOptions,-} from "@/lib/channels/queries";+import { useMarkOpenChannelRead } from "@/lib/channels/mark-read";+import { type AgentChannel, channelQueryOptions } from "@/lib/channels/queries";import { onComputerActivity } from "@/lib/copilot/computer-activity";const chatSearchSchema = z.object({@@ -57,34 +47,7 @@ function RouteComponent() {/** Channel routing currently supports one coworker. */const agentId = channel.data?.agentIds[0];- const queryClient = useQueryClient();- const markRead = useMutation(markChannelReadMutationOptions(queryClient));- /*- * This channel's roster summary, read out of the same infinite query the sidebar renders.- * The detail query deliberately knows nothing about activity; the roster is where the socket- * keeps lastMessageAt live, so it is the one honest source for "has something new been said".- */- const roster = useInfiniteQuery(channelListQueryOptions());- const summary = roster.data?.find((row) => row.id === channelId);-- /*- * Opening the channel marks it read; the Bot replying while it is open marks it read again.- * One effect covers both: the dep changes on navigation and on every activity patch, and the- * unseen check keeps it from writing a row per render. No dependency on the mutation object —- * its identity changes per render and the effect must not re-fire for that.- *- * Keyed on primitives, deliberately. The optimistic mark-read patch changes the summary OBJECT's- * identity without changing these values, so an object dep would re-fire the effect on its own- * write — and when lastMessageAt sits ahead of this browser's clock (another device wrote it),- * that re-fire loops into a PUT per render. Primitives hold still under the patch: one PUT.- */- const unseen = summary !== undefined && hasUnseenActivity(summary);- const markReadMutate = markRead.mutate;- useEffect(() => {- if (unseen) {- markReadMutate(channelId);- }- }, [channelId, unseen, markReadMutate]);+ useMarkOpenChannelRead(channelId);// Browser activity may auto-open the screen once per run unless this run was dismissed.const dismissedEpoch = useRef<number | null>(null);diff --git a/app/src/routes/_authed/_app/channel/new.tsx b/app/src/routes/_authed/_app/channel/new.tsxindex a2f40f3f..4193fee5 100644--- a/app/src/routes/_authed/_app/channel/new.tsx+++ b/app/src/routes/_authed/_app/channel/new.tsx@@ -3,17 +3,25 @@ import { useQuery } from "@tanstack/react-query";import { createFileRoute } from "@tanstack/react-router";import { useState } from "react";import { ChannelAvatar } from "@/components/channels/avatar";-import { canSend, type Recipient } from "@/components/channels/compose-state";+import {+ canSend,+ type Recipient,+ startsGroup,+ toFieldChange,+} from "@/components/channels/compose-state";import { ConversationView } from "@/components/channels/conversation-view";import { seedMessage } from "@/components/channels/transcript-messages";import { SidebarToggle } from "@/components/layout/sidebar-toggle";import {Combobox,+ ComboboxChip,+ ComboboxChips,+ ComboboxChipsInput,ComboboxContent,ComboboxEmpty,- ComboboxInput,ComboboxItem,ComboboxList,+ useComboboxAnchor,} from "@/components/ui/combobox";import { defaultAgentProfile } from "@/lib/agents/default-agent";import {@@ -26,8 +34,9 @@ import { useSkillCommands } from "@/lib/plugins/skill-commands";import { newId } from "../../../../lib/new-id";/**- * Creates the channel on first send. The selected coworker stays in the URL so profile links and- * reloads preserve the pending recipient without creating an empty channel.+ * Creates the conversation on first send. One Bot in the To: field is an ordinary channel; two or+ * more are a group, answering in the order they were picked. The first Bot stays in the URL so+ * profile links and reloads preserve the pending recipient without creating an empty channel.*//** What `GET /api/agents/:id` answers for a Bot this person cannot see. */const AGENT_NOT_FOUND = "Agent not found.";@@ -42,7 +51,7 @@ export const Route = createFileRoute("/_authed/_app/channel/new")({function RouteComponent() {const { agent } = Route.useSearch();const navigate = Route.useNavigate();- const { startChosen, pending } = useStartChannel();+ const { startChosen, startGroup, pending } = useStartChannel();const { data: profiles, isError: rosterError } = useQuery(agentListQueryOptions(),);@@ -89,10 +98,19 @@ function RouteComponent() {? "This Bot isn't available to you. It may be unpublished, not shared with you, or not described yet.": "Coworker couldn't be loaded.": null;- const recipients: Recipient[] = chosen- ? [{ id: chosen.id, name: chosen.name }]- : [];- const skillCommands = useSkillCommands(chosen?.id ?? "");+ /** Bots picked in the To: field, in the order they will answer; the URL's Bot until one is picked. */+ const [picked, setPicked] = useState<AgentProfile[] | null>(null);+ const selected = picked ?? (chosen ? [chosen] : []);+ const anchor = useComboboxAnchor();+ const recipients: Recipient[] = selected.map((profile) => ({+ id: profile.id,+ name: profile.name,+ }));+ const group = startsGroup(recipients);+ // A group's first message goes to all of its Bots, so no one Bot's commands are offered.+ const skillCommands = useSkillCommands(+ group ? "" : (recipients[0]?.id ?? ""),+ );if (profiles === undefined && !rosterError) return null;@@ -105,33 +123,58 @@ function RouteComponent() {// Do not auto-open when the recipient came from the URL; the field is already answered.defaultOpen={!chosen && !loadError && !waitingForUrlAgent}autoHighlight+ multipleitems={profiles ?? []}isItemEqualToValue={(item: AgentProfile, value: AgentProfile) =>item.id === value.id}itemToStringLabel={(item: AgentProfile) => item.name}itemToStringValue={(item: AgentProfile) => item.id}- onValueChange={(next) => {- // Recipient changes are not separate navigation history entries.+ onValueChange={(next: AgentProfile[], details) => {+ const kept = toFieldChange(selected, next, details.reason);+ setPicked(kept);+ // The first Bot stays in the URL so a reload keeps the conversation's recipient; the+ // rest of a group lives in the page. Not a separate navigation history entry.void navigate({replace: true,- search: next ? { agent: next.id } : {},+ search: kept[0] ? { agent: kept[0].id } : {},});}}- value={chosen ?? null}+ value={selected}>- <ComboboxInput- // The popup opening is not enough on its own: typing filters through this input, so- // the caret starts here whenever the recipient question is still open. Same condition- // as `defaultOpen` — a recipient from the URL means the composer takes focus instead.- autoFocus={!chosen}- placeholder="Choose a coworker…"- // InputGroup owns focus rings via `has-[…:focus-visible]`; disable that wrapper ring here.- className="border-none w-full bg-transparent! text-sm has-[[data-slot=input-group-control]:focus-visible]:ring-0"- />+ <ComboboxChips+ ref={anchor}+ className="flex-1 border-none bg-transparent! focus-within:ring-0 dark:bg-transparent!"+ >+ {selected.map((profile) => (+ <ComboboxChip+ className="gap-1.5 pl-1"+ key={profile.id}+ removeLabel={`Remove ${profile.name}`}+ >+ <ChannelAvatar participantIds={[profile.id]} size={16} />+ {profile.name}+ </ComboboxChip>+ ))}+ <ComboboxChipsInput+ // The popup opening is not enough on its own: typing filters through this input, so+ // the caret starts here whenever the recipient question is still open. A recipient+ // from the URL means the composer takes focus instead.+ autoFocus={!chosen}+ placeholder={+ selected.length+ ? "Add another Bot for a group…"+ : "Choose a Bot…"+ }+ />+ </ComboboxChips>{/* Allow max-w to constrain the popup even though its anchor is full-width. */}- <ComboboxContent className="min-w-0 max-w-lg" sideOffset={12}>- <ComboboxEmpty>No agents found.</ComboboxEmpty>+ <ComboboxContent+ anchor={anchor}+ className="min-w-0 max-w-lg"+ sideOffset={12}+ >+ <ComboboxEmpty>No Bots found.</ComboboxEmpty><ComboboxList>{(item: AgentProfile) => (<ComboboxItem key={item.id} value={item} className="h-10">@@ -166,6 +209,23 @@ function RouteComponent() {onSubmit={async (draft) => {const recipient = recipients[0];if (!recipient || !canSend(recipients, draft.text)) return;+ if (group) {+ setError(null);+ try {+ await startGroup(+ recipients.map((entry) => entry.id),+ draft.text,+ );+ } catch (caught) {+ setError(+ caught instanceof Error+ ? caught.message+ : "Could not start the group.",+ );+ throw caught;+ }+ return;+ }setError(null);setSent(seedMessage(draft.text, newId()));diff --git a/app/src/routes/_authed/_app/group/$channelId.tsx b/app/src/routes/_authed/_app/group/$channelId.tsxindex c3726695..c8ce2fa0 100644--- a/app/src/routes/_authed/_app/group/$channelId.tsx+++ b/app/src/routes/_authed/_app/group/$channelId.tsx@@ -1,9 +1,11 @@import { useQuery } from "@tanstack/react-query";import { createFileRoute } from "@tanstack/react-router";-import { ChannelAvatar } from "@/components/channels/avatar";import { BotPausedBanner } from "@/components/bot-profile/pause-banner";+import { ChannelAvatar } from "@/components/channels/avatar";import { GroupChat } from "@/components/channels/group-chat";+import { GroupPeopleButton } from "@/components/channels/group-people";import { SidebarToggle } from "@/components/layout/sidebar-toggle";+import { useMarkOpenChannelRead } from "@/lib/channels/mark-read";import { channelQueryOptions } from "@/lib/channels/queries";/** A conversation with several Bots. The channel is an ordinary channel with more than one Bot. */@@ -14,6 +16,7 @@ export const Route = createFileRoute("/_authed/_app/group/$channelId")({function RouteComponent() {const { channelId } = Route.useParams();const channel = useQuery(channelQueryOptions(channelId));+ useMarkOpenChannelRead(channelId);return (<div className="flex h-full min-h-0 flex-col"><div className="sticky top-0 flex min-h-12 flex-row items-center gap-1.5 border-b border-border px-3 py-2">@@ -25,6 +28,7 @@ function RouteComponent() {<span className="min-w-0 truncate text-sm tracking-tight">{channel.data?.name ?? "Group"}</span>+ <GroupPeopleButton channelId={channelId} /></div>{(channel.data?.agentIds ?? []).map((agentId) => (<BotPausedBanner agentId={agentId} key={agentId} />diff --git a/app/src/routes/_authed/_app/group/new.tsx b/app/src/routes/_authed/_app/group/new.tsxindex 24700b08..480621f4 100644--- a/app/src/routes/_authed/_app/group/new.tsx+++ b/app/src/routes/_authed/_app/group/new.tsx@@ -1,109 +1,9 @@-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";-import { createFileRoute } from "@tanstack/react-router";-import { useState } from "react";-import { ChannelAvatar } from "@/components/channels/avatar";-import { SidebarToggle } from "@/components/layout/sidebar-toggle";-import { Button } from "@/components/ui/button";-import { Checkbox } from "@/components/ui/checkbox";-import { agentListQueryOptions } from "@/lib/agents/queries";-import { channelKeys } from "@/lib/channels/queries";-import { createGroupMutationOptions } from "@/lib/groups";+import { createFileRoute, redirect } from "@tanstack/react-router";+import { LEGACY_PAGES } from "@/lib/agents/legacy-routes";-/**- * Start a conversation with two or more Bots. It is an ordinary channel holding several Bots; the- * server refuses any Bot this person cannot see, exactly as it does for a one-Bot channel.- */+/** Groups are started from the new-conversation screen, with two or more Bots in To:. */export const Route = createFileRoute("/_authed/_app/group/new")({- component: RouteComponent,+ beforeLoad: () => {+ throw redirect({ to: LEGACY_PAGES["/group/new"], replace: true });+ },});--function RouteComponent() {- const navigate = Route.useNavigate();- const queryClient = useQueryClient();- const profiles = useQuery(agentListQueryOptions());- const create = useMutation(createGroupMutationOptions(queryClient));- const [chosen, setChosen] = useState<string[]>([]);-- const start = async () => {- const channel = await create.mutateAsync(chosen);- queryClient.setQueryData(channelKeys.detail(channel.id), channel);- await navigate({- to: "/group/$channelId",- params: { channelId: channel.id },- replace: true,- });- };-- return (- <div className="flex h-full flex-col">- <div className="sticky top-0 flex h-12 flex-row items-center gap-1.5 border-b border-border px-3">- <SidebarToggle />- <span className="text-sm tracking-tight">New group conversation</span>- </div>- <div className="mx-auto flex w-full max-w-xl flex-col gap-4 px-4 py-6">- <p className="text-sm text-muted-foreground">- Choose at least two Bots, in the order they should answer. Each sees- what the others said and can hand the conversation to another with- @Name.- </p>- {profiles.isError ? (- <p className="text-sm text-destructive" role="alert">- {profiles.error.message}- </p>- ) : null}- <div className="flex flex-col gap-1">- {(profiles.data ?? []).map((profile) => {- const checked = chosen.includes(profile.id);- return (- <label- className="flex h-10 cursor-pointer items-center gap-2 rounded-lg px-2 hover:bg-foreground/5"- htmlFor={`group-bot-${profile.id}`}- key={profile.id}- >- <Checkbox- aria-label={profile.name}- checked={checked}- id={`group-bot-${profile.id}`}- onCheckedChange={(next) =>- setChosen((current) =>- next- ? [...current, profile.id]- : current.filter((id) => id !== profile.id),- )- }- />- <ChannelAvatar participantIds={[profile.id]} size={24} />- <span className="text-sm">{profile.name}</span>- {checked ? (- <span className="text-xs text-muted-foreground">- answers {ordinal(chosen.indexOf(profile.id) + 1)}- </span>- ) : null}- <span className="truncate text-sm text-muted-foreground">- {profile.title}- </span>- </label>- );- })}- </div>- {create.error ? (- <p className="text-sm text-destructive" role="alert">- {create.error.message}- </p>- ) : null}- <div>- <Button- disabled={chosen.length < 2 || create.isPending}- onClick={() => void start().catch(() => {})}- >- Start group- </Button>- </div>- </div>- </div>- );-}--function ordinal(position: number) {- return ["first", "second", "third"][position - 1] ?? `#${position}`;-}diff --git a/app/src/routes/_authed/_app/memory.tsx b/app/src/routes/_authed/_app/memory.tsxindex e74d9c5e..289d188c 100644--- a/app/src/routes/_authed/_app/memory.tsx+++ b/app/src/routes/_authed/_app/memory.tsx@@ -1,490 +1,9 @@-import { useMutation, useQuery } from "@tanstack/react-query";-import { createFileRoute } from "@tanstack/react-router";-import { useId, useState } from "react";-import { PageShell } from "@/components/layout/page-shell";-import {- ProactiveResearchSettings,- SuggestionsInbox,-} from "@/components/suggestions/proactive-panel";-import { Button } from "@/components/ui/button";-import { Input } from "@/components/ui/input";-import { Textarea } from "@/components/ui/textarea";-import { agentListQueryOptions } from "@/lib/agents/queries";-import {- addMemorySource,- availableMemorySourcesQueryOptions,- createMemory,- deleteMemory,- type MemoryRecord,- memoriesQueryOptions,- memoryKeys,- memorySourceAction,- memorySourcesQueryOptions,- updateMemory,-} from "@/lib/memory";-import { queryClient } from "@/query-client";+import { createFileRoute, redirect } from "@tanstack/react-router";+import { LEGACY_PAGES } from "@/lib/agents/legacy-routes";++/** `/memory` left the sidebar. Memories are in Settings; sources and research are on each Bot's page. */export const Route = createFileRoute("/_authed/_app/memory")({- component: MemoryPage,+ beforeLoad: () => {+ throw redirect({ to: LEGACY_PAGES["/memory"], replace: true });+ },});-// min-w-0 and w-full, or a select as wide as its longest option pushes its grid column off the card.-const field = "grid min-w-0 gap-1 text-sm";-const select =- "h-9 w-full min-w-0 rounded-md border bg-background px-3 text-sm";-async function refresh() {- await queryClient.invalidateQueries({ queryKey: memoryKeys.all });-}-function MemoryPage() {- const memories = useQuery(memoriesQueryOptions());- const [content, setContent] = useState("");- const formId = useId();- const remember = useMutation({- mutationFn: createMemory,- onSuccess: async () => {- setContent("");- await refresh();- },- });- return (- <PageShell- title="Memory"- description="Review what your Bots remember, and choose which connected apps can contribute facts."- >- <div className="grid gap-6">- <SuggestionsInbox />- <form- className="grid gap-3 rounded-lg border p-4"- onSubmit={(event) => {- event.preventDefault();- remember.mutate(content);- }}- >- <h2 className="font-semibold">Remember a fact</h2>- <label className={field} htmlFor={formId}>- Something you want your Bots to know- </label>- <Textarea- id={formId}- required- maxLength={6000}- value={content}- onChange={(event) => setContent(event.target.value)}- placeholder="I prefer meetings in the morning."- />- <Button- type="submit"- disabled={remember.isPending || !content.trim()}- className="justify-self-start"- >- Remember- </Button>- {remember.error && (- <p role="alert" className="text-destructive">- {remember.error.message}- </p>- )}- </form>- <ProactiveResearchSettings />- <Sources />- <section className="grid gap-3">- <h2 className="font-semibold">Your memories</h2>- {memories.isPending ? (- <p>Loading memories…</p>- ) : memories.error ? (- <p role="alert" className="text-destructive">- {memories.error.message}- </p>- ) : memories.data?.length ? (- memories.data.map((memory) => (- <MemoryCard key={memory.id} memory={memory} />- ))- ) : (- <p className="text-muted-foreground">You have no memories yet.</p>- )}- </section>- </div>- </PageShell>- );-}-function MemoryCard({ memory }: { memory: MemoryRecord }) {- const [content, setContent] = useState(memory.content);- const id = useId();- const save = useMutation({- mutationFn: (input: {- content?: string;- enabled?: boolean;- reviewState?: "confirmed";- }) => updateMemory(memory.id, input),- onSuccess: refresh,- });- const forget = useMutation({- mutationFn: () => deleteMemory(memory.id),- onSuccess: refresh,- });- return (- <article className="grid gap-3 rounded-lg border p-4">- <div className="flex flex-wrap justify-between gap-2">- <label htmlFor={id} className="text-sm text-muted-foreground">- {memory.provenance}- </label>- <span className="text-xs text-muted-foreground">- {!memory.enabled- ? "Disabled"- : memory.reviewState === "unreviewed"- ? memory.formedBy === "bot"- ? "Formed by your Bot · awaiting review"- : "Imported · awaiting review"- : "Reviewed"}- </span>- </div>- {memory.formedBy === "bot" && (- <p className="text-xs text-muted-foreground">- From {memory.sourceApp ?? "a conversation"}- {memory.observedAt- ? `, read ${new Date(memory.observedAt).toLocaleString()}`- : ""}- {memory.sourceLink && (- <>- {" · "}- <a- className="underline"- href={memory.sourceLink}- target="_blank"- rel="noreferrer"- >- Open record- </a>- </>- )}- </p>- )}- <Textarea- id={id}- value={content}- maxLength={6000}- onChange={(event) => setContent(event.target.value)}- />- <div className="flex flex-wrap gap-2">- <Button- size="sm"- disabled={save.isPending || !content.trim()}- onClick={() => save.mutate({ content })}- >- Save- </Button>- {memory.reviewState === "unreviewed" && (- <Button- size="sm"- variant="outline"- onClick={() => save.mutate({ reviewState: "confirmed" })}- >- Confirm- </Button>- )}- <Button- size="sm"- variant="outline"- onClick={() => save.mutate({ enabled: !memory.enabled })}- >- {memory.enabled ? "Disable" : "Enable"}- </Button>- <Button- size="sm"- variant="outline"- disabled={forget.isPending}- onClick={() => forget.mutate()}- >- Forget- </Button>- </div>- {(save.error || forget.error) && (- <p role="alert" className="text-destructive">- {save.error?.message || forget.error?.message}- </p>- )}- </article>- );-}-function Sources() {- const sources = useQuery(memorySourcesQueryOptions());- const bots = useQuery(agentListQueryOptions());- const [agentId, setAgentId] = useState("");- const [toolRef, setToolRef] = useState("");- const [title, setTitle] = useState("");- const [args, setArgs] = useState<Record<string, string>>({});- const [error, setError] = useState("");- const id = useId();- const tools = useQuery(availableMemorySourcesQueryOptions(agentId));- const chosen = tools.data?.find((tool) => tool.ref === toolRef);- const properties = chosen?.inputSchema.properties;- const settings =- properties && typeof properties === "object" && !Array.isArray(properties)- ? Object.entries(properties).flatMap(([name, value]) =>- value && typeof value === "object" && !Array.isArray(value)- ? [- {- name,- schema: value as {- type?: string;- title?: string;- description?: string;- enum?: unknown[];- },- },- ]- : [],- )- : [];- const required = Array.isArray(chosen?.inputSchema.required)- ? chosen.inputSchema.required- : [];- const add = useMutation({- mutationFn: addMemorySource,- onSuccess: async () => {- setTitle("");- await refresh();- },- });- const action = useMutation({- mutationFn: ({- sourceId,- name,- }: {- sourceId: string;- name: "sync" | "remove" | "enable" | "disable";- }) => memorySourceAction(sourceId, name),- onSuccess: refresh,- });- return (- <section className="grid gap-3">- <h2 className="font-semibold">Connected app sources</h2>- <p className="text-sm text-muted-foreground">- Opt in to a read from an app your Bot can already access. Enabled- sources refresh every 15 minutes. Their facts are available to the- selected Bot.- </p>- <form- className="grid gap-3 rounded-lg border p-4"- onSubmit={(event) => {- event.preventDefault();- try {- const values: Record<string, unknown> = {};- for (const setting of settings) {- const value = args[setting.name];- if (!value) continue;- if (- setting.schema.type === "number" ||- setting.schema.type === "integer"- ) {- const number = Number(value);- if (!Number.isFinite(number))- throw new Error(`Enter a number for ${setting.name}.`);- values[setting.name] = number;- } else if (setting.schema.type === "boolean")- values[setting.name] = value === "true";- else if (setting.schema.type === "array")- values[setting.name] = value- .split("\n")- .map((entry) => entry.trim())- .filter(Boolean);- else if (setting.schema.type === "object")- throw new Error(- "Choose an action with simple search settings.",- );- else values[setting.name] = value;- }- setError("");- add.mutate({- agentId,- toolRef,- title,- args: values,- });- } catch (cause) {- setError(- cause instanceof Error- ? cause.message- : "Check the source settings.",- );- }- }}- >- <div className="grid gap-3 sm:grid-cols-2">- <label className={field}>- Bot- <select- required- className={select}- value={agentId}- onChange={(event) => {- setAgentId(event.target.value);- setToolRef("");- }}- >- <option value="">Choose a Bot</option>- {bots.data?.map((bot) => (- <option key={bot.id} value={bot.id}>- {bot.name}- </option>- ))}- </select>- </label>- <label className={field}>- Connected app action- <select- required- className={select}- value={toolRef}- onChange={(event) => {- setToolRef(event.target.value);- setArgs({});- }}- >- <option value="">Choose a read action</option>- {tools.data?.map((tool) => (- <option key={tool.ref} value={tool.ref}>- {tool.title}- </option>- ))}- </select>- </label>- </div>- {chosen && (- <p className="text-sm text-muted-foreground">{chosen.description}</p>- )}- <label className={field} htmlFor={`${id}-name`}>- Source name- <Input- id={`${id}-name`}- required- maxLength={160}- value={title}- onChange={(event) => setTitle(event.target.value)}- placeholder="My project documents"- />- </label>- {settings.map(({ name, schema }) => (- <label key={name} className={field} htmlFor={`${id}-${name}`}>- {schema.title || name.replaceAll("_", " ")}- {required.includes(name) ? " *" : ""}- {schema.type === "boolean" || schema.enum ? (- <select- id={`${id}-${name}`}- className={select}- value={args[name] ?? ""}- required={required.includes(name)}- onChange={(event) =>- setArgs({ ...args, [name]: event.target.value })- }- >- <option value="">Choose a value</option>- {(schema.enum ?? ["true", "false"]).map((value) => (- <option key={String(value)} value={String(value)}>- {String(value)}- </option>- ))}- </select>- ) : (- <Input- id={`${id}-${name}`}- type={- schema.type === "number" || schema.type === "integer"- ? "number"- : "text"- }- required={required.includes(name)}- value={args[name] ?? ""}- onChange={(event) =>- setArgs({ ...args, [name]: event.target.value })- }- />- )}- {schema.description && (- <span className="text-xs text-muted-foreground">- {schema.description}- </span>- )}- </label>- ))}- <Button- type="submit"- className="justify-self-start"- disabled={add.isPending || !toolRef}- >- {add.isPending ? "Reading source…" : "Add and sync source"}- </Button>- {(error || add.error || tools.error) && (- <p role="alert" className="text-destructive">- {error || add.error?.message || tools.error?.message}- </p>- )}- </form>- {sources.error && (- <p role="alert" className="text-destructive">- {sources.error.message}- </p>- )}- {sources.data?.map((source) => (- <article key={source.id} className="grid gap-2 rounded-lg border p-4">- <div className="flex justify-between">- <strong>{source.title}</strong>- <span className="text-sm text-muted-foreground">- {source.enabled- ? source.syncStatus === "succeeded"- ? "Up to date"- : source.syncStatus- : "Disabled"}- </span>- </div>- {source.lastSyncAt && (- <p className="text-xs text-muted-foreground">- Last read {new Date(source.lastSyncAt).toLocaleString()}- </p>- )}- {source.syncError && (- <p role="alert" className="text-destructive">- {source.syncError}- </p>- )}- <div className="flex flex-wrap gap-2">- <Button- size="sm"- variant="outline"- disabled={!source.enabled || action.isPending}- onClick={() =>- action.mutate({ sourceId: source.id, name: "sync" })- }- >- Sync now- </Button>- <Button- size="sm"- variant="outline"- onClick={() =>- action.mutate({- sourceId: source.id,- name: source.enabled ? "disable" : "enable",- })- }- >- {source.enabled ? "Disable" : "Enable"}- </Button>- <Button- size="sm"- variant="outline"- onClick={() =>- action.mutate({ sourceId: source.id, name: "remove" })- }- >- Remove- </Button>- </div>- </article>- ))}- {action.error && (- <p role="alert" className="text-destructive">- {action.error.message}- </p>- )}- </section>- );-}diff --git a/app/src/routes/_authed/_app/reachability.tsx b/app/src/routes/_authed/_app/reachability.tsxindex 74e267d3..6da10e7d 100644--- a/app/src/routes/_authed/_app/reachability.tsx+++ b/app/src/routes/_authed/_app/reachability.tsx@@ -1,333 +1,9 @@-import { useInfiniteQuery, useMutation, useQuery } from "@tanstack/react-query";-import { createFileRoute } from "@tanstack/react-router";-import { useEffect, useState } from "react";-import { PageShell } from "@/components/layout/page-shell";-import { Button } from "@/components/ui/button";-import { Input } from "@/components/ui/input";-import { agentListQueryOptions } from "@/lib/agents/queries";-import { conversationLabel } from "@/lib/channels/label";-import { channelListQueryOptions } from "@/lib/channels/queries";-import {- confirmSms,- deliveryKey,- deliveryQueryOptions,- removeDeliveryBinding,- removePushDevice,- startChatLink,- startSms,-} from "@/lib/delivery";-import { queryClient } from "@/query-client";--/**- * The phone verification waiting for its code, kept for the tab.- *- * Only the challenge id lives in the page, and the text with the code arrives on the person's- * phone a moment after they may have looked away: leaving and coming back used to drop the box to- * type it into, with no way to confirm the code they had just been sent.- */-const PENDING_SMS = "openbot.reachability.pendingSms";-function readPending(): string {- try {- return sessionStorage.getItem(PENDING_SMS) ?? "";- } catch {- return "";- }-}-function writePending(id: string) {- try {- if (id) sessionStorage.setItem(PENDING_SMS, id);- else sessionStorage.removeItem(PENDING_SMS);- } catch {- /* A browser that keeps nothing still confirms within the visit. */- }-}+import { createFileRoute, redirect } from "@tanstack/react-router";+import { LEGACY_PAGES } from "@/lib/agents/legacy-routes";+/** `/reachability` left the sidebar. Linking is on each Bot's page; devices and deliveries are in Settings. */export const Route = createFileRoute("/_authed/_app/reachability")({- component: ReachabilityPage,+ beforeLoad: () => {+ throw redirect({ to: LEGACY_PAGES["/reachability"], replace: true });+ },});-function ReachabilityPage() {- const reach = useQuery(deliveryQueryOptions());- const channels = useInfiniteQuery(channelListQueryOptions());- const bots = useQuery(agentListQueryOptions());- // People read Bots by name; the id is what the list used to show.- const botName = (id: string) =>- bots.data?.find((bot) => bot.id === id)?.name ?? id;- const [channelId, setChannelId] = useState("");- const [agentId, setAgentId] = useState("");- const [phone, setPhone] = useState("");- const [copied, setCopied] = useState(false);- const [challengeId, setChallengeId] = useState(readPending);- useEffect(() => writePending(challengeId), [challengeId]);- const [code, setCode] = useState("");- const refresh = () =>- queryClient.invalidateQueries({ queryKey: deliveryKey });- const link = useMutation({- mutationFn: (platform: "slack" | "teams") =>- startChatLink({ channelId, agentId, platform }),- onSuccess: () => setCopied(false),- });- const sms = useMutation({- mutationFn: () => startSms({ channelId, agentId, phone }),- onSuccess: setChallengeId,- });- const confirm = useMutation({- mutationFn: () => confirmSms(challengeId, code),- onSuccess: async () => {- setChallengeId("");- setCode("");- await refresh();- },- });- const remove = useMutation({- mutationFn: removeDeliveryBinding,- onSuccess: refresh,- });- const deviceRemove = useMutation({- mutationFn: removePushDevice,- onSuccess: refresh,- });- const selected = channels.data?.find((channel) => channel.id === channelId);- const error =- reach.error ??- channels.error ??- link.error ??- sms.error ??- confirm.error ??- remove.error ??- deviceRemove.error;- return (- <PageShell- title="Reachability"- description="Continue a conversation in Slack, Microsoft Teams, by text message, or on your phone. Questions and approval requests reach the same person who owns the conversation."- >- <div className="grid gap-5">- {error && (- <p role="alert" className="text-destructive">- {error.message}- </p>- )}- <div className="grid gap-3 rounded-lg border p-4">- <h2 className="font-semibold">Connect a conversation</h2>- <label className="grid gap-1 text-sm">- Conversation- <select- className="h-9 rounded border bg-background px-3"- value={channelId}- onChange={(event) => {- setChannelId(event.target.value);- setAgentId("");- }}- >- <option value="">Choose a conversation</option>- {channels.data- ?.filter((channel) => channel.active)- .map((channel) => (- <option key={channel.id} value={channel.id}>- {conversationLabel(channel)}- </option>- ))}- </select>- </label>- <label className="grid gap-1 text-sm">- Bot- <select- className="h-9 rounded border bg-background px-3"- value={agentId}- onChange={(event) => setAgentId(event.target.value)}- >- <option value="">Choose a Bot</option>- {selected?.agentIds.map((id) => (- <option key={id} value={id}>- {botName(id)}- </option>- ))}- </select>- </label>- {channels.hasNextPage && (- <Button variant="outline" onClick={() => channels.fetchNextPage()}>- Load more conversations- </Button>- )}- <div className="flex flex-wrap gap-2">- <Button- disabled={- !agentId || !reach.data?.available.slack || link.isPending- }- onClick={() => link.mutate("slack")}- >- Link Slack- </Button>- <Button- variant="outline"- disabled={- !agentId || !reach.data?.available.teams || link.isPending- }- onClick={() => link.mutate("teams")}- >- Link Microsoft Teams- </Button>- </div>- {link.data && (- <div className="grid gap-2 rounded border bg-muted/40 p-3 text-sm">- <p>- Send this message to the OpenBot app in{" "}- {link.data.platform === "teams" ? "Microsoft Teams" : "Slack"}{" "}- within {link.data.expiresInMinutes} minutes. It links that- account to this conversation and Bot.- </p>- <div className="flex items-center gap-2">- <code className="min-w-0 flex-1 break-all rounded bg-background px-2 py-1">- {link.data.command}- </code>- <Button- size="sm"- variant="outline"- onClick={async () => {- await navigator.clipboard.writeText(- link.data?.command ?? "",- );- setCopied(true);- }}- >- {copied ? "Copied" : "Copy"}- </Button>- </div>- </div>- )}- <p className="text-sm text-muted-foreground">- In a channel other people can read, the Bot answers you in a direct- message instead.- </p>- {reach.data && !reach.data.available.slack && (- <p className="text-sm text-muted-foreground">- An administrator needs to pair OpenBot with OpenTag before Slack- or Teams can be linked.- </p>- )}- <form- className="grid gap-3 border-t pt-3"- onSubmit={(event) => {- event.preventDefault();- sms.mutate();- }}- >- <label htmlFor="delivery-phone" className="grid gap-1 text-sm">- Phone number- <Input- id="delivery-phone"- type="tel"- value={phone}- onChange={(event) => setPhone(event.target.value)}- placeholder="+15551234567"- required- pattern="\+[1-9][0-9]{7,14}"- />- </label>- <Button- type="submit"- disabled={!agentId || !reach.data?.available.sms || sms.isPending}- >- Send verification code- </Button>- </form>- {challengeId && (- <form- className="flex gap-2"- onSubmit={(event) => {- event.preventDefault();- confirm.mutate();- }}- >- <Input- aria-label="Verification code"- autoComplete="one-time-code"- value={code}- onChange={(event) => setCode(event.target.value)}- required- />- <Button type="submit" disabled={confirm.isPending}>- Confirm phone- </Button>- </form>- )}- </div>- <section className="grid gap-3 rounded-lg border p-4">- <h2 className="font-semibold">Connected destinations</h2>- {reach.isPending ? (- <p>Loading connections…</p>- ) : (- reach.data?.bindings- .filter((binding) => binding.enabled)- .map((binding) => (- <div- key={binding.id}- className="flex items-center justify-between gap-2"- >- <p className="text-sm">- {binding.transport === "slack"- ? "Slack"- : binding.transport === "teams"- ? "Microsoft Teams"- : binding.optedOutAt- ? `${binding.address} (replied STOP; text START to resume)`- : binding.address}{" "}- · {botName(binding.agentId)}- </p>- <Button- variant="outline"- size="sm"- disabled={remove.isPending}- onClick={() => remove.mutate(binding.id)}- >- Disconnect- </Button>- </div>- ))- )}- {reach.data?.bindings.every((binding) => !binding.enabled) && (- <p className="text-sm text-muted-foreground">- No destinations connected.- </p>- )}- </section>- <section className="grid gap-3 rounded-lg border p-4">- <h2 className="font-semibold">Native devices</h2>- <p className="text-sm text-muted-foreground">- Sign in to the OpenBot native app and enable notifications to- register your device.- </p>- {reach.data?.devices.map((device) => (- <div key={device.id} className="flex items-center justify-between">- <p>{device.platform}</p>- <Button- variant="outline"- size="sm"- disabled={deviceRemove.isPending}- onClick={() => deviceRemove.mutate(device.id)}- >- Remove device- </Button>- </div>- ))}- </section>- <section className="grid gap-2 rounded-lg border p-4">- <h2 className="font-semibold">Recent deliveries</h2>- {reach.data?.deliveries.map((delivery) => (- <div key={delivery.id} className="border-t pt-2 text-sm">- <p>- {delivery.transport} · {delivery.kind} · {delivery.state} ·{" "}- {new Date(delivery.createdAt).toLocaleString()}- </p>- {delivery.error && (- <p className="text-destructive">{delivery.error}</p>- )}- </div>- ))}- {reach.data?.deliveries.length === 0 && (- <p className="text-sm text-muted-foreground">No deliveries yet.</p>- )}- </section>- </div>- </PageShell>- );-}diff --git a/app/src/routes/_authed/_app/responsibilities.tsx b/app/src/routes/_authed/_app/responsibilities.tsxindex 4c27d444..0a5ed0ae 100644--- a/app/src/routes/_authed/_app/responsibilities.tsx+++ b/app/src/routes/_authed/_app/responsibilities.tsx@@ -1,1209 +1,9 @@-import {- useInfiniteQuery,- useMutation,- useQuery,- useQueryClient,-} from "@tanstack/react-query";-import { createFileRoute, Link } from "@tanstack/react-router";-import { useId, useState } from "react";-import { Streamdown } from "streamdown";-import { PageShell } from "@/components/layout/page-shell";-import { SharedAppNotice } from "@/components/plugins/shared-app-notice";-import { Button } from "@/components/ui/button";-import { Input } from "@/components/ui/input";-import { Textarea } from "@/components/ui/textarea";-import { agentListQueryOptions } from "@/lib/agents/queries";-import { conversationLabel } from "@/lib/channels/label";-import { channelListQueryOptions } from "@/lib/channels/queries";-import { markdownComponents } from "@/lib/markdown";-import { sharedUseKeys } from "@/lib/plugins/shared-use";-import {- createGithubBinding,- createResponsibility,- createTrigger,- githubBindingsQueryOptions,- type ResponsibilityRecord,- removeGithubBinding,- removeTrigger,- responsibilitiesQueryOptions,- responsibilityAction,- responsibilityKeys,- responsibilityRunsQueryOptions,- revealTriggerSecret,- setTriggerEnabled,- setTriggerSecret,- type TriggerConfig,- type TriggerKind,- type TriggerRecord,- triggersQueryOptions,- updateResponsibility,-} from "@/lib/responsibilities";-import { queryClient } from "@/query-client";+import { createFileRoute, redirect } from "@tanstack/react-router";+import { LEGACY_PAGES } from "@/lib/agents/legacy-routes";+/** `/responsibilities` left the sidebar. Each Bot's responsibilities are on its own page. */export const Route = createFileRoute("/_authed/_app/responsibilities")({- component: ResponsibilitiesPage,+ beforeLoad: () => {+ throw redirect({ to: LEGACY_PAGES["/responsibilities"], replace: true });+ },});-const fieldClass = "grid gap-1 text-sm";-const selectClass = "h-9 rounded-md border bg-background px-3 text-sm";-async function refresh() {- await queryClient.invalidateQueries({ queryKey: responsibilityKeys.all });-}--function ResponsibilitiesPage() {- const goals = useQuery(responsibilitiesQueryOptions());- return (- <PageShell- title="Responsibilities"- description="Give a Bot a lasting goal, follow its progress, and decide when it should work."- >- <div className="grid gap-6">- <NewResponsibility />- {goals.isPending ? (- <p>Loading responsibilities…</p>- ) : goals.error ? (- <p role="alert" className="text-destructive">- {goals.error.message}- </p>- ) : goals.data?.length ? (- goals.data.map((goal) => <GoalCard key={goal.id} goal={goal} />)- ) : (- <p className="text-muted-foreground">- You have no responsibilities yet.- </p>- )}- <GithubSources />- </div>- </PageShell>- );-}--function NewResponsibility() {- const formId = useId();- const bots = useQuery(agentListQueryOptions());- const channels = useInfiniteQuery(channelListQueryOptions());- const [channelId, setChannelId] = useState("");- const [agentId, setAgentId] = useState("");- const [title, setTitle] = useState("");- const [instruction, setInstruction] = useState("");- const [successCriteria, setSuccessCriteria] = useState("");- const [source, setSource] = useState<- "none" | ResponsibilityRecord["subscriptions"][number]["source"]- >("none");- const [eventType, setEventType] = useState("");- const selectedChannel = channels.data?.find(- (channel) => channel.id === channelId,- );- const availableBots =- bots.data?.filter((bot) => selectedChannel?.agentIds.includes(bot.id)) ??- [];- const create = useMutation({- mutationFn: createResponsibility,- onSuccess: async () => {- setTitle("");- setInstruction("");- setSuccessCriteria("");- await refresh();- },- });- return (- <form- className="grid gap-3 rounded-lg border p-4"- onSubmit={(event) => {- event.preventDefault();- create.mutate({- channelId,- agentId,- title,- instruction,- successCriteria,- subscriptions: source === "none" ? [] : [{ source, eventType }],- });- }}- >- <h2 className="font-semibold">New responsibility</h2>- <div className="grid gap-3 sm:grid-cols-2">- <label className={fieldClass}>- Conversation- <select- className={selectClass}- required- value={channelId}- onChange={(event) => {- setChannelId(event.target.value);- setAgentId("");- }}- >- <option value="">Choose a conversation</option>- {channels.data- ?.filter((channel) => channel.active)- .map((channel) => (- <option key={channel.id} value={channel.id}>- {conversationLabel(channel)}- </option>- ))}- </select>- </label>- <label className={fieldClass}>- Bot- <select- className={selectClass}- required- value={agentId}- onChange={(event) => setAgentId(event.target.value)}- >- <option value="">Choose a Bot</option>- {availableBots.map((bot) => (- <option key={bot.id} value={bot.id}>- {bot.name}- </option>- ))}- </select>- </label>- </div>- {channels.hasNextPage && (- <Button- type="button"- variant="outline"- onClick={() => channels.fetchNextPage()}- >- Load more conversations- </Button>- )}- {(channels.error || bots.error) && (- <p role="alert" className="text-destructive">- {channels.error?.message ?? bots.error?.message}- </p>- )}- <label className={fieldClass} htmlFor={`${formId}-title`}>- Title- <Input- id={`${formId}-title`}- required- maxLength={160}- value={title}- onChange={(event) => setTitle(event.target.value)}- placeholder="Keep the customer report up to date"- />- </label>- <label className={fieldClass} htmlFor={`${formId}-instruction`}>- Instruction- <Textarea- id={`${formId}-instruction`}- required- maxLength={6000}- value={instruction}- onChange={(event) => setInstruction(event.target.value)}- />- </label>- <label className={fieldClass} htmlFor={`${formId}-criteria`}>- Success criteria- <Textarea- id={`${formId}-criteria`}- required- maxLength={3000}- value={successCriteria}- onChange={(event) => setSuccessCriteria(event.target.value)}- placeholder="The report contains the current quarter's graph and a source link."- />- </label>- <div className="grid gap-3 sm:grid-cols-2">- <label className={fieldClass}>- Event source- <select- className={selectClass}- value={source}- onChange={(event) => {- const value = event.target.value;- if (- value === "none" ||- value === "github" ||- value === "slack" ||- value === "connector" ||- value === "schedule" ||- value === "manual"- )- setSource(value);- }}- >- <option value="none">Run when asked</option>- <option value="github">GitHub</option>- <option value="slack">Slack</option>- <option value="connector">Connected app</option>- <option value="schedule">Schedule</option>- </select>- </label>- {source !== "none" && (- <label className={fieldClass} htmlFor={`${formId}-event`}>- Event type- <Input- id={`${formId}-event`}- required- maxLength={128}- value={eventType}- onChange={(event) => setEventType(event.target.value)}- placeholder={source === "github" ? "issues.opened" : "Event type"}- />- </label>- )}- </div>- {create.error && (- <p role="alert" className="text-destructive">- {create.error.message}- </p>- )}- <Button disabled={create.isPending} type="submit">- {create.isPending ? "Creating…" : "Create responsibility"}- </Button>- </form>- );-}--function GoalCard({ goal }: { goal: ResponsibilityRecord }) {- const [editing, setEditing] = useState(false);- const [showRuns, setShowRuns] = useState(false);- const [title, setTitle] = useState(goal.title);- const [instruction, setInstruction] = useState(goal.instruction);- const [successCriteria, setSuccessCriteria] = useState(goal.successCriteria);- const action = useMutation({- mutationFn: (value: "pause" | "resume" | "complete" | "run") =>- responsibilityAction(goal.id, value),- onSuccess: refresh,- });- const edit = useMutation({- mutationFn: () =>- updateResponsibility(goal.id, { title, instruction, successCriteria }),- onSuccess: async () => {- setEditing(false);- await refresh();- },- });- const runs = useQuery({- ...responsibilityRunsQueryOptions(goal.id),- enabled: showRuns,- });- return (- <article className="grid gap-3 rounded-lg border p-4">- <div className="flex flex-wrap items-center justify-between gap-2">- <h2 className="font-semibold">{goal.title}</h2>- <span className="rounded bg-muted px-2 py-1 text-xs capitalize">- {goal.status}- </span>- </div>- {editing ? (- <form- className="grid gap-3"- onSubmit={(event) => {- event.preventDefault();- edit.mutate();- }}- >- <label className={fieldClass} htmlFor={`${goal.id}-title`}>- Title- <Input- id={`${goal.id}-title`}- value={title}- onChange={(event) => setTitle(event.target.value)}- required- maxLength={160}- />- </label>- <label className={fieldClass} htmlFor={`${goal.id}-instruction`}>- Instruction- <Textarea- id={`${goal.id}-instruction`}- value={instruction}- onChange={(event) => setInstruction(event.target.value)}- required- maxLength={6000}- />- </label>- <label className={fieldClass} htmlFor={`${goal.id}-criteria`}>- Success criteria- <Textarea- id={`${goal.id}-criteria`}- value={successCriteria}- onChange={(event) => setSuccessCriteria(event.target.value)}- required- maxLength={3000}- />- </label>- <div className="flex gap-2">- <Button type="submit" disabled={edit.isPending}>- Save- </Button>- <Button- variant="outline"- type="button"- onClick={() => setEditing(false)}- >- Cancel- </Button>- </div>- </form>- ) : (- <>- <p className="whitespace-pre-wrap text-sm">{goal.instruction}</p>- <p className="text-sm text-muted-foreground">- Success: {goal.successCriteria}- </p>- </>- )}- {goal.progress && (- <div className="text-sm">- <span className="font-medium">Progress:</span>- <RunMarkdown>{goal.progress}</RunMarkdown>- </div>- )}- {goal.lastResult && (- <div className="rounded bg-muted p-3 text-sm">- <RunMarkdown>{goal.lastResult}</RunMarkdown>- </div>- )}- {goal.subscriptions.length > 0 && (- <p className="text-xs text-muted-foreground">- Events:{" "}- {goal.subscriptions- .map(- (subscription) =>- `${subscription.source} · ${subscription.eventType}`,- )- .join(", ")}- </p>- )}- <div className="flex flex-wrap gap-2">- <Button- variant="outline"- size="sm"- onClick={() => setEditing(!editing)}- >- Edit- </Button>- {goal.status === "active" && (- <>- <Button- size="sm"- disabled={action.isPending}- onClick={() => {- setShowRuns(true);- action.mutate("run");- }}- title="Runs it for real, now: the Bot does the work and can post and act."- >- Run now (real run)- </Button>- <Button- variant="outline"- size="sm"- disabled={action.isPending}- onClick={() => action.mutate("pause")}- >- Pause- </Button>- </>- )}- {goal.status === "paused" && (- <Button- size="sm"- disabled={action.isPending}- onClick={() => action.mutate("resume")}- >- Resume- </Button>- )}- {goal.status !== "completed" && (- <Button- variant="outline"- size="sm"- disabled={action.isPending}- onClick={() => action.mutate("complete")}- >- Complete- </Button>- )}- <Button- variant="ghost"- size="sm"- onClick={() => setShowRuns(!showRuns)}- >- {showRuns ? "Hide runs" : "View runs"}- </Button>- <Link- to="/channel/$channelId"- params={{ channelId: goal.channelId }}- className="self-center text-sm underline"- >- Open conversation- </Link>- </div>- {(action.error || edit.error) && (- <p role="alert" className="text-destructive">- {action.error?.message ?? edit.error?.message}- </p>- )}- <Triggers goal={goal} />- {showRuns && (- <div className="grid gap-2 border-t pt-3">- {runs.isPending ? (- <p>Loading runs…</p>- ) : runs.error ? (- <p role="alert">{runs.error.message}</p>- ) : runs.data?.length ? (- runs.data.map((run) => (- <div key={run.id} className="text-sm">- <p>- <span className={runStatusClass(run.status)}>- {RUN_LABEL[run.status]}- </span>{" "}- · {new Date(run.createdAt).toLocaleString()} ·{" "}- <Link- to="/channel/$channelId"- params={{ channelId: goal.channelId }}- className="underline"- >- Open thread- </Link>- </p>- {run.waiting && (- <p>- Waiting for {run.waiting.kind}. Respond through your- approval inbox or conversation.- </p>- )}- {run.error && (- <p className="text-muted-foreground">{run.error}</p>- )}- {run.replyText && <RunMarkdown>{run.replyText}</RunMarkdown>}- </div>- ))- ) : (- <p>No runs yet.</p>- )}- </div>- )}- </article>- );-}--/**- * A Bot's own words, drawn the way the conversation draws them.- *- * Progress, the last result and each run's reply are the Bot's markdown, and shown as plain text- * they read as literal asterisks and backticks. Same renderer and components as the transcript, kept- * to the row's size: no heading scale, tight paragraph and list spacing.- */-function RunMarkdown({ children }: { children: string }) {- return (- <Streamdown- className="min-w-0 text-sm [&_h1]:text-sm [&_h2]:text-sm [&_h3]:text-sm [&_li]:my-0 [&_ol]:my-1 [&_p]:my-1 [&_ul]:my-1 [&>*:first-child]:mt-0 [&>*:last-child]:mb-0"- components={markdownComponents}- mode="static"- >- {children}- </Streamdown>- );-}--function GithubSources() {- const formId = useId();- const bindings = useQuery(githubBindingsQueryOptions());- const [repository, setRepository] = useState("");- const [secret, setSecret] = useState("");- const create = useMutation({- mutationFn: () => createGithubBinding(repository, secret),- onSuccess: async () => {- setSecret("");- setRepository("");- await refresh();- },- });- const remove = useMutation({- mutationFn: removeGithubBinding,- onSuccess: refresh,- });- return (- <section className="grid gap-3 rounded-lg border p-4">- <h2 className="font-semibold">GitHub event sources</h2>- <p className="text-sm text-muted-foreground">- Register a repository, then add its webhook in GitHub using the endpoint- below and the same secret. Subscribe a responsibility to an event such- as issues.opened.- </p>- <form- className="grid gap-3 sm:grid-cols-3"- onSubmit={(event) => {- event.preventDefault();- create.mutate();- }}- >- <label className={fieldClass} htmlFor={`${formId}-repository`}>- Repository- <Input- id={`${formId}-repository`}- value={repository}- onChange={(event) => setRepository(event.target.value)}- placeholder="owner/repository"- required- />- </label>- <label className={fieldClass} htmlFor={`${formId}-secret`}>- Webhook secret- <Input- id={`${formId}-secret`}- type="password"- autoComplete="new-password"- value={secret}- onChange={(event) => setSecret(event.target.value)}- required- />- </label>- <Button type="submit" className="self-end" disabled={create.isPending}>- Connect events- </Button>- </form>- {(bindings.error || create.error || remove.error) && (- <p role="alert" className="text-destructive">- {bindings.error?.message ??- create.error?.message ??- remove.error?.message}- </p>- )}- {bindings.data?.map((binding) => (- <div- key={binding.id}- className="flex flex-wrap items-center justify-between gap-2 border-t pt-3"- >- <div>- <p className="text-sm">{binding.repository}</p>- <code className="break-all text-xs">- {window.location.origin}/api/events/github/{binding.id}- </code>- </div>- <Button- size="sm"- variant="outline"- disabled={remove.isPending}- onClick={() => remove.mutate(binding.id)}- >- Disconnect- </Button>- </div>- ))}- </section>- );-}--const RUN_LABEL: Record<string, string> = {- queued: "Queued",- running: "Running",- waiting: "Waiting for you",- succeeded: "Succeeded",- failed: "Failed",- skipped: "Skipped",-};-function runStatusClass(status: string) {- return status === "failed"- ? "text-destructive"- : status === "succeeded"- ? "text-emerald-600 dark:text-emerald-500"- : "text-muted-foreground";-}--const KIND_LABEL: Record<TriggerKind, string> = {- webhook: "Webhook",- github: "GitHub",- linear: "Linear",- sentry: "Sentry",- pagerduty: "PagerDuty",- email: "Email",- slack: "Slack",-};-const KIND_HELP: Record<TriggerKind, string> = {- webhook:- "POST JSON to the URL with the authorization header (or Standard Webhooks signature headers). 200 means accepted and queued, not finished.",- github:- "In the repository's Settings → Webhooks, set the payload URL to this URL, content type application/json, and the secret to the key.",- linear:- "In Linear, Settings → API → Webhooks: set the URL, then paste the signing secret Linear shows here.",- sentry:- "In a Sentry internal integration, set the webhook URL, then paste the integration's client secret here.",- pagerduty:- "In PagerDuty, Integrations → Generic Webhooks (v3): set the URL, then paste the secret shown on creation here.",- email: "Send or forward mail to this address to start a run.",- slack:- "Fires from Slack events delivered through this Bot's Slack pairing. Messages from before the trigger existed are ignored.",-};-const VENDOR_SECRET: ReadonlySet<TriggerKind> = new Set([- "linear",- "sentry",- "pagerduty",-]);-const list = (value: string) =>- value- .split(",")- .map((item) => item.trim())- .filter(Boolean);--function CopyButton({ value, label }: { value: string; label: string }) {- const [copied, setCopied] = useState(false);- return (- <Button- size="sm"- type="button"- variant="outline"- onClick={async () => {- await navigator.clipboard.writeText(value);- setCopied(true);- setTimeout(() => setCopied(false), 1500);- }}- >- {copied ? "Copied" : label}- </Button>- );-}--function describeFilter(config: TriggerConfig) {- if (config.kind === "slack") {- const where = config.channels.length- ? `in ${config.channels.join(", ")}`- : "in every channel the Bot is in";- const what =- config.mode === "mention"- ? "when the Bot is mentioned"- : config.mode === "message"- ? "on any message"- : config.mode === "phrase"- ? `on messages containing ${config.phrases.map((phrase) => `"${phrase}"`).join(" or ")}`- : `on reactions${config.reactions.length ? ` :${config.reactions.join(": :")}:` : ""}`;- return `${what} ${where} (workspace ${config.teamId})`;- }- const parts = [- config.filter.eventTypes.length- ? `events ${config.filter.eventTypes.join(", ")}`- : "every event",- ];- if (config.filter.field)- parts.push(- `where ${config.filter.field.path} = ${config.filter.field.equals}`,- );- if (config.kind === "github" && config.repository)- parts.push(`from ${config.repository}`);- if (config.kind === "email" && config.allowedSenders.length)- parts.push(`from ${config.allowedSenders.join(", ")} (authenticated)`);- return parts.join(" ");-}--function Triggers({ goal }: { goal: ResponsibilityRecord }) {- const triggers = useQuery(triggersQueryOptions(goal.id));- const [adding, setAdding] = useState(false);- const [freshSecret, setFreshSecret] = useState<{- id: string;- secret: string;- } | null>(null);- const reload = () =>- queryClient.invalidateQueries({- queryKey: responsibilityKeys.triggers(goal.id),- });- return (- <section className="grid gap-2 border-t pt-3">- <div className="flex flex-wrap items-center justify-between gap-2">- <h3 className="font-medium text-sm">Triggers</h3>- <Button- size="sm"- variant="outline"- type="button"- onClick={() => setAdding(!adding)}- >- {adding ? "Cancel" : "Add trigger"}- </Button>- </div>- {goal.status !== "active" && (- <p className="text-muted-foreground text-xs">- This responsibility is {goal.status}, so its triggers are acknowledged- but never run it.- </p>- )}- {adding && (- <NewTrigger- goalId={goal.id}- botId={goal.agentId}- onCreated={async (created) => {- setAdding(false);- if (created.secret)- setFreshSecret({- id: created.trigger.id,- secret: created.secret,- });- await reload();- }}- />- )}- {triggers.error && (- <p role="alert" className="text-destructive text-sm">- {triggers.error.message}- </p>- )}- {triggers.data?.length === 0 && !adding && (- <p className="text-muted-foreground text-xs">- No triggers. It runs when you press Run now, or on the event- subscriptions above.- </p>- )}- {triggers.data?.map((trigger) => (- <TriggerRow- key={trigger.id}- trigger={trigger}- freshSecret={- freshSecret?.id === trigger.id ? freshSecret.secret : null- }- onChanged={async (secret) => {- if (secret) setFreshSecret({ id: trigger.id, secret });- await reload();- }}- />- ))}- </section>- );-}--function TriggerRow({- trigger,- freshSecret,- onChanged,-}: {- trigger: TriggerRecord;- freshSecret: string | null;- onChanged: (secret: string | null) => Promise<void>;-}) {- const [secret, setSecret] = useState<string | null>(freshSecret);- const [pasted, setPasted] = useState("");- const [confirmRemove, setConfirmRemove] = useState(false);- const shown = freshSecret ?? secret;- const reveal = useMutation({- mutationFn: () => revealTriggerSecret(trigger.id),- onSuccess: setSecret,- });- const rotate = useMutation({- mutationFn: () =>- setTriggerSecret(- trigger.id,- VENDOR_SECRET.has(trigger.kind) ? pasted : undefined,- ),- onSuccess: async (result) => {- setPasted("");- setSecret(result.secret);- await onChanged(result.secret);- },- });- const remove = useMutation({- mutationFn: () => removeTrigger(trigger.id),- onSuccess: () => onChanged(null),- });- const toggle = useMutation({- mutationFn: () => setTriggerEnabled(trigger.id, !trigger.enabled),- onSuccess: () => onChanged(null),- });- const url = trigger.path ? `${window.location.origin}${trigger.path}` : null;- const generated = trigger.kind === "webhook" || trigger.kind === "github";- return (- <div className="grid gap-2 rounded-md bg-muted/50 p-3 text-sm">- <div className="flex flex-wrap items-center justify-between gap-2">- <p>- <span className="font-medium">{KIND_LABEL[trigger.kind]}</span>{" "}- <span className="text-muted-foreground">- {describeFilter(trigger.config)}- </span>- {!trigger.enabled && (- <span className="ml-2 rounded bg-background px-1.5 py-0.5 text-xs">- Paused- </span>- )}- </p>- <Button- size="sm"- variant="outline"- disabled={toggle.isPending}- onClick={() => toggle.mutate()}- >- {trigger.enabled ? "Pause" : "Resume"}- </Button>- {confirmRemove ? (- <span className="flex gap-2">- <Button- size="sm"- variant="destructive"- disabled={remove.isPending}- onClick={() => remove.mutate()}- >- Remove for good- </Button>- <Button- size="sm"- variant="ghost"- onClick={() => setConfirmRemove(false)}- >- Keep- </Button>- </span>- ) : (- <Button- size="sm"- variant="ghost"- onClick={() => setConfirmRemove(true)}- >- Remove- </Button>- )}- </div>- <p className="text-muted-foreground text-xs">{KIND_HELP[trigger.kind]}</p>- {url && (- <div className="flex flex-wrap items-center gap-2">- <span className="text-xs">POST to</span>- <code className="break-all rounded bg-background px-2 py-1 text-xs">- {url}- </code>- <CopyButton value={url} label="Copy URL" />- </div>- )}- {trigger.kind === "email" &&- (trigger.address ? (- <div className="flex flex-wrap items-center gap-2">- <code className="break-all rounded bg-background px-2 py-1 text-xs">- {trigger.address}- </code>- <CopyButton value={trigger.address} label="Copy address" />- </div>- ) : (- <p className="text-amber-600 text-xs dark:text-amber-500">- Inbound email is not configured on this deployment- (OPENBOT_INBOUND_EMAIL_DOMAIN and- OPENBOT_INBOUND_EMAIL_SNS_TOPIC_ARNS), so this address cannot- receive mail yet.- </p>- ))}- {generated && (- <div className="flex flex-wrap items-center gap-2">- <span className="text-xs">Key</span>- {shown ? (- <>- <code className="break-all rounded bg-background px-2 py-1 text-xs">- {shown}- </code>- <CopyButton value={shown} label="Copy key" />- {trigger.kind === "webhook" && (- <CopyButton- value={`Authorization: Bearer ${shown}`}- label="Copy header"- />- )}- </>- ) : (- <Button- size="sm"- variant="outline"- disabled={reveal.isPending}- onClick={() => reveal.mutate()}- >- Show key- </Button>- )}- <Button- size="sm"- variant="outline"- disabled={rotate.isPending}- onClick={() => rotate.mutate()}- >- Rotate key- </Button>- </div>- )}- {trigger.kind === "webhook" && shown && (- <code className="break-all rounded bg-background px-2 py-1 text-xs">- Authorization: Bearer {shown}- </code>- )}- {VENDOR_SECRET.has(trigger.kind) && (- <form- className="flex flex-wrap items-center gap-2"- onSubmit={(event) => {- event.preventDefault();- rotate.mutate();- }}- >- <span- className={- trigger.hasSecret- ? "text-xs"- : "text-amber-600 text-xs dark:text-amber-500"- }- >- {trigger.hasSecret- ? "Signing secret stored"- : "Waiting for the signing secret"}- </span>- <Input- className="h-8 max-w-64"- type="password"- autoComplete="new-password"- placeholder={- trigger.hasSecret- ? "Paste a new secret to rotate"- : "Paste the signing secret"- }- value={pasted}- onChange={(event) => setPasted(event.target.value)}- required- />- <Button size="sm" type="submit" disabled={rotate.isPending}>- Save secret- </Button>- </form>- )}- {(reveal.error || rotate.error || remove.error || toggle.error) && (- <p role="alert" className="text-destructive text-xs">- {reveal.error?.message ??- rotate.error?.message ??- remove.error?.message ??- toggle.error?.message}- </p>- )}- </div>- );-}--function NewTrigger({- goalId,- botId,- onCreated,-}: {- goalId: string;- botId: string;- onCreated: (created: {- trigger: TriggerRecord;- secret: string | null;- }) => Promise<void>;-}) {- const id = useId();- const queryClient = useQueryClient();- const [kind, setKind] = useState<TriggerKind>("webhook");- const [eventTypes, setEventTypes] = useState("");- const [fieldPath, setFieldPath] = useState("");- const [fieldEquals, setFieldEquals] = useState("");- const [repository, setRepository] = useState("");- const [senders, setSenders] = useState("");- const [secret, setSecret] = useState("");- const [teamId, setTeamId] = useState("");- const [mode, setMode] = useState<- "mention" | "phrase" | "reaction" | "message"- >("mention");- const [phrases, setPhrases] = useState("");- const [reactions, setReactions] = useState("");- const [channels, setChannels] = useState("");- const config = (): TriggerConfig => {- if (kind === "slack")- return {- kind,- teamId: teamId.trim(),- mode,- phrases: list(phrases),- reactions: list(reactions).map((reaction) =>- reaction.replace(/:/g, ""),- ),- channels: list(channels),- };- const filter = {- eventTypes: list(eventTypes),- ...(fieldPath.trim() && fieldEquals.trim()- ? { field: { path: fieldPath.trim(), equals: fieldEquals.trim() } }- : {}),- };- if (kind === "github")- return {- kind,- filter,- ...(repository.trim() ? { repository: repository.trim() } : {}),- };- if (kind === "email")- return { kind, filter, allowedSenders: list(senders) };- return { kind, filter };- };- const create = useMutation({- mutationFn: () =>- createTrigger(goalId, {- config: config(),- ...(VENDOR_SECRET.has(kind) && secret ? { secret } : {}),- }),- onSuccess: async (created) => {- await onCreated(created);- /* A new trigger is a new way the shared app gets called, so the approval it needs may- * have changed: refresh the inbox and this Bot's shared-app notice alongside it. */- await queryClient.invalidateQueries({- queryKey: sharedUseKeys.requests(),- });- },- });- const placeholder: Record<TriggerKind, string> = {- webhook: "deploy.finished (blank: any)",- github: "issues.opened, pull_request",- linear: "Issue.create, Comment",- sentry: "issue.created, event_alert.triggered",- pagerduty: "incident.triggered",- email: "received",- slack: "",- };- return (- <form- className="grid gap-3 rounded-md border p-3"- onSubmit={(event) => {- event.preventDefault();- create.mutate();- }}- >- <label className={fieldClass}>- Trigger- <select- className={selectClass}- value={kind}- onChange={(event) => setKind(event.target.value as TriggerKind)}- >- {(Object.keys(KIND_LABEL) as TriggerKind[]).map((value) => (- <option key={value} value={value}>- {KIND_LABEL[value]}- </option>- ))}- </select>- </label>- <p className="text-muted-foreground text-xs">{KIND_HELP[kind]}</p>- {kind === "slack" ? (- <div className="grid gap-3 sm:grid-cols-2">- <label className={fieldClass} htmlFor={`${id}-team`}>- Slack team ID- <Input- id={`${id}-team`}- required- placeholder="T0123ABCD"- value={teamId}- onChange={(event) => setTeamId(event.target.value)}- />- </label>- <label className={fieldClass}>- Fire on- <select- className={selectClass}- value={mode}- onChange={(event) => setMode(event.target.value as typeof mode)}- >- <option value="mention">The Bot is mentioned</option>- <option value="phrase">A message contains a phrase</option>- <option value="reaction">A reaction is added</option>- <option value="message">Any message</option>- </select>- </label>- {mode === "phrase" && (- <label className={fieldClass} htmlFor={`${id}-phrases`}>- Phrases (comma separated)- <Input- id={`${id}-phrases`}- required- value={phrases}- onChange={(event) => setPhrases(event.target.value)}- />- </label>- )}- {mode === "reaction" && (- <label className={fieldClass} htmlFor={`${id}-reactions`}>- Reactions (blank: any)- <Input- id={`${id}-reactions`}- placeholder="eyes, rotating_light"- value={reactions}- onChange={(event) => setReactions(event.target.value)}- />- </label>- )}- <label className={fieldClass} htmlFor={`${id}-channels`}>- Channel IDs (blank: all the Bot is in)- <Input- id={`${id}-channels`}- placeholder="C0123ABCD"- value={channels}- onChange={(event) => setChannels(event.target.value)}- />- </label>- </div>- ) : (- <div className="grid gap-3 sm:grid-cols-3">- <label className={fieldClass} htmlFor={`${id}-types`}>- Event types- <Input- id={`${id}-types`}- placeholder={placeholder[kind]}- value={eventTypes}- onChange={(event) => setEventTypes(event.target.value)}- />- </label>- <label className={fieldClass} htmlFor={`${id}-path`}>- Only when field- <Input- id={`${id}-path`}- placeholder="data.team.key"- value={fieldPath}- onChange={(event) => setFieldPath(event.target.value)}- />- </label>- <label className={fieldClass} htmlFor={`${id}-equals`}>- equals- <Input- id={`${id}-equals`}- placeholder="ENG"- value={fieldEquals}- onChange={(event) => setFieldEquals(event.target.value)}- />- </label>- {kind === "github" && (- <label className={fieldClass} htmlFor={`${id}-repo`}>- Repository (optional)- <Input- id={`${id}-repo`}- placeholder="owner/name"- value={repository}- onChange={(event) => setRepository(event.target.value)}- />- </label>- )}- {kind === "email" && (- <label className={fieldClass} htmlFor={`${id}-senders`}>- Allowed senders (blank: anyone)- <Input- id={`${id}-senders`}- placeholder="[email protected], example.com"- value={senders}- onChange={(event) => setSenders(event.target.value)}- />- </label>- )}- {VENDOR_SECRET.has(kind) && (- <label className={fieldClass} htmlFor={`${id}-secret`}>- Signing secret (can be added later)- <Input- id={`${id}-secret`}- type="password"- autoComplete="new-password"- value={secret}- onChange={(event) => setSecret(event.target.value)}- />- </label>- )}- </div>- )}- <SharedAppNotice botId={botId} reason="trigger" />- {create.error && (- <p role="alert" className="text-destructive text-sm">- {create.error.message}- </p>- )}- <Button type="submit" disabled={create.isPending}>- {create.isPending ? "Adding…" : `Add ${KIND_LABEL[kind]} trigger`}- </Button>- </form>- );-}diff --git a/app/src/routes/_authed/_app/team-bots.tsx b/app/src/routes/_authed/_app/team-bots.tsxindex 0d008981..0dc440dd 100644--- a/app/src/routes/_authed/_app/team-bots.tsx+++ b/app/src/routes/_authed/_app/team-bots.tsx@@ -1,324 +1,8 @@-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";-import { createFileRoute, Link } from "@tanstack/react-router";-import { useState } from "react";-import { ChannelAvatar } from "@/components/channels/avatar";-import { PageSection, PageShell } from "@/components/layout/page-shell";-import { SharedAppNotice } from "@/components/plugins/shared-app-notice";-import { Button } from "@/components/ui/button";-import { Input } from "@/components/ui/input";-import { currentUserQueryOptions } from "@/lib/auth/queries";-import {- assignTeamBotMutationOptions,- clearTeamBotConsentsMutationOptions,- publishTeamBotMutationOptions,- type TeamBot,- teamBotLink,- teamBotsQueryOptions,- unpublishTeamBotMutationOptions,-} from "@/lib/team-bots";+import { createFileRoute, redirect } from "@tanstack/react-router";-/**- * Team Bots: find the Bots teammates published, publish your own to the team or to named people and- * groups, and (administrators) put one in a group's sidebars. A chat with a Team Bot is always the- * teammate's own; its owner cannot read it.- */+/** Team Bots moved: the roster lists them, and each Bot's Sharing page publishes it. */export const Route = createFileRoute("/_authed/_app/team-bots")({- component: TeamBotsPage,+ beforeLoad: () => {+ throw redirect({ to: "/bots", replace: true });+ },});--const list = (value: string) =>- value- .split(",")- .map((part) => part.trim())- .filter(Boolean);--function TeamBotsPage() {- const data = useQuery(teamBotsQueryOptions());- const me = useQuery(currentUserQueryOptions()).data;- const clear = useMutation(clearTeamBotConsentsMutationOptions());- const bots = data.data?.teamBots ?? [];- const shared = bots.filter((bot) => !bot.mine);- const mine = bots.filter((bot) => bot.mine);-- return (- <PageShell- description="Bots your teammates published, and the ones you share. Each chat with a Team Bot is private to the person having it."- title="Team Bots"- width="wide"- >- {data.isError ? (- <p className="text-sm text-destructive" role="alert">- {data.error.message}- </p>- ) : null}- <PageSection title="Available to you">- {shared.length === 0 ? (- <p className="text-sm text-muted-foreground">- Nobody has published a Bot to you yet.- </p>- ) : (- shared.map((bot) => <TeamBotRow bot={bot} key={bot.id} />)- )}- </PageSection>- <PageSection title="Yours">- {mine.map((bot) => (- <div className="flex flex-col gap-2" key={bot.id}>- <TeamBotRow bot={bot} />- <PublishForm botId={bot.id} current={bot} />- </div>- ))}- {(data.data?.publishable ?? []).length ? (- <PublishNew publishable={data.data?.publishable ?? []} />- ) : mine.length === 0 ? (- <p className="text-sm text-muted-foreground">- You have no Bots of your own to publish.- </p>- ) : null}- </PageSection>- {me?.role === "admin" ? (- <PageSection title="Assign to groups">- <p className="text-sm text-muted-foreground">- An assigned Bot appears in every member's sidebar, and they cannot- hide it. Use * for the whole team.- </p>- {bots.map((bot) => (- <Assignments bot={bot} key={bot.id} />- ))}- </PageSection>- ) : null}- <PageSection title="Your accounts">- <p className="text-sm text-muted-foreground">- A Team Bot uses its owner's connected apps. It uses your own account- only when you allow it on the card it shows you.- </p>- <div className="flex items-center gap-2">- <Button- disabled={clear.isPending}- onClick={() => clear.mutate()}- size="sm"- variant="outline"- >- Clear connector preferences- </Button>- {clear.isSuccess ? (- <span className="text-sm text-muted-foreground" role="status">- Cleared. Team Bots will ask again.- </span>- ) : null}- </div>- </PageSection>- </PageShell>- );-}--function TeamBotRow({ bot }: { bot: TeamBot }) {- const queryClient = useQueryClient();- const unpublish = useMutation(unpublishTeamBotMutationOptions(queryClient));- const [copied, setCopied] = useState(false);- return (- <div- className="flex flex-wrap items-center gap-3 rounded-lg border border-border p-3"- data-team-bot={bot.id}- >- <ChannelAvatar participantIds={[bot.id]} size={28} />- <div className="flex min-w-0 flex-1 flex-col">- <span className="text-sm font-medium">{bot.name}</span>- <span className="truncate text-sm text-muted-foreground">- {bot.title}- {bot.assigned ? " · assigned to you" : ""}- {bot.mine && !bot.visibleToTeam- ? " · hidden from teammates until it has a real name and a description"- : ""}- {bot.mine- ? bot.audience === "team"- ? " · published to the whole team"- : ` · published to ${[...(bot.people ?? []), ...(bot.groups ?? []).map((group) => `group ${group}`)].join(", ")}`- : ""}- </span>- </div>- <Button- render={(props) => (- <Link {...props} search={{ agent: bot.id }} to="/channel/new" />- )}- size="sm"- >- Start a private chat- </Button>- <Button- onClick={() =>- void navigator.clipboard- .writeText(teamBotLink(bot.id))- .then(() => setCopied(true))- }- size="sm"- variant="outline"- >- {copied ? "Copied" : "Copy link"}- </Button>- {bot.mine ? (- <Button- disabled={unpublish.isPending}- onClick={() => unpublish.mutate(bot.id)}- size="sm"- variant="ghost"- >- Unpublish- </Button>- ) : null}- </div>- );-}--function PublishNew({- publishable,-}: {- publishable: { id: string; name: string }[];-}) {- const [botId, setBotId] = useState(publishable[0]?.id ?? "");- return (- <div className="flex flex-col gap-2 rounded-lg border border-dashed border-border p-3">- <label className="grid gap-1 text-sm">- Publish one of your Bots- <select- className="h-9 rounded-md border bg-background px-3 text-sm"- onChange={(event) => setBotId(event.target.value)}- value={botId}- >- {publishable.map((bot) => (- <option key={bot.id} value={bot.id}>- {bot.name}- </option>- ))}- </select>- </label>- {botId ? <PublishForm botId={botId} key={botId} /> : null}- </div>- );-}--/** Who a Bot is published to: the whole team, or named people and groups. */-function PublishForm({ botId, current }: { botId: string; current?: TeamBot }) {- const queryClient = useQueryClient();- const publish = useMutation(publishTeamBotMutationOptions(queryClient));- const [audience, setAudience] = useState<"team" | "people">(- current?.audience ?? "team",- );- const [emails, setEmails] = useState((current?.people ?? []).join(", "));- const [groups, setGroups] = useState((current?.groups ?? []).join(", "));- return (- <form- className="flex flex-col gap-2"- onSubmit={(event) => {- event.preventDefault();- publish.mutate({- botId,- audience,- emails: audience === "people" ? list(emails) : [],- groups: audience === "people" ? list(groups) : [],- });- }}- >- <div className="flex flex-wrap gap-4 text-sm">- <label className="flex items-center gap-1.5">- <input- checked={audience === "team"}- name={`audience-${botId}`}- onChange={() => setAudience("team")}- type="radio"- />- The whole team- </label>- <label className="flex items-center gap-1.5">- <input- checked={audience === "people"}- name={`audience-${botId}`}- onChange={() => setAudience("people")}- type="radio"- />- Specific people or groups- </label>- </div>- {audience === "people" ? (- <div className="grid gap-2 sm:grid-cols-2">- <Input- aria-label="People, by email"- onChange={(event) => setEmails(event.target.value)}- placeholder="People, by email, comma separated"- value={emails}- />- <Input- aria-label="Groups"- onChange={(event) => setGroups(event.target.value)}- placeholder="Groups, comma separated"- value={groups}- />- </div>- ) : null}- <SharedAppNotice botId={botId} reason="publish" />- <div className="flex items-center gap-2">- <Button disabled={publish.isPending} size="sm" type="submit">- {current ? "Update" : "Publish to team"}- </Button>- {publish.error ? (- <span className="text-sm text-destructive" role="alert">- {publish.error.message}- </span>- ) : null}- </div>- </form>- );-}--function Assignments({ bot }: { bot: TeamBot }) {- const queryClient = useQueryClient();- const assign = useMutation(assignTeamBotMutationOptions(queryClient));- const [group, setGroup] = useState("");- return (- <div className="flex flex-wrap items-center gap-2 text-sm">- <span className="font-medium">{bot.name}</span>- {(bot.assignments ?? []).map((name) => (- <Button- aria-label={`Remove ${name}`}- key={name}- onClick={() =>- assign.mutate({ botId: bot.id, group: name, remove: true })- }- size="sm"- variant="outline"- >- {name === "*" ? "Whole team" : name} ×- </Button>- ))}- <form- className="flex items-center gap-2"- onSubmit={(event) => {- event.preventDefault();- assign.mutate(- { botId: bot.id, group },- { onSuccess: () => setGroup("") },- );- }}- >- <Input- aria-label={`Assign ${bot.name} to a group`}- className="w-40"- onChange={(event) => setGroup(event.target.value)}- placeholder="Group, or *"- value={group}- />- <Button- disabled={!group.trim() || assign.isPending}- size="sm"- type="submit"- >- Assign- </Button>- </form>- {assign.error ? (- <span className="text-destructive" role="alert">- {assign.error.message}- </span>- ) : null}- </div>- );-}diff --git a/app/src/routes/_authed/admin/approvals.tsx b/app/src/routes/_authed/admin/approvals.tsxnew file mode 100644index 00000000..af067d45--- /dev/null+++ b/app/src/routes/_authed/admin/approvals.tsx@@ -0,0 +1,18 @@+import { createFileRoute } from "@tanstack/react-router";+import { TeamApprovalSettings } from "@/components/approvals/team-settings";+import { PageShell } from "@/components/layout/page-shell";++export const Route = createFileRoute("/_authed/admin/approvals")({+ component: AdminApprovalsPage,+});++function AdminApprovalsPage() {+ return (+ <PageShell+ description="What members' Bots must ask before acting, rules for everyone, and requests to use shared accounts."+ title="Approvals"+ >+ <TeamApprovalSettings />+ </PageShell>+ );+}diff --git a/app/src/routes/_authed/admin/credentials.tsx b/app/src/routes/_authed/admin/credentials.tsxindex c9637019..879f3416 100644--- a/app/src/routes/_authed/admin/credentials.tsx+++ b/app/src/routes/_authed/admin/credentials.tsx@@ -2,7 +2,7 @@ import { IconPlus } from "@tabler/icons-react";import { useForm } from "@tanstack/react-form";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import { createFileRoute } from "@tanstack/react-router";-import { useState } from "react";+import { useId, useState } from "react";import {PageEmpty,PageRows,@@ -62,6 +62,7 @@ export const Route = createFileRoute("/_authed/admin/credentials")({function CredentialsPage() {const [adding, setAdding] = useState(false);+ const formId = useId();const queryClient = useQueryClient();const credentials = useQuery(credentialListQueryOptions());const createCredential = useMutation(@@ -104,20 +105,23 @@ function CredentialsPage() {*/}<Dialog onOpenChange={setAdding} open={adding}><DialogContent>- <form- noValidate- onSubmit={(event) => {- event.preventDefault();- form.handleSubmit();- }}- >- <DialogHeader>- <DialogTitle>Add credential</DialogTitle>- <DialogDescription>- Held for this deployment and never shown again once saved.- </DialogDescription>- </DialogHeader>- <DialogBody className="mt-4">+ <DialogHeader>+ <DialogTitle>Add credential</DialogTitle>+ <DialogDescription>+ Held for this deployment and never shown again once saved.+ </DialogDescription>+ </DialogHeader>+ <DialogBody className="mt-4">+ {/* The submit button is in the footer and reaches this form by id, so DialogBody stays a+ direct child of DialogContent and keeps scrolling. */}+ <form+ id={formId}+ noValidate+ onSubmit={(event) => {+ event.preventDefault();+ form.handleSubmit();+ }}+ ><FieldGroup className="sm:grid sm:grid-cols-2"><form.Field name="kind">{(field) => {@@ -231,65 +235,66 @@ function CredentialsPage() {}}</form.Field></FieldGroup>- {/*- * Said before the write, not after it.- *- * A key holds one live credential, so saving onto a key that already has one is a- * replacement: the old credential is revoked in the same transaction. The page calls- * this Add and has no rotate control, so without this line an administrator retires- * the credential an MCP server or an agent is currently authenticating with, and- * nothing on screen mentions it until something stops working.- */}- <form.Subscribe- selector={(state) => [- state.values.kind,- state.values.provider,- state.values.keyId,- ]}- >- {([kind, provider, keyId]) =>- liveCredentialFor(credentials.data, kind, provider, keyId) ? (- <p className="text-amber-600 text-sm dark:text-amber-500">- This key already holds a live credential. Saving replaces- it, and the one it replaces is revoked.- </p>- ) : null- }- </form.Subscribe>- {createCredential.error ? (- <p className="text-destructive text-sm" role="alert">- Could not save the credential. Try again.- </p>- ) : null}- </DialogBody>- <DialogFooter className="mt-4">- <Button- onClick={() => setAdding(false)}- size="sm"- type="button"- variant="ghost"- >- Cancel- </Button>- <form.Subscribe- selector={(state) => [state.canSubmit, state.isSubmitting]}- >- {([canSubmit, isSubmitting]) => (- <Button- disabled={- !canSubmit || isSubmitting || createCredential.isPending- }- size="sm"- type="submit"- >- {isSubmitting || createCredential.isPending- ? "Saving…"- : "Save credential"}- </Button>- )}- </form.Subscribe>- </DialogFooter>- </form>+ </form>+ {/*+ * Said before the write, not after it.+ *+ * A key holds one live credential, so saving onto a key that already has one is a+ * replacement: the old credential is revoked in the same transaction. The page calls+ * this Add and has no rotate control, so without this line an administrator retires+ * the credential an MCP server or an agent is currently authenticating with, and+ * nothing on screen mentions it until something stops working.+ */}+ <form.Subscribe+ selector={(state) => [+ state.values.kind,+ state.values.provider,+ state.values.keyId,+ ]}+ >+ {([kind, provider, keyId]) =>+ liveCredentialFor(credentials.data, kind, provider, keyId) ? (+ <p className="text-amber-600 text-sm dark:text-amber-500">+ This key already holds a live credential. Saving replaces+ it, and the one it replaces is revoked.+ </p>+ ) : null+ }+ </form.Subscribe>+ {createCredential.error ? (+ <p className="text-destructive text-sm" role="alert">+ Could not save the credential. Try again.+ </p>+ ) : null}+ </DialogBody>+ <DialogFooter className="mt-4">+ <Button+ onClick={() => setAdding(false)}+ size="sm"+ type="button"+ variant="ghost"+ >+ Cancel+ </Button>+ <form.Subscribe+ selector={(state) => [state.canSubmit, state.isSubmitting]}+ >+ {([canSubmit, isSubmitting]) => (+ <Button+ disabled={+ !canSubmit || isSubmitting || createCredential.isPending+ }+ form={formId}+ size="sm"+ type="submit"+ >+ {isSubmitting || createCredential.isPending+ ? "Saving…"+ : "Save credential"}+ </Button>+ )}+ </form.Subscribe>+ </DialogFooter></DialogContent></Dialog>diff --git a/app/src/routes/_authed/admin/enterprise.tsx b/app/src/routes/_authed/admin/enterprise.tsxindex 58ee27a0..2ac24083 100644--- a/app/src/routes/_authed/admin/enterprise.tsx+++ b/app/src/routes/_authed/admin/enterprise.tsx@@ -14,7 +14,7 @@ import {} from "@tabler/icons-react";import { useMutation, useQuery } from "@tanstack/react-query";import { createFileRoute } from "@tanstack/react-router";-import { useState } from "react";+import { useId, useState } from "react";import {PageEmpty,PageRows,@@ -854,6 +854,7 @@ function NetworkDialog({const save = useMutation(setNetworkPolicyMutationOptions(queryClient));const remove = useMutation(removeNetworkPolicyMutationOptions(queryClient));const scopeId = initial.scopeKind === "group" ? group : "";+ const formId = useId();return (<Dialog onOpenChange={(open) => (open ? undefined : onClose())} open>@@ -865,22 +866,26 @@ function NetworkDialog({: "Group network policy"}</DialogTitle></DialogHeader>- <form- onSubmit={(event) => {- event.preventDefault();- save.mutate(- {- scopeKind: initial.scopeKind,- scopeId,- mode,- rules: rulesFromText(rules),- locked,- },- { onSuccess: onClose },- );- }}- >- <DialogBody className="mt-4 space-y-4 overflow-y-auto">+ <DialogBody className="mt-4 space-y-4 overflow-y-auto">+ {/* The submit button is in the footer and reaches this form by id, so DialogBody stays a+ direct child of DialogContent and keeps scrolling. */}+ <form+ className="flex flex-col gap-4"+ id={formId}+ onSubmit={(event) => {+ event.preventDefault();+ save.mutate(+ {+ scopeKind: initial.scopeKind,+ scopeId,+ mode,+ rules: rulesFromText(rules),+ locked,+ },+ { onSuccess: onClose },+ );+ }}+ >{initial.scopeKind === "group" && !initial.scopeId ? (<div className="space-y-1.5"><Label>Group</Label>@@ -955,43 +960,44 @@ function NetworkDialog({/></div>) : null}- {(save.error ?? remove.error) ? (- <p className="text-destructive text-sm" role="alert">- {(save.error ?? remove.error)?.message}- </p>- ) : null}- </DialogBody>- <DialogFooter className="mt-4">- {existing ? (- <Button- disabled={remove.isPending}- onClick={() =>- remove.mutate(- { scopeKind: initial.scopeKind, scopeId },- { onSuccess: onClose },- )- }- size="sm"- type="button"- variant="destructive"- >- Remove policy- </Button>- ) : null}- <Button onClick={onClose} size="sm" type="button" variant="outline">- Cancel- </Button>+ </form>+ {(save.error ?? remove.error) ? (+ <p className="text-destructive text-sm" role="alert">+ {(save.error ?? remove.error)?.message}+ </p>+ ) : null}+ </DialogBody>+ <DialogFooter className="mt-4">+ {existing ? (<Button- disabled={- save.isPending || (initial.scopeKind === "group" && !scopeId)+ disabled={remove.isPending}+ onClick={() =>+ remove.mutate(+ { scopeKind: initial.scopeKind, scopeId },+ { onSuccess: onClose },+ )}size="sm"- type="submit"+ type="button"+ variant="destructive">- {save.isPending ? "Saving…" : "Save"}+ Remove policy</Button>- </DialogFooter>- </form>+ ) : null}+ <Button onClick={onClose} size="sm" type="button" variant="outline">+ Cancel+ </Button>+ <Button+ disabled={+ save.isPending || (initial.scopeKind === "group" && !scopeId)+ }+ form={formId}+ size="sm"+ type="submit"+ >+ {save.isPending ? "Saving…" : "Save"}+ </Button>+ </DialogFooter></DialogContent></Dialog>);diff --git a/app/src/routes/_authed/admin/identity-providers.tsx b/app/src/routes/_authed/admin/identity-providers.tsxindex 124ff2f9..f166f006 100644--- a/app/src/routes/_authed/admin/identity-providers.tsx+++ b/app/src/routes/_authed/admin/identity-providers.tsx@@ -1,7 +1,7 @@import { IconBuildingBank, IconTrash } from "@tabler/icons-react";import { useMutation, useQuery } from "@tanstack/react-query";import { createFileRoute } from "@tanstack/react-router";-import { useState } from "react";+import { useId, useState } from "react";import {PageEmpty,PageRows,@@ -63,6 +63,7 @@ function IdentityProvidersPage() {);const [open, setOpen] = useState(false);const [draft, setDraft] = useState(EMPTY);+ const formId = useId();// A removal failure belongs on the page: there is no dialog to put it in. A registration failure// is shown inside the dialog instead, where the person who caused it is looking.@@ -164,8 +165,10 @@ function IdentityProvidersPage() {<DialogHeader><DialogTitle>Add an identity provider</DialogTitle></DialogHeader>- <form onSubmit={submit}>- <DialogBody className="mt-4 space-y-4 overflow-y-auto">+ <DialogBody className="mt-4 space-y-4 overflow-y-auto">+ {/* The submit button is in the footer and reaches this form by id, so DialogBody stays a+ direct child of DialogContent and keeps scrolling. */}+ <form className="flex flex-col gap-4" id={formId} onSubmit={submit}><div className="flex gap-2">{(["saml", "oidc"] as const).map((protocol) => (<Button@@ -288,32 +291,36 @@ function IdentityProvidersPage() {</div></>)}-- {/*+ </form>+ {/*Here as well as on the page behind, because while this is open the page behind it isnot visible. A registration refused by the identity provider or by Better Auth leftthe dialog sitting there unchanged, which reads as the button not working.*/}- {register.error ? (- <p className="text-destructive text-sm" role="alert">- {register.error.message}- </p>- ) : null}- </DialogBody>- <DialogFooter className="mt-4">- <Button- onClick={() => setOpen(false)}- size="sm"- type="button"- variant="outline"- >- Cancel- </Button>- <Button disabled={register.isPending} size="sm" type="submit">- {register.isPending ? "Adding…" : "Add"}- </Button>- </DialogFooter>- </form>+ {register.error ? (+ <p className="text-destructive text-sm" role="alert">+ {register.error.message}+ </p>+ ) : null}+ </DialogBody>+ <DialogFooter className="mt-4">+ <Button+ onClick={() => setOpen(false)}+ size="sm"+ type="button"+ variant="outline"+ >+ Cancel+ </Button>+ <Button+ disabled={register.isPending}+ form={formId}+ size="sm"+ type="submit"+ >+ {register.isPending ? "Adding…" : "Add"}+ </Button>+ </DialogFooter></DialogContent></Dialog></PageShell>diff --git a/app/src/routes/_authed/admin/index.tsx b/app/src/routes/_authed/admin/index.tsxindex 9fd8f1cc..d80c2831 100644--- a/app/src/routes/_authed/admin/index.tsx+++ b/app/src/routes/_authed/admin/index.tsx@@ -1,5 +1,6 @@import {IconBuildingBank,+ IconChecks,IconChevronRight,IconCode,IconDeviceDesktop,@@ -68,6 +69,12 @@ const SECTIONS: {icon: IconShieldCheck,linkOptions: { to: "/admin/boundaries" },},+ {+ title: "Approvals",+ description: "What every member's Bots must ask before acting.",+ icon: IconChecks,+ linkOptions: { to: "/admin/approvals" },+ },{title: "Computers",description: "The machines Bots run their tools on.",diff --git a/app/src/routes/_authed/admin/plugins/$key_.bots.$agentId.tsx b/app/src/routes/_authed/admin/plugins/$key_.bots.$agentId.tsxindex da6a0681..81d321ca 100644--- a/app/src/routes/_authed/admin/plugins/$key_.bots.$agentId.tsx+++ b/app/src/routes/_authed/admin/plugins/$key_.bots.$agentId.tsx@@ -499,8 +499,8 @@ function RouteComponent() {</PageSection>{/*- * Stacked over the switch it came from, same pattern as the delete confirmation in- * `agent-dialog.tsx`: the consent a Shared app needs is its own moment, not a row that+ * Stacked over the switch it came from, same pattern as a Bot's delete confirmation in+ * `bot-profile/manage.tsx`: the consent a Shared app needs is its own moment, not a row that* happens to have grown a form. Closing without confirming — the backdrop, Escape, or* Cancel — leaves `pendingGrant` behind and the Switch stays exactly where it was; nothing* is granted until the confirm button below runs.diff --git a/app/src/routes/_authed/settings/approvals.tsx b/app/src/routes/_authed/settings/approvals.tsxnew file mode 100644index 00000000..9fcad272--- /dev/null+++ b/app/src/routes/_authed/settings/approvals.tsx@@ -0,0 +1,18 @@+import { createFileRoute } from "@tanstack/react-router";+import { ApprovalSettings } from "@/components/approvals/settings";+import { PageShell } from "@/components/layout/page-shell";++export const Route = createFileRoute("/_authed/settings/approvals")({+ component: ApprovalsSettingsPage,+});++function ApprovalsSettingsPage() {+ return (+ <PageShell+ description="Whether your Bots ask before they change things, and rules that apply to all of them."+ title="Approvals"+ >+ <ApprovalSettings />+ </PageShell>+ );+}diff --git a/app/src/routes/_authed/settings/connected-accounts/index.tsx b/app/src/routes/_authed/settings/connected-accounts/index.tsxindex 5a275288..dd7736c4 100644--- a/app/src/routes/_authed/settings/connected-accounts/index.tsx+++ b/app/src/routes/_authed/settings/connected-accounts/index.tsx@@ -5,16 +5,19 @@ import {IconPlug,IconSearch,} from "@tabler/icons-react";-import { useQuery } from "@tanstack/react-query";+import { useMutation, useQuery } from "@tanstack/react-query";import { createFileRoute, Link } from "@tanstack/react-router";import * as React from "react";import {PageEmpty,+ PageRows,PageSection,PageShell,} from "@/components/layout/page-shell";import { RowMark } from "@/components/layout/row-mark";import { PluginLogo } from "@/components/plugins/plugin-logo";+import { GithubSources } from "@/components/settings/github-sources";+import { Button } from "@/components/ui/button";import {InputGroup,InputGroupAddon,@@ -33,6 +36,7 @@ import {personalConnections,pluginsPageQueryOptions,} from "@/lib/plugins/queries";+import { clearTeamBotConsentsMutationOptions } from "@/lib/team-bots";/*** The services a Bot reads as you.@@ -385,6 +389,50 @@ function RouteComponent() {</div></PageSection>) : null}+ <GithubSources />+ <TeamBotConsents /></PageShell>);}++/**+ * A Bot someone shared with you uses its owner's connected apps unless you let it use yours on the+ * card it shows you. This forgets every one of those answers, so each such Bot asks again.+ */+function TeamBotConsents() {+ const clear = useMutation(clearTeamBotConsentsMutationOptions());+ return (+ <PageSection+ description="A Bot someone shared with you uses their connected apps, and yours only where you allowed it on the card it showed you."+ title="Bots shared with you"+ >+ {clear.error ? (+ <p className="mt-4 text-destructive text-sm" role="alert">+ {clear.error.message}+ </p>+ ) : null}+ <PageRows>+ <Item size="sm">+ <ItemContent>+ <ItemTitle>Your answers</ItemTitle>+ <ItemDescription>+ {clear.isSuccess+ ? "Cleared. Each will ask again."+ : "Forget them, so each asks again."}+ </ItemDescription>+ </ItemContent>+ <ItemActions>+ <Button+ disabled={clear.isPending}+ onClick={() => clear.mutate()}+ size="sm"+ variant="outline"+ >+ Clear+ </Button>+ </ItemActions>+ </Item>+ </PageRows>+ </PageSection>+ );+}diff --git a/app/src/routes/_authed/settings/memory.tsx b/app/src/routes/_authed/settings/memory.tsxnew file mode 100644index 00000000..01335bcd--- /dev/null+++ b/app/src/routes/_authed/settings/memory.tsx@@ -0,0 +1,19 @@+import { createFileRoute } from "@tanstack/react-router";+import { PageShell } from "@/components/layout/page-shell";+import { MemoryList, RememberFact } from "@/components/memory/memories";++export const Route = createFileRoute("/_authed/settings/memory")({+ component: MemorySettingsPage,+});++function MemorySettingsPage() {+ return (+ <PageShell+ action={<RememberFact />}+ description="What your Bots know about you. Facts you tell them reach every Bot; what a Bot learns stays with that Bot."+ title="Memory"+ >+ <MemoryList />+ </PageShell>+ );+}diff --git a/app/src/routes/_authed/settings/notifications.tsx b/app/src/routes/_authed/settings/notifications.tsxnew file mode 100644index 00000000..6a7a8de5--- /dev/null+++ b/app/src/routes/_authed/settings/notifications.tsx@@ -0,0 +1,22 @@+import { createFileRoute } from "@tanstack/react-router";+import { PageShell } from "@/components/layout/page-shell";+import { NativeDevices, RecentDeliveries } from "@/components/settings/devices";+import { UpdateRoutingSection } from "@/components/settings/update-routing";++export const Route = createFileRoute("/_authed/settings/notifications")({+ component: NotificationsPage,+});++/** Where your Bots' updates reach you, for all of your Bots at once. Each Bot's own page says how much. */+function NotificationsPage() {+ return (+ <PageShell+ description="Where updates from all your Bots reach you when you are not looking. How much each Bot sends is on its own page."+ title="Notifications"+ >+ <UpdateRoutingSection />+ <NativeDevices />+ <RecentDeliveries />+ </PageShell>+ );+}diff --git a/app/tests/agent-roster-error.test.tsx b/app/tests/agent-roster-error.test.tsxindex 44535d7c..cf0ff05b 100644--- a/app/tests/agent-roster-error.test.tsx+++ b/app/tests/agent-roster-error.test.tsx@@ -11,21 +11,18 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import {createMemoryHistory,createRootRoute,- createRoute,createRouter,- Outlet,RouterProvider,} from "@tanstack/react-router";import { cleanup, render, waitFor } from "@testing-library/react";import { type AgentProfile, agentKeys } from "@/lib/agents/queries";-import { Route as AgentsRoute } from "@/routes/_authed/_app/agents/index";import { Route as HomeRoute } from "@/routes/_authed/_app/index";/**- * Both agent-facing screens read the same `agentListQueryOptions()` query, and both drew their- * empty state on a FAILED query, not just an empty one: `isPending` (what each screen branches on)- * goes false on failure exactly as it does on success, so a broken fetch fell through to "you have- * nothing" and told somebody who may own twenty coworkers that they own none.+ * The home screen reads `agentListQueryOptions()` and drew its empty state on a FAILED query, not+ * just an empty one: `isPending` goes false on failure exactly as it does on success, so a broken+ * fetch fell through to "you have nothing" and told somebody who may own twenty coworkers that they+ * own none. The Bots roster's own failure handling is pinned in `bot-roster.test.tsx`.** THE HARNESS IS THIS REPOSITORY'S. `GlobalRegistrator` in `beforeAll`/`afterAll`, `cleanup` in* `afterEach`, and queries off `render()`'s own return, matching `proposed-bot-card.test.tsx` for@@ -34,8 +31,7 @@ import { Route as HomeRoute } from "@/routes/_authed/_app/index";** Each test builds its own `QueryClient` with `retry: false` — the app's own client (see* `query-client.ts`) retries once, which is correct for production and would just slow this test- * down for no assertion it needs. Both screens are exercised through their real, exported `Route`,- * not a stand-in; see `renderAgents` below for what that costs on `/agents`.+ * down for no assertion it needs.*/beforeAll(() => GlobalRegistrator.register());@@ -117,13 +113,12 @@ async function waitForFailedRefetch(queryClient: QueryClient) {}/**- * `findByText`'s own default wait is 1000ms, and `/` additionally mounts the heavy rich-text- * `Composer` on top of the roster query this file already exercises, so a render on `/` is- * measurably slower than its `/agents` twin. Under load that gap crosses 1000ms and the default+ * `findByText`'s own default wait is 1000ms, and `/` mounts the heavy rich-text `Composer` on top+ * of the roster query, so a render on `/` is slow. Under load it crosses 1000ms and the default* times out around 1010ms — not a logic bug (data is never cleared or corrupted through the error* transition; this was checked with a `Profiler`), just too little headroom for a busy machine. Do* not remove this as a redundant-looking argument: every `findByText` in a test that renders `/`- * needs it, and `/agents`-only tests do not, because they never mount `Composer`.+ * needs it.*/const HOME_FIND_TIMEOUT = { timeout: 5000 };@@ -142,149 +137,6 @@ function renderHome(queryClient: QueryClient) {);}-/**- * `/agents`'s component calls `Route.useSearch()` and `Route.useNavigate()`, which read `this.id`- * off the very `Route` singleton the source file exports — so, unlike `/`, a bare root standing in- * for it is not enough; those hooks fail to resolve a match unless that exact object is present in- * the router's tree with the id it expects.- *- * That id is not a free choice: `Route.useSearch()`/`useNavigate()` read it from `this.id`, which- * TanStack Router computes by walking `getParentRoute()` up to the root and joining each ancestor's- * own id, so it is fixed by the file's real position — `/_authed/_app/agents/` for a leaf declared- * `createFileRoute("/_authed/_app/agents/")` under pathless `_authed`/`_app` parents. Reproducing- * that with two throwaway pathless routes (`id`-only, no `path`, so they contribute nothing to the- * URL — exactly what `_authed`/`_app` do) is enough for the join to land on the same id; it does not- * require the real ancestors, whose `beforeLoad` checks a signed-in session and whose components- * mount the sidebar shell and the Copilot provider — none of which this test is about.- *- * The real `Route` singleton is `.update()`d in place to attach to this decoy chain, because- * `Route.useSearch()`/`useNavigate()` are bound to the one object the source module exports — there- * is no way to hand the component a stand-in. `beforeEach`/`afterEach` capture and restore its- * *entire own state* — not just `options`, and not by replaying it through `.update()` — around each- * render, so a real router built elsewhere in this same bun process (there is exactly one:- * `router.test.ts`, which never inspects this route) is never left pointed at the decoy.- *- * A restore that merely replayed the captured `options` through `.update()` would not work: the- * installed `update()` (`@tanstack/[email protected]`'s `dist/esm/route.js`) is- * `Object.assign(this.options, options); return this;` — a merge. `Object.assign` only overwrites- * or adds keys, it never deletes one, so merging a snapshot that predates this file's `id`/`path`/- * `getParentRoute` back on top leaves those decoy keys sitting in `options` untouched. Worse,- * `update()` never touches the *derived* state `router.js`'s `buildRouteTree()` computes by calling- * `route.init({ originalIndex })` once per route each time a router is built (`_id`, `_path`,- * `_fullPath`, `_to`, `parentRoute`, `originalIndex`) — those stay pinned to whatever this file's own- * `createRouter()` last resolved them to, decoy parent included, since nothing re-runs `init()` on- * `.update()`. The only restore that actually undoes a render is a full replace: snapshot every own- * property up front (with `options` itself shallow-cloned, since `update()` mutates that very object- * in place rather than replacing it) and, afterward, delete whatever the render added and reassign- * the rest verbatim.- */-function captureRouteState(route: object): Record<string, unknown> {- return { ...route, options: { ...(route as { options: object }).options } };-}--function restoreRouteState(- route: object,- snapshot: Record<string, unknown>,-): void {- for (const key of Object.keys(route)) {- if (!(key in snapshot)) {- delete (route as Record<string, unknown>)[key];- }- }- Object.assign(route, snapshot);-}--/**- * Captured exactly once, at module scope, the instant this line of top-level code runs — which is- * before any `test()` body in this file has had a chance to run. That timing, not any claim about- * the route being untouched, is what makes this the right fixed point.- *- * It is deliberately NOT described as "pristine in the absolute". `AgentsRoute` gains its derived- * keys (`_id`, `_fullPath`, `parentRoute`, ...) when `route.init()` runs, which `createRouter()`- * triggers — and that is NOT confined to this file: `app/src/router.tsx` calls `createRouter()` at- * module top level over the generated `routeTree`, which contains this very route, so merely- * importing it initialises `AgentsRoute`. `app/tests/router.test.ts` imports it, and bun runs every- * file in one process, so depending on file order this constant may capture a route that the real- * router has already initialised.- *- * That is fine, and it is the point: what this has to restore is the state the route was in before- * THIS file interfered with it, whatever that state was. Either way the rest of the process gets- * back exactly what it had. A snapshot taken in `beforeEach` instead — as this used to do — would- * be reading the *live*, already-rendered-on `AgentsRoute` from test two onward, which is exactly- * how a broken `restoreRouteState` (one that merges but never deletes the stray keys a render adds)- * went undetected: each test's "before" picture already had last test's leak baked in as normal.- *- * `captureRouteState` is called again on this constant, rather than using it directly, everywhere- * below it is needed. `restoreRouteState`'s `Object.assign(route, snapshot)` step aliases- * `route.options` to `snapshot.options` — not a clone — and `Route.update()` mutates `this.options`- * in place. Handing the very same object out of every `beforeEach` would let the next render's- * `.update()` mutate this "pristine" constant through that alias, corrupting the one fixed point- * this whole scheme depends on. Re-running it through `captureRouteState` produces a fresh- * `options` clone each time, so the constant itself is never written to after this line.- */-const pristineAgentsRouteState = captureRouteState(AgentsRoute);--let agentsRouteSnapshot: Record<string, unknown>;--beforeEach(() => {- agentsRouteSnapshot = captureRouteState(pristineAgentsRouteState);-});--afterEach(() => {- restoreRouteState(AgentsRoute, agentsRouteSnapshot);-});--function renderAgents(queryClient: QueryClient) {- const rootRoute = createRootRoute({ component: Outlet });- const authedRoute = createRoute({- id: "/_authed",- getParentRoute: () => rootRoute,- component: Outlet,- });- const appRoute = createRoute({- id: "/_app",- getParentRoute: () => authedRoute,- component: Outlet,- });- const wired = (- AgentsRoute as unknown as {- update: (options: unknown) => typeof AgentsRoute;- }- ).update({- id: "/agents/",- path: "/agents/",- getParentRoute: () => appRoute,- });- const tree = rootRoute.addChildren([- authedRoute.addChildren([appRoute.addChildren([wired])]),- ]);- const router = createRouter({- routeTree: tree,- history: createMemoryHistory({ initialEntries: ["/agents"] }),- });- return render(- <QueryClientProvider client={queryClient}>- <RouterProvider router={router as never} />- </QueryClientProvider>,- );-}--test("a failed roster on /agents reports the failure, not an empty roster", async () => {- const view = renderAgents(failingQueryClient());-- expect(await view.findByText("Your agents couldn't be loaded.")).toBeTruthy();- expect(- await view.findByText("Agents shared with you couldn't be loaded."),- ).toBeTruthy();-- // The whole point: a person with agents must never be told they have none because the request- // that would have proven otherwise never came back.- expect(view.queryByText("You don't have any agents created.")).toBeNull();- expect(- view.queryByText("Nobody has shared an agent with you yet."),- ).toBeNull();-});-test("a failed roster on / reports the failure and explains the disabled composer", async () => {const view = renderHome(failingQueryClient());@@ -310,66 +162,6 @@ test("a failed roster on / reports the failure and explains the disabled compose).toBeTruthy();});-test("both /agents sections hold a skeleton while the roster is pending, not an empty state", async () => {- // A fetch that never settles is `isPending` forever — the state each section's loading arm- // renders once the router has finished its own (also async) initial match, which is why this- // still waits rather than reading `view.container` on the very next line.- global.fetch = (() =>- new Promise<Response>(() => {})) as unknown as typeof fetch;-- const view = renderAgents(failingQueryClient());-- const skeletons = await waitFor(() => {- const found = view.container.querySelectorAll('[data-slot="skeleton"]');- expect(found.length).toBe(2);- return found;- });- expect(skeletons.length).toBe(2);-- // A skeleton sitting beside a premature empty or error sentence would be no fix at all: the- // point is that loading reserves the section's height instead of claiming an answer it doesn't- // have yet.- expect(view.queryByText("You don't have any agents created.")).toBeNull();- expect(- view.queryByText("Nobody has shared an agent with you yet."),- ).toBeNull();- expect(view.queryByText("Your agents couldn't be loaded.")).toBeNull();- expect(- view.queryByText("Agents shared with you couldn't be loaded."),- ).toBeNull();-});--/*- * The three tests above all exercise a query that has NEVER succeeded: `isPending` and `isError`- * both come from a first attempt. TanStack Query keeps a query's last good `data` across a failed- * BACKGROUND refetch — the library's own comment on that code path reads "flag existing data as- * invalidated if we get a background error" — so `isError === true` beside a perfectly good,- * previously-loaded roster is an ordinary state, not the one the tests above cover. Both screens- * used to let `failed` outrank the populated-list check regardless of which of these two `isError`- * causes produced it, which replaced a working roster with an error card, and on `/` also showed an- * alert claiming the composer had nothing to send to while it was, in fact, still enabled.- */-test("a failed REFETCH on /agents keeps the roster it already had, not the error", async () => {- const mine = agent({ id: "mine-1", name: "Mine Agent", mine: true });- const shared = agent({- id: "shared-1",- name: "Shared Agent",- mine: false,- visibility: "public",- });- const queryClient = staleQueryClient([mine, shared]);-- const view = renderAgents(queryClient);- await waitForFailedRefetch(queryClient);-- expect(await view.findByText("Mine Agent")).toBeTruthy();- expect(await view.findByText("Shared Agent")).toBeTruthy();- expect(view.queryByText("Your agents couldn't be loaded.")).toBeNull();- expect(- view.queryByText("Agents shared with you couldn't be loaded."),- ).toBeNull();-});-test("a failed REFETCH on / keeps the roster and does not disclaim the composer", async () => {const shared = agent({id: "shared-1",@@ -412,133 +204,6 @@ test("a failed REFETCH on / keeps the roster and does not disclaim the composer"* sibling, right beside a section rendering real cards from that very same query. The real cards* are the proof: the response came back, and this slice of it is just empty.*/-test("a failed REFETCH on /agents with one empty slice shows it as empty, not broken", async () => {- const mine = agent({ id: "mine-1", name: "Mine Agent", mine: true });- const queryClient = staleQueryClient([mine]);-- const view = renderAgents(queryClient);- await waitForFailedRefetch(queryClient);-- expect(await view.findByText("Mine Agent")).toBeTruthy();- expect(- await view.findByText("Nobody has shared an agent with you yet."),- ).toBeTruthy();- expect(- view.queryByText("Agents shared with you couldn't be loaded."),- ).toBeNull();-});--test("a failed REFETCH on /agents with the other slice empty also shows it as empty", async () => {- const shared = agent({- id: "shared-1",- name: "Shared Agent",- mine: false,- visibility: "public",- });- const queryClient = staleQueryClient([shared]);-- const view = renderAgents(queryClient);- await waitForFailedRefetch(queryClient);-- expect(await view.findByText("Shared Agent")).toBeTruthy();- expect(- await view.findByText("You don't have any agents created."),- ).toBeTruthy();- expect(view.queryByText("Your agents couldn't be loaded.")).toBeNull();-});--/*- * Hiding a coworker takes it off both rosters, and Unhide is only in its dialog, which only a card- * opens. These serve the two list requests from their real URLs so the hidden roster arrives the- * way the server sends it: `GET /api/agents?hidden=true`.- */-function servingRosters(visible: AgentProfile[], hidden: AgentProfile[]) {- global.fetch = (async (input: RequestInfo | URL) => {- const url = String(input);- const agents = url.includes("hidden=true") ? hidden : visible;- return Response.json({ agents });- }) as unknown as typeof fetch;-}--test("a hidden coworker is on /agents under Hidden, collapsed, with a card that opens it", async () => {- const mine = agent({ id: "mine-1", name: "Mine Agent" });- const tucked = agent({ id: "hidden-1", name: "Tucked Agent", hidden: true });- servingRosters([mine], [tucked]);-- const view = renderAgents(failingQueryClient());-- expect(await view.findByText("Hidden")).toBeTruthy();- const section = view.container.querySelector("details");- expect(section).not.toBeNull();- // Collapsed until asked for, so it does not push the two rosters apart.- expect(section?.open).toBe(false);- // Inside the section rather than in either roster above it.- expect(section?.textContent).toContain("Tucked Agent");- expect(section?.textContent).not.toContain("Mine Agent");- // The card's own Details link is the way to the dialog that holds Unhide.- const link = view.getByLabelText("View details for Tucked Agent");- expect(link.getAttribute("href")).toBe("/agents?agent=hidden-1");-});--test("with nothing hidden, /agents has no Hidden section at all", async () => {- servingRosters([agent({ id: "mine-1", name: "Mine Agent" })], []);- const queryClient = failingQueryClient();-- const view = renderAgents(queryClient);-- expect(await view.findByText("Mine Agent")).toBeTruthy();- // Absent because the hidden roster came back empty, not because it has not come back yet.- await waitFor(() => {- expect(queryClient.getQueryState(agentKeys.list(true))?.status).toBe(- "success",- );- });- expect(view.queryByText("Hidden")).toBeNull();- expect(view.container.querySelector("details")).toBeNull();-});--test("a pinned coworker moves into Pinned at the top, out of its roster", async () => {- const kept = agent({ id: "mine-1", name: "Kept Agent" });- const favourite = agent({ id: "mine-2", name: "Favourite", pinned: true });- servingRosters([kept, favourite], []);-- const view = renderAgents(failingQueryClient());-- expect(await view.findByText("Pinned")).toBeTruthy();- const headings = [...view.container.querySelectorAll("h2")].map(- (heading) => heading.textContent,- );- expect(headings).toEqual(["Pinned", "Your agents", "Explore agents"]);- // Once, in Pinned, rather than twice.- expect(view.getAllByText("Favourite")).toHaveLength(1);- const pinnedSection = view.getByText("Pinned").parentElement;- expect(pinnedSection?.textContent).toContain("Favourite");- expect(pinnedSection?.textContent).not.toContain("Kept Agent");-});--test("with every coworker of yours pinned, Your agents says so instead of claiming none", async () => {- servingRosters(- [agent({ id: "mine-1", name: "Favourite", pinned: true })],- [],- );-- const view = renderAgents(failingQueryClient());-- expect(- await view.findByText("Your agents are all pinned above."),- ).toBeTruthy();- expect(view.queryByText("You don't have any agents created.")).toBeNull();-});--test("with nothing pinned, /agents has no Pinned section", async () => {- servingRosters([agent({ id: "mine-1", name: "Mine Agent" })], []);-- const view = renderAgents(failingQueryClient());-- expect(await view.findByText("Mine Agent")).toBeTruthy();- expect(view.queryByText("Pinned")).toBeNull();-});-test("a failed REFETCH on / with explore empty shows it as empty, not broken", async () => {const mine = agent({ id: "mine-1", name: "Mine Agent", mine: true });const queryClient = staleQueryClient([mine]);@@ -564,112 +229,3 @@ test("a failed REFETCH on / with explore empty shows it as empty, not broken", a),).toBeNull();});--/**- * Proves the restore itself, rather than trusting the doc comment above it: it drives- * `captureRouteState`/`restoreRouteState` directly, sandwiched around a corruption that reproduces- * both halves of what `renderAgents` does to the singleton — the `.update()` merge that plants- * `id`/`path`/`getParentRoute`, and the `route.init()` call `createRouter()` makes for every route in- * a tree it builds, which is what actually derives `_id`/`_fullPath`/`_to`/`parentRoute` from those- * options. Checking inside a test's own body can never observe what that test's own `afterEach` did- * — the hook has not run yet at that point — so this calls `restoreRouteState` itself rather than- * waiting on a hook, which observes the exact same restore path `afterEach` uses without depending on- * bun's cross-test hook ordering.- *- * `before` is `pristineAgentsRouteState`, not a fresh `captureRouteState(AgentsRoute)` read here.- * This test runs last, after every `renderAgents()`-driven test before it has already rendered on- * (and had its `afterEach` "restore") the live singleton; reading `AgentsRoute` at this point trusts- * that every prior restore actually worked, which is the very thing under test here. Comparing- * against the one snapshot taken before any router ever touched the route is what turns a leaked key- * into a visible diff instead of two contaminated pictures agreeing with each other.- */-test("restoring after a decoy render leaves no trace on the exported Route singleton", () => {- const before = captureRouteState(pristineAgentsRouteState);-- const decoyParentRoute = { id: "/_app", fullPath: "/" };- const route = AgentsRoute as unknown as {- update: (options: unknown) => unknown;- init: (opts: { originalIndex: number }) => void;- };- route.update({- id: "/agents/",- path: "/agents/",- getParentRoute: () => decoyParentRoute,- });- route.init({ originalIndex: 0 });-- // Sanity check: the corruption actually took, so the restore below proves something.- expect((AgentsRoute as { parentRoute: unknown }).parentRoute).toBe(- decoyParentRoute,- );-- restoreRouteState(AgentsRoute, before);-- expect(captureRouteState(AgentsRoute)).toEqual(before);-});--/**- * The test above compares one `captureRouteState` snapshot against another. That is only as- * trustworthy as `captureRouteState`'s own `options` clone and `beforeEach`'s own re-clone off- * `pristineAgentsRouteState` — and this file has now shipped three separate breakages that drop- * one of those two clones. Each one aliases `pristineAgentsRouteState.options` to the live route's- * `options` object, so `Route.update()`'s in-place mutation reaches the "pristine" constant too.- * Once that happens, `before`'s own `options` in the test above is read off the very same corrupted- * constant that `AgentsRoute` gets restored to, so the two sides of that `toEqual` are corrupted in- * lockstep and agree with each other anyway — the assertion goes tautological and the suite stays- * green with the pristine constant silently ruined for the rest of the process.- *- * The only way to catch that is to anchor to something the corruption itself cannot drag along: an- * object-identity check against `pristineAgentsRouteState` itself, and a second identity check- * against a decoy value created fresh inside THIS test — neither is derived from- * `pristineAgentsRouteState` or `agentsRouteSnapshot` the way `before` is, so neither can be dragged- * into the corruption alongside them.- *- * The second anchor is deliberately NOT "these key names must be absent from `options`" (`id`,- * `path`, `getParentRoute`), even though those are the very keys this test's own decoy `.update()`- * plants: `app/src/routeTree.gen.ts` calls the REAL `AgentsRoute.update({ id: '/agents/', path:- * '/agents/', getParentRoute: () => AuthedAppRoute })` too, as part of wiring the real app router —- * see `app/src/router.tsx`. Whenever this file shares a bun process with anything that imports that- * real router (e.g. `router.test.ts`, or any component test that mounts the real app shell), those- * exact key names are legitimately present in the pristine state this file must restore, so- * asserting their bare absence goes red on correct code the moment file ordering changes — the very- * "not pristine in the absolute" trap `pristineAgentsRouteState`'s own doc comment warns about.- * Anchoring to a function reference this test just created sidesteps that: no real code, past or- * future, can ever hold a reference to it.- *- * This test drives the exact same decoy-and-restore sequence as the one above, but reads- * `agentsRouteSnapshot` — the real module-scope variable this test's own `beforeEach` already- * populated, the same one the real `afterEach` restores through — rather than taking a fresh- * snapshot of its own, so it is exercising the actual hook wiring rather than a stand-in for it.- */-test("the pristine snapshot's options is never the live route's, and a restore leaves no decoy behind — checked by identity, not against another snapshot", () => {- const decoyParentRoute = { id: "/_app", fullPath: "/" };- const decoyGetParentRoute = () => decoyParentRoute;- const route = AgentsRoute as unknown as {- update: (options: unknown) => unknown;- init: (opts: { originalIndex: number }) => void;- };- route.update({- id: "/agents/",- path: "/agents/",- getParentRoute: decoyGetParentRoute,- });- route.init({ originalIndex: 0 });-- restoreRouteState(AgentsRoute, agentsRouteSnapshot);-- const liveOptions = (- AgentsRoute as unknown as {- options: { getParentRoute?: unknown };- }- ).options;-- // Anchor 1 — identity, not a snapshot: the constant this whole file's restore promise rests on- // must never be the very object `Route.update()` writes into, restore or no restore.- expect(pristineAgentsRouteState.options).not.toBe(liveOptions);-- // Anchor 2 — identity against a value created fresh in this test, not a snapshot and not a key- // name: no real caller, past or future, can ever hold a reference to this closure, so its- // survival past the restore is unambiguous corruption either way.- expect(liveOptions.getParentRoute).not.toBe(decoyGetParentRoute);-});diff --git a/app/tests/approval-team-settings.test.tsx b/app/tests/approval-team-settings.test.tsxnew file mode 100644index 00000000..a2a18488--- /dev/null+++ b/app/tests/approval-team-settings.test.tsx@@ -0,0 +1,168 @@+import {+ afterAll,+ afterEach,+ beforeAll,+ beforeEach,+ expect,+ test,+} from "bun:test";+import { GlobalRegistrator } from "@happy-dom/global-registrator";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { cleanup, render, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { TeamApprovalSettings } from "@/components/approvals/team-settings";+import { settleReactWork } from "./settle-react-work";++/** Admin → Approvals: the team-wide controls and team rules, in one place for administrators. */++beforeAll(() => GlobalRegistrator.register());+afterEach(cleanup);+afterAll(async () => {+ await settleReactWork();+ GlobalRegistrator.unregister();+});++const originalFetch = global.fetch;+const sent: { path: string; method: string; body: unknown }[] = [];++const inbox = {+ enabled: false,+ requests: [+ {+ id: "request-1",+ status: "pending",+ createdAt: new Date().toISOString(),+ action: {+ botId: "Shopper",+ toolRef: "computer_click",+ effect: "write",+ scope: "shop.example",+ threadId: "thread",+ args: { element: "Pay now" },+ target: {},+ toolCallId: "pay-call",+ policy: {+ behaviour: "hand_off",+ source: "safety",+ reason:+ "Paying, purchasing or moving money is always done by the person.",+ },+ },+ },+ ],+ rules: [+ {+ id: "mine",+ botId: "*",+ toolRef: "mcp/gmail/*",+ effect: "*",+ scope: "*",+ behaviour: "allow",+ },+ ],+ teamRules: [+ {+ id: "locked",+ botId: "*",+ toolRef: "mcp/drive/share",+ effect: "*",+ scope: "*",+ behaviour: "ask",+ },+ ],+ preferences: { enabled: false, autoReview: false, hostCommands: "allow" },+ team: {+ enforceAutoReview: true,+ customRulesEnabled: true,+ hostCommandsCap: "ask",+ },+ hostCommands: "ask",+ questions: [],+};++beforeEach(() => {+ sent.length = 0;+ global.fetch = Object.assign(+ async (path: Parameters<typeof fetch>[0], init?: RequestInit) => {+ const url = String(path);+ if (init?.method && init.method !== "GET") {+ sent.push({+ path: url,+ method: init.method,+ body: init.body ? JSON.parse(String(init.body)) : undefined,+ });+ return Response.json({ ok: true });+ }+ if (url === "/api/approvals") return Response.json(inbox);+ if (url === "/api/approvals/shared-use")+ return Response.json({ requests: [] });+ if (url === "/api/me")+ return Response.json({+ user: { id: "me", email: "[email protected]", role: "admin" },+ });+ return new Response(null, { status: 404 });+ },+ { preconnect: originalFetch.preconnect },+ );+});+afterEach(() => {+ global.fetch = originalFetch;+});++function draw() {+ return render(+ <QueryClientProvider+ client={+ new QueryClient({ defaultOptions: { queries: { retry: false } } })+ }+ >+ <TeamApprovalSettings />+ </QueryClientProvider>,+ );+}++test("an administrator sets the team-wide controls", async () => {+ const view = draw();+ await view.findByText("Team settings");+ const user = userEvent.setup({ document });+ await user.click(+ view.getByRole("combobox", {+ name: "Commands on members' computers, at most",+ }),+ );+ await user.click(await view.findByRole("option", { name: "Never" }));+ await waitFor(() =>+ expect(sent).toContainEqual({+ path: "/api/approvals/team",+ method: "PATCH",+ body: { hostCommandsCap: "never" },+ }),+ );+ // Team rules only: a member's own rules are theirs, in Settings.+ expect(view.getAllByRole("button", { name: "Remove" }).length).toBe(1);+});++test("an administrator adds a team rule for every Bot", async () => {+ const view = draw();+ await view.findByText("Add a team rule");+ const user = userEvent.setup({ document });+ await user.click(view.getByRole("button", { name: /Add a team rule/ }));+ await user.type(+ await view.findByRole("textbox", { name: "Tool or app" }),+ "mcp/slack/*",+ );+ await user.click(view.getByRole("button", { name: "Save rule" }));+ await waitFor(() =>+ expect(sent).toContainEqual({+ path: "/api/approvals/team/rules",+ method: "POST",+ body: {+ botId: "*",+ toolRef: "mcp/slack/*",+ effect: "*",+ scope: "*",+ behaviour: "ask",+ },+ }),+ );+});diff --git a/app/tests/approvals-rules.test.tsx b/app/tests/approvals-rules.test.tsxindex 685124c8..60d9da29 100644--- a/app/tests/approvals-rules.test.tsx+++ b/app/tests/approvals-rules.test.tsx@@ -8,9 +8,22 @@ import {} from "bun:test";import { GlobalRegistrator } from "@happy-dom/global-registrator";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { cleanup, fireEvent, render, waitFor } from "@testing-library/react";+import {+ createMemoryHistory,+ createRootRoute,+ createRouter,+ RouterProvider,+} from "@tanstack/react-router";+import type { ReactNode } from "react";+import {+ cleanup,+ fireEvent,+ render,+ waitFor,+ within,+} from "@testing-library/react";import userEvent from "@testing-library/user-event";-import { ApprovalInbox } from "@/components/approvals/inbox";+import { ApprovalSettings } from "@/components/approvals/settings";import { InlineApproval } from "@/components/approvals/inline-approval";import {BrowserActivity,@@ -81,8 +94,16 @@ const inbox = {questions: [],};+/** Per-test changes to the inbox the server returns. */+let inboxOverride: Record<string, unknown> = {};+/** A refusal the server gives the next time a rule is added, or none. */+let refuseRule: string | null = null;+beforeEach(() => {sent.length = 0;+ inboxOverride = {};+ refuseRule = null;+ role = "user";global.fetch = Object.assign(async (path: Parameters<typeof fetch>[0], init?: RequestInit) => {const url = String(path);@@ -92,9 +113,17 @@ beforeEach(() => {method: init.method,body: init.body ? JSON.parse(String(init.body)) : undefined,});+ if (url === "/api/approvals/rules" && refuseRule) {+ const error = refuseRule;+ refuseRule = null;+ return Response.json({ error }, { status: 400 });+ }return Response.json({ ok: true });}- if (url === "/api/approvals") return Response.json(inbox);+ if (url === "/api/approvals")+ return Response.json({ ...inbox, ...inboxOverride });+ if (url.startsWith("/api/agents"))+ return Response.json({ agents: [{ id: "shopper-bot", name: "Shop" }] });if (url === "/api/me")return Response.json({user: { id: "me", email: "[email protected]", role },@@ -108,39 +137,30 @@ afterEach(() => {global.fetch = originalFetch;});-function draw() {+/** A screen in a router of one route, for the links it holds. */+function draw(screen: ReactNode = <ApprovalSettings />) {+ const router = createRouter({+ history: createMemoryHistory({ initialEntries: ["/"] }),+ routeTree: createRootRoute({ component: () => screen }),+ });return render(<QueryClientProviderclient={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>- <ApprovalInbox />+ <RouterProvider router={router as never} /></QueryClientProvider>,);}-test("a hand-off is marked done by the person, never allowed on their behalf", async () => {- const view = draw();- await view.findByText(/Handed to you: Paying/);- expect(view.queryByRole("button", { name: "Allow once" })).toBeNull();- fireEvent.click(view.getByRole("button", { name: "I did it myself" }));- await waitFor(() =>- expect(sent).toContainEqual({- path: "/api/approvals/request-1/decision",- method: "POST",- body: { decision: "handled" },- }),- );-});-test("team rules are locked for members, enforced auto-review is shown as required, and the host cap is named", async () => {- const view = draw();+ const view = draw(<ApprovalSettings />);await view.findByText("Ask before taking action (team rule)");const mine = view.getByRole("combobox", {name: "Behaviour for mcp/gmail/*",- }) as HTMLSelectElement;- expect(mine.value).toBe("allow");+ });+ expect(mine.textContent).toContain("Take action without asking");expect(view.getByText("Locked")).toBeTruthy();const review = view.getByRole("switch", { name: "Auto-review" });expect(review.getAttribute("aria-checked")).toBe("true");@@ -152,11 +172,15 @@ test("team rules are locked for members, enforced auto-review is shown as requir});test("a member changes a saved rule in place", async () => {- const view = draw();+ const view = draw(<ApprovalSettings />);const mine = await view.findByRole("combobox", {name: "Behaviour for mcp/gmail/*",});- fireEvent.change(mine, { target: { value: "hand_off" } });+ const user = userEvent.setup({ document });+ await user.click(mine);+ await user.click(+ await view.findByRole("option", { name: "Hand off to you" }),+ );await waitFor(() =>expect(sent).toContainEqual({path: "/api/approvals/rules/mine",@@ -170,21 +194,21 @@ test("a member changes a saved rule in place", async () => {});test("a member adds a rule with one of the four behaviours", async () => {- const view = draw();+ const view = draw(<ApprovalSettings />);await view.findByText("Add a rule");const user = userEvent.setup({ document });+ await user.click(view.getByRole("button", { name: /Add a rule/ }));await user.type(- view.getByRole("textbox", { name: "Tool or app" }),+ await view.findByRole("textbox", { name: "Tool or app" }),"mcp/slack/*",);- fireEvent.change(- view.getAllByRole("combobox", { name: "Behaviour" })[0] as HTMLElement,- {- target: { value: "pre_approved" },- },+ // Rules here apply to every Bot, so there is no Bot to name.+ expect(view.queryByRole("textbox", { name: "Bot" })).toBeNull();+ await user.click(view.getByRole("combobox", { name: "Behaviour" }));+ await user.click(+ await view.findByRole("option", { name: "Take action if pre-approved" }),);- const save = view.getByRole("button", { name: "Save rule" });- fireEvent.submit(save.closest("form") as HTMLFormElement);+ await user.click(view.getByRole("button", { name: "Save rule" }));await waitFor(() =>expect(sent).toContainEqual({path: "/api/approvals/rules",@@ -200,28 +224,130 @@ test("a member adds a rule with one of the four behaviours", async () => {);});-test("an administrator sets the team-wide controls", async () => {+test("a rule that is not saved keeps the dialog open, with what was typed and why", async () => {+ refuseRule = "That tool is not one a Bot can use.";+ const view = draw(<ApprovalSettings />);+ await view.findByText("Add a rule");+ const user = userEvent.setup({ document });+ await user.click(view.getByRole("button", { name: /Add a rule/ }));+ await user.type(+ await view.findByRole("textbox", { name: "Tool or app" }),+ "mcp/nowhere/*",+ );+ await user.click(view.getByRole("button", { name: "Save rule" }));+ const dialog = await view.findByRole("dialog");+ expect((await within(dialog).findByRole("alert")).textContent).toContain(+ "That tool is not one a Bot can use.",+ );+ expect(+ (+ within(dialog).getByRole("textbox", {+ name: "Tool or app",+ }) as HTMLInputElement+ ).value,+ ).toBe("mcp/nowhere/*");+ // Saved the second time, the dialog closes.+ await user.click(within(dialog).getByRole("button", { name: "Save rule" }));+ await waitFor(() => expect(view.queryByRole("dialog")).toBeNull());+ expect(+ sent.filter((request) => request.path === "/api/approvals/rules"),+ ).toHaveLength(2);+});++test("two rules for one tool are told apart by the rest of what they match, never cut short", async () => {+ inboxOverride = {+ rules: [+ {+ id: "anywhere",+ botId: "*",+ toolRef: "computer_click",+ effect: "*",+ scope: "*",+ behaviour: "ask",+ },+ {+ id: "one-site",+ botId: "*",+ toolRef: "computer_click",+ effect: "write",+ scope: "checkout.a-very-long-shop-name.example",+ behaviour: "allow",+ },+ ],+ };+ const view = draw(<ApprovalSettings />);+ const match = await view.findByText(+ "write on checkout.a-very-long-shop-name.example",+ );+ expect(match.className).toContain("line-clamp-none");+ // The tool stays the row's title.+ expect(view.getAllByText("computer_click")).toHaveLength(2);+});++test("with personal rules switched off by the team, they are shown as not applying and none can be added", async () => {+ inboxOverride = {+ team: { ...inbox.team, customRulesEnabled: false },+ };+ const view = draw(<ApprovalSettings />);+ expect(await view.findByText(/kept but do not apply/)).toBeTruthy();+ expect(view.queryByText("Add a rule")).toBeNull();+});++test("an administrator is told where team settings are", async () => {role = "admin";- try {- const view = draw();- await view.findByText("Team settings");- fireEvent.change(- view.getByRole("combobox", {- name: "Commands on members' computers, at most",- }),- { target: { value: "never" } },- );- await waitFor(() =>- expect(sent).toContainEqual({- path: "/api/approvals/team",- method: "PATCH",- body: { hostCommandsCap: "never" },- }),- );- expect(view.getAllByRole("button", { name: "Remove" }).length).toBe(2);- } finally {- role = "user";- }+ const view = draw(<ApprovalSettings />);+ const link = await view.findByRole("link", { name: "Admin → Approvals" });+ expect(link.getAttribute("href")).toBe("/admin/approvals");+});++test("a member is not pointed at Admin", async () => {+ const view = draw(<ApprovalSettings />);+ await view.findByText("Rules for every Bot");+ expect(view.queryByRole("link", { name: "Admin → Approvals" })).toBeNull();+});++test("rules for every Bot point to where rules for a single Bot are", async () => {+ inboxOverride = {+ rules: [+ ...inbox.rules,+ {+ id: "one-bot",+ botId: "shopper-bot",+ toolRef: "computer_click",+ effect: "*",+ scope: "*",+ behaviour: "ask",+ },+ ],+ };+ const view = draw(<ApprovalSettings />);+ const link = await view.findByRole("link", { name: "that Bot's page" });+ expect(link.getAttribute("href")).toBe("/bots");+ // A rule naming one Bot lives on that Bot's page, not here.+ expect(+ view.queryByRole("combobox", { name: "Behaviour for computer_click" }),+ ).toBeNull();+});++test("a rule naming no Bot this person can open is listed so it can be removed", async () => {+ inboxOverride = {+ rules: [+ ...inbox.rules,+ {+ id: "orphan",+ botId: "Shopper",+ toolRef: "computer_click",+ effect: "*",+ scope: "*",+ behaviour: "allow",+ },+ ],+ };+ const view = draw(<ApprovalSettings />);+ expect(await view.findByText("Rules for other Bots")).toBeTruthy();+ expect(+ view.getByRole("combobox", { name: "Behaviour for computer_click" }),+ ).toBeTruthy();});test("a pending change is drawn in the conversation where the action was, and decided there", async () => {diff --git a/app/tests/bot-access-skills.test.tsx b/app/tests/bot-access-skills.test.tsxnew file mode 100644index 00000000..f8bab068--- /dev/null+++ b/app/tests/bot-access-skills.test.tsx@@ -0,0 +1,164 @@+import { afterAll, afterEach, beforeAll, expect, test } from "bun:test";+import { GlobalRegistrator } from "@happy-dom/global-registrator";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import {+ createMemoryHistory,+ createRootRoute,+ createRouter,+ RouterProvider,+} from "@tanstack/react-router";+import { cleanup, fireEvent, render, waitFor } from "@testing-library/react";+import { AccessSections } from "@/components/bot-profile/access";+import type { AgentProfile } from "@/lib/agents/queries";+import { settleReactWork } from "./settle-react-work";++/**+ * A Bot's Skills and access page. A person may put their own skill on a Bot they own, and only+ * that, so the switches are their own skills on their own Bot.+ */++beforeAll(() => GlobalRegistrator.register());+afterEach(cleanup);+afterAll(async () => {+ await settleReactWork();+ GlobalRegistrator.unregister();+});++const originalFetch = global.fetch;+afterEach(() => {+ global.fetch = originalFetch;+});++const BOT: AgentProfile = {+ id: "expenses",+ name: "Expenses",+ title: "Finance",+ roleDescription: "Receipts.",+ avatarSeed: "e",+ visibility: "private",+ endpoint: null,+ builtIn: true,+ hasAuth: false,+ hasCallbackToken: false,+ hidden: false,+ pinned: false,+ systemOwned: false,+ canManage: true,+ mine: true,+};++const skill = (+ slug: string,+ ownerUserId: string | null,+ grantedTo: string[],+) => ({+ id: slug,+ slug,+ ownerUserId,+ title: slug,+ summary: `${slug} summary`,+ instructions: "",+ origin: "user",+ installedBy: null,+ grantedTo,+ tools: [],+});++const grants: string[] = [];+function serving() {+ grants.length = 0;+ global.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ if (url.includes("/api/plugins/grants")) {+ grants.push(`${init?.method ?? "GET"} ${url} ${init?.body ?? ""}`);+ return Response.json({ ok: true });+ }+ if (url.includes("/api/plugins/for/")) {+ return Response.json({ tools: [], skills: [] });+ }+ if (url.endsWith("/api/plugins")) {+ return Response.json({+ catalogue: [],+ servers: [],+ botsMayCallBack: true,+ redirectUri: null,+ skills: [+ skill("mine-on", "me", ["expenses"]),+ skill("mine-off", "me", []),+ skill("theirs", "other", []),+ ],+ });+ }+ if (url.includes("/handoff")) {+ return Response.json({+ handoff: {+ enabled: true,+ canGrant: false,+ reachable: [],+ grantable: true,+ },+ });+ }+ if (url.includes("/api/agents")) return Response.json({ agents: [] });+ return Response.json({+ user: { id: "me", role: "user", email: "[email protected]", name: "Me" },+ });+ }) as unknown as typeof fetch;+}++function draw(agent: AgentProfile) {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ const router = createRouter({+ history: createMemoryHistory({ initialEntries: ["/"] }),+ routeTree: createRootRoute({+ component: () => <AccessSections agent={agent} />,+ }),+ });+ return render(+ <QueryClientProvider client={client}>+ <RouterProvider router={router as never} />+ </QueryClientProvider>,+ );+}++test("your own skills each have a switch that reflects whether this Bot carries it", async () => {+ serving();+ const view = draw(BOT);+ const on = await view.findByRole("switch", { name: "mine-on" });+ const off = view.getByRole("switch", { name: "mine-off" });+ expect(on.getAttribute("aria-checked")).toBe("true");+ expect(off.getAttribute("aria-checked")).toBe("false");+ // Somebody else's skill is not offered: the server would refuse it.+ expect(view.queryByRole("switch", { name: "theirs" })).toBeNull();+});++test("switching a skill on grants it to this Bot", async () => {+ serving();+ const view = draw(BOT);+ fireEvent.click(await view.findByRole("switch", { name: "mine-off" }));+ await waitFor(() => expect(grants).toHaveLength(1));+ expect(grants[0]).toContain("POST");+ expect(grants[0]).toContain("mine-off");+ expect(grants[0]).toContain("expenses");+});++test("on a Bot that is not yours there are no skill switches", async () => {+ serving();+ const view = draw({ ...BOT, mine: false, canManage: false });+ expect(await view.findByText(/^Nothing granted yet\./)).toBeTruthy();+ expect(view.queryByRole("switch")).toBeNull();+});++test("your skills failing to load says so, not that you have none", async () => {+ serving();+ const served = global.fetch;+ global.fetch = (async (input: RequestInfo | URL, init?: RequestInit) =>+ String(input).endsWith("/api/plugins")+ ? new Response(null, { status: 500 })+ : served(input, init)) as unknown as typeof fetch;+ const view = draw(BOT);+ expect(await view.findByText("Could not load your skills.")).toBeTruthy();+ expect(view.queryByText(/You have not written a skill yet/)).toBeNull();+});diff --git a/app/tests/bot-approval-rules.test.tsx b/app/tests/bot-approval-rules.test.tsxnew file mode 100644index 00000000..8c5d36d5--- /dev/null+++ b/app/tests/bot-approval-rules.test.tsx@@ -0,0 +1,151 @@+import { afterAll, afterEach, beforeAll, expect, test } from "bun:test";+import { GlobalRegistrator } from "@happy-dom/global-registrator";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import {+ createMemoryHistory,+ createRootRoute,+ createRouter,+ RouterProvider,+} from "@tanstack/react-router";+import { cleanup, render, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { BotApprovalRules } from "@/components/approvals/bot-rules";+import { settleReactWork } from "./settle-react-work";++/** A Bot's Approval rules page: the person's rules for this Bot, and the team rules that reach it. */++beforeAll(() => GlobalRegistrator.register());+afterEach(cleanup);+afterAll(async () => {+ await settleReactWork();+ GlobalRegistrator.unregister();+});++const originalFetch = global.fetch;+afterEach(() => {+ global.fetch = originalFetch;+});++const rule = (id: string, botId: string, toolRef: string) => ({+ id,+ botId,+ toolRef,+ effect: "*",+ scope: "*",+ behaviour: "ask",+});++const sent: { path: string; method: string; body: unknown }[] = [];+function serving() {+ sent.length = 0;+ global.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ if (init?.method && init.method !== "GET") {+ sent.push({+ path: url,+ method: init.method,+ body: init.body ? JSON.parse(String(init.body)) : undefined,+ });+ return Response.json({ ok: true });+ }+ return Response.json({+ enabled: true,+ requests: [],+ questions: [],+ rules: [+ rule("mine", "expenses", "mcp/gmail/*"),+ rule("other", "knowledge", "mcp/drive/*"),+ rule("every", "*", "mcp/slack/*"),+ ],+ teamRules: [+ rule("team-every", "*", "mcp/drive/share"),+ rule("team-expenses", "expenses", "computer_click"),+ rule("team-knowledge", "knowledge", "host/*"),+ ],+ preferences: { enabled: true, autoReview: false, hostCommands: "ask" },+ team: {+ enforceAutoReview: false,+ customRulesEnabled: true,+ hostCommandsCap: "allow",+ },+ hostCommands: "ask",+ });+ }) as unknown as typeof fetch;+}++function draw() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ const router = createRouter({+ history: createMemoryHistory({ initialEntries: ["/"] }),+ routeTree: createRootRoute({+ component: () => <BotApprovalRules agentId="expenses" />,+ }),+ });+ return render(+ <QueryClientProvider client={client}>+ <RouterProvider router={router as never} />+ </QueryClientProvider>,+ );+}++test("only this Bot's own rules can be changed, and the team rules that reach it are shown locked", async () => {+ serving();+ const view = draw();+ expect(+ await view.findByRole("combobox", { name: "Behaviour for mcp/gmail/*" }),+ ).toBeTruthy();+ expect(+ view.queryByRole("combobox", { name: "Behaviour for mcp/drive/*" }),+ ).toBeNull();+ expect(+ view.queryByRole("combobox", { name: "Behaviour for mcp/slack/*" }),+ ).toBeNull();+ expect(view.getByText("mcp/drive/share")).toBeTruthy();+ expect(view.getByText(/^computer_click/)).toBeTruthy();+ expect(view.queryByText(/^host\/\*/)).toBeNull();+});++test("a rule added here is for this Bot, with no Bot to type", async () => {+ serving();+ const view = draw();+ await view.findByText("Add a rule");+ const user = userEvent.setup({ document });+ await user.click(view.getByRole("button", { name: /Add a rule/ }));+ await user.type(+ await view.findByRole("textbox", { name: "Tool or app" }),+ "mcp/notion/*",+ );+ expect(view.queryByRole("textbox", { name: "Bot" })).toBeNull();+ await user.click(view.getByRole("button", { name: "Save rule" }));+ await waitFor(() =>+ expect(sent).toContainEqual({+ path: "/api/approvals/rules",+ method: "POST",+ body: {+ botId: "expenses",+ toolRef: "mcp/notion/*",+ effect: "*",+ scope: "*",+ behaviour: "ask",+ },+ }),+ );+});++test("a personal rule whose Bot is a pattern matching this Bot is shown and can be removed here", async () => {+ serving();+ const served = global.fetch;+ global.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {+ const response = await served(input, init);+ if (String(input) !== "/api/approvals" || init?.method) return response;+ const body = await response.json();+ body.rules.push(rule("pattern", "exp*", "mcp/linear/*"));+ return Response.json(body);+ }) as unknown as typeof fetch;+ const view = draw();+ expect(+ await view.findByRole("combobox", { name: "Behaviour for mcp/linear/*" }),+ ).toBeTruthy();+});diff --git a/app/tests/bot-manage.test.tsx b/app/tests/bot-manage.test.tsxnew file mode 100644index 00000000..c2b7323d--- /dev/null+++ b/app/tests/bot-manage.test.tsx@@ -0,0 +1,148 @@+import { afterAll, afterEach, beforeAll, expect, mock, test } from "bun:test";+import { GlobalRegistrator } from "@happy-dom/global-registrator";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { cleanup, fireEvent, render, waitFor } from "@testing-library/react";+import { ManageSection } from "@/components/bot-profile/manage";+import type { AgentProfile } from "@/lib/agents/queries";+import { settleReactWork } from "./settle-react-work";++/**+ * What can be done to a Bot from its own page. Navigation is the page's, so the section reports+ * where to go through callbacks, and these tests assert on those.+ */++beforeAll(() => GlobalRegistrator.register());+afterEach(cleanup);+afterAll(async () => {+ await settleReactWork();+ GlobalRegistrator.unregister();+});++const originalFetch = global.fetch;+afterEach(() => {+ global.fetch = originalFetch;+});++const BOT: AgentProfile = {+ id: "expenses",+ name: "Expenses",+ title: "Finance",+ roleDescription: "Review receipts.",+ avatarSeed: "expenses",+ visibility: "private",+ endpoint: null,+ builtIn: true,+ hasAuth: false,+ hasCallbackToken: false,+ hidden: false,+ pinned: false,+ systemOwned: false,+ canManage: true,+ mine: true,+};++const requests: string[] = [];+function serving() {+ requests.length = 0;+ global.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {+ requests.push(`${init?.method ?? "GET"} ${String(input)}`);+ if (String(input).endsWith("/duplicate")) {+ return Response.json({ agent: { ...BOT, id: "expenses-copy" } });+ }+ return Response.json({ agent: BOT });+ }) as unknown as typeof fetch;+}++function draw(+ agent: AgentProfile,+ handlers: {+ onHidden?: () => void;+ onDuplicated?: (copyId: string) => void;+ onDeleted?: () => void;+ } = {},+) {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return render(+ <QueryClientProvider client={client}>+ <ManageSection+ agent={agent}+ onDeleted={handlers.onDeleted ?? (() => {})}+ onDuplicated={handlers.onDuplicated ?? (() => {})}+ onHidden={handlers.onHidden ?? (() => {})}+ />+ </QueryClientProvider>,+ );+}++test("someone who cannot manage the Bot is not offered Delete", () => {+ const view = draw({ ...BOT, canManage: false, mine: false });+ expect(view.queryByText("Delete")).toBeNull();+ expect(view.getByText("Duplicate")).toBeTruthy();+});++test("hiding a Bot takes the person back to the roster", async () => {+ serving();+ const onHidden = mock(() => {});+ const view = draw(BOT, { onHidden });+ fireEvent.click(view.getByRole("switch", { name: "Hidden" }));+ await waitFor(() => expect(onHidden).toHaveBeenCalledTimes(1));+});++test("unhiding a hidden Bot keeps the person on its page", async () => {+ serving();+ const onHidden = mock(() => {});+ const view = draw({ ...BOT, hidden: true }, { onHidden });+ fireEvent.click(view.getByRole("switch", { name: "Hidden" }));+ await waitFor(() =>+ expect(requests.some((request) => request.startsWith("POST"))).toBe(true),+ );+ // Let the mutation settle before asserting nothing navigated.+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(onHidden).not.toHaveBeenCalled();+});++test("duplicating opens the copy", async () => {+ serving();+ const onDuplicated = mock((_copyId: string) => {});+ const view = draw(BOT, { onDuplicated });+ fireEvent.click(view.getByRole("button", { name: /Duplicate/ }));+ await waitFor(() =>+ expect(onDuplicated).toHaveBeenCalledWith("expenses-copy"),+ );+});++test("a Bot an administrator assigned to you reads as pinned and cannot be hidden or unpinned", () => {+ const view = draw({+ ...BOT,+ mine: false,+ canManage: false,+ assignedToMe: true,+ });+ const pinned = view.getByRole("switch", { name: "Pinned" });+ const hidden = view.getByRole("switch", { name: "Hidden" });+ expect(pinned.getAttribute("aria-checked")).toBe("true");+ expect(+ pinned.hasAttribute("disabled") ||+ pinned.getAttribute("aria-disabled") === "true",+ ).toBe(true);+ expect(+ hidden.hasAttribute("disabled") ||+ hidden.getAttribute("aria-disabled") === "true",+ ).toBe(true);+ expect(+ view.getAllByText(/Assigned to you by an administrator/).length,+ ).toBeGreaterThan(0);+});++test("rows that open a dialog show a chevron, and Duplicate, which acts at once, does not", () => {+ const view = draw(BOT);+ const chevron = (name: RegExp) =>+ view+ .getByRole("button", { name })+ .querySelector(".tabler-icon-chevron-right");+ expect(chevron(/^Reset/)).not.toBeNull();+ expect(chevron(/^Delete/)).not.toBeNull();+ expect(chevron(/^Duplicate/)).toBeNull();+});diff --git a/app/tests/bot-memory.test.tsx b/app/tests/bot-memory.test.tsxnew file mode 100644index 00000000..57f891c9--- /dev/null+++ b/app/tests/bot-memory.test.tsx@@ -0,0 +1,191 @@+import { afterAll, afterEach, beforeAll, expect, test } from "bun:test";+import { GlobalRegistrator } from "@happy-dom/global-registrator";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { cleanup, render, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import type { ReactNode } from "react";+import { MemorySources } from "@/components/memory/sources";+import { ProactiveResearchSettings } from "@/components/suggestions/proactive-panel";+import { settleReactWork } from "./settle-react-work";++/** A Bot's Memory page: the apps that feed it facts, and its background research. */++beforeAll(() => GlobalRegistrator.register());+afterEach(cleanup);+afterAll(async () => {+ await settleReactWork();+ GlobalRegistrator.unregister();+});++const originalFetch = global.fetch;+afterEach(() => {+ global.fetch = originalFetch;+});++const source = (id: string, agentId: string, title: string) => ({+ id,+ title,+ agentId,+ toolRef: "mcp/drive/search",+ enabled: true,+ syncStatus: "succeeded",+ syncError: null,+ lastSyncAt: null,+});++const research = (id: string, agentId: string, focus: string) => ({+ id,+ agentId,+ channelId: `channel-${agentId}`,+ focus,+ enabled: true,+ intervalMinutes: 240,+ nextRunAt: "2026-10-09T12:00:00Z",+ lastRunAt: null,+ lastStatus: "idle",+ lastError: null,+});++const requested: string[] = [];+/** A refusal the server gives the next write, or none. */+let refuseWrite: string | null = null;+/** The settings the Drive search action takes. */+let searchSettings: Record<string, unknown> = {};+function serving() {+ requested.length = 0;+ refuseWrite = null;+ searchSettings = {};+ global.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ requested.push(url);+ if (init?.method && init.method !== "GET") {+ if (refuseWrite) {+ const error = refuseWrite;+ refuseWrite = null;+ return Response.json({ error }, { status: 400 });+ }+ return Response.json({ ok: true });+ }+ if (url === "/api/memory/sources") {+ return Response.json({+ sources: [+ source("s1", "expenses", "Receipts folder"),+ source("s2", "knowledge", "Wiki pages"),+ ],+ });+ }+ if (url.startsWith("/api/memory/sources/available/")) {+ return Response.json({+ tools: [+ {+ ref: "mcp/drive/search",+ title: "Search Drive",+ description: "",+ inputSchema: { properties: searchSettings },+ },+ ],+ });+ }+ if (url === "/api/proactive/settings") {+ return Response.json({+ settings: [+ research("p1", "expenses", "Unpaid invoices"),+ research("p2", "knowledge", "Stale pages"),+ ],+ });+ }+ if (url.startsWith("/api/channels")) {+ return Response.json({ channels: [], nextCursor: null });+ }+ return Response.json({+ agents: [+ { id: "expenses", name: "Expenses" },+ { id: "knowledge", name: "Knowledge" },+ ],+ });+ }) as unknown as typeof fetch;+}++function draw(node: ReactNode) {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return render(+ <QueryClientProvider client={client}>{node}</QueryClientProvider>,+ );+}++test("only this Bot's sources are listed, and its app actions load without picking a Bot", async () => {+ serving();+ const view = draw(<MemorySources agentId="expenses" />);+ expect(await view.findByText("Receipts folder")).toBeTruthy();+ expect(view.queryByText("Wiki pages")).toBeNull();+ expect(view.queryByRole("combobox", { name: /^Bot/ })).toBeNull();+ await waitFor(() =>+ expect(requested).toContain("/api/memory/sources/available/expenses"),+ );+});++test("only this Bot's background research is listed, with no Bot to pick", async () => {+ serving();+ const view = draw(<ProactiveResearchSettings agentId="expenses" />);+ expect(await view.findByText(/Unpaid invoices/)).toBeTruthy();+ expect(view.queryByText(/Stale pages/)).toBeNull();+ expect(view.queryByRole("combobox", { name: /^Bot/ })).toBeNull();+});++/** Opens Add source for the Expenses Bot and chooses its one read action. */+async function openAddSource(view: ReturnType<typeof draw>) {+ const user = userEvent.setup({ document });+ await view.findByText("Receipts folder");+ await user.click(view.getByRole("button", { name: "Add source" }));+ await user.click(+ await view.findByRole("combobox", { name: "Connected app action" }),+ );+ await user.click(await view.findByRole("option", { name: "Search Drive" }));+ return user;+}++test("an action setting called name is its own field, not the source name", async () => {+ serving();+ searchSettings = { name: { type: "string" } };+ const view = draw(<MemorySources agentId="expenses" />);+ await openAddSource(view);+ const setting = await view.findByLabelText("name");+ expect(setting).not.toBe(view.getByLabelText("Source name"));+});++test("reopening Add source after a failure keeps the draft but not the failure", async () => {+ serving();+ const view = draw(<MemorySources agentId="expenses" />);+ const user = await openAddSource(view);+ await user.type(view.getByLabelText("Source name"), "Invoices");+ refuseWrite = "That folder cannot be read.";+ await user.click(view.getByRole("button", { name: "Add and sync source" }));+ expect((await view.findByRole("alert")).textContent).toBe(+ "That folder cannot be read.",+ );+ await user.keyboard("{Escape}");+ await waitFor(() => expect(view.queryByRole("dialog")).toBeNull());+ await user.click(view.getByRole("button", { name: "Add source" }));+ const name = (await view.findByLabelText("Source name")) as HTMLInputElement;+ expect(name.value).toBe("Invoices");+ expect(view.queryByRole("alert")).toBeNull();+});++test("reopening a research row after a failure starts without it", async () => {+ serving();+ const view = draw(<ProactiveResearchSettings agentId="expenses" />);+ const user = userEvent.setup({ document });+ await user.click(await view.findByRole("button", { name: /Expenses/ }));+ refuseWrite = "Research is paused.";+ await user.click(await view.findByRole("button", { name: "Run now" }));+ expect((await view.findByRole("alert")).textContent).toBe(+ "Research is paused.",+ );+ await user.keyboard("{Escape}");+ await waitFor(() => expect(view.queryByRole("dialog")).toBeNull());+ await user.click(view.getByRole("button", { name: /Expenses/ }));+ await view.findByRole("button", { name: "Run now" });+ expect(view.queryByRole("alert")).toBeNull();+});diff --git a/app/tests/bot-needs-you.test.tsx b/app/tests/bot-needs-you.test.tsxnew file mode 100644index 00000000..487ce527--- /dev/null+++ b/app/tests/bot-needs-you.test.tsx@@ -0,0 +1,245 @@+import { afterAll, afterEach, beforeAll, expect, test } from "bun:test";+import { GlobalRegistrator } from "@happy-dom/global-registrator";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { cleanup, fireEvent, render, waitFor } from "@testing-library/react";+import type { ReactNode } from "react";+import { BotNeedsYou } from "@/components/approvals/waiting";+import { SuggestionsInbox } from "@/components/suggestions/proactive-panel";+import { settleReactWork } from "./settle-react-work";++/**+ * The top of a Bot's page: what that Bot is waiting on the person for, decided right there, and the+ * next steps its background research suggested.+ */++beforeAll(() => GlobalRegistrator.register());+afterEach(cleanup);+afterAll(async () => {+ await settleReactWork();+ GlobalRegistrator.unregister();+});++const originalFetch = global.fetch;+afterEach(() => {+ global.fetch = originalFetch;+});++const request = (+ id: string,+ botId: string,+ behaviour: "ask" | "hand_off" = "ask",+) => ({+ id,+ status: "pending",+ createdAt: "2026-10-09T10:00:00Z",+ action: {+ botId,+ toolRef: "computer_click",+ effect: "write",+ scope: "shop.example",+ threadId: "thread",+ args: { element: "Pay now" },+ target: {},+ policy: {+ behaviour,+ source: "rule",+ reason: behaviour === "hand_off" ? "Paying is done by you." : "Asked.",+ },+ },+});++let inbox: Record<string, unknown> = {};+const sent: { path: string; method: string; body: unknown }[] = [];+function serving() {+ sent.length = 0;+ global.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ if (init?.method && init.method !== "GET") {+ sent.push({+ path: url,+ method: init.method,+ body: init.body ? JSON.parse(String(init.body)) : undefined,+ });+ return Response.json({ ok: true });+ }+ if (url === "/api/approvals") return Response.json(inbox);+ if (url === "/api/proactive/suggestions") {+ return Response.json({+ suggestions: [+ {+ id: "s1",+ agentId: "expenses",+ title: "Chase the March invoice",+ detail: "",+ sourceApp: null,+ sourceLink: null,+ createdAt: "2026-10-09T10:00:00Z",+ },+ {+ id: "s2",+ agentId: "knowledge",+ title: "Archive old pages",+ detail: "",+ sourceApp: null,+ sourceLink: null,+ createdAt: "2026-10-09T10:00:00Z",+ },+ ],+ });+ }+ return Response.json({+ agents: [+ { id: "expenses", name: "Expenses" },+ { id: "knowledge", name: "Knowledge" },+ ],+ });+ }) as unknown as typeof fetch;+}++function draw(node: ReactNode) {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return render(+ <QueryClientProvider client={client}>{node}</QueryClientProvider>,+ );+}++const base = {+ enabled: true,+ rules: [],+ teamRules: [],+};++test("the target of a waiting action is shown whole, however long", async () => {+ const long = request("r1", "expenses");+ long.action.scope =+ "https://checkout.example/carts/0f8e2a4c-9b1d-4f6e-a3c7-5d2e8b1f9a04/pay";+ inbox = { ...base, requests: [long], questions: [] };+ serving();+ const view = draw(<BotNeedsYou agentId="expenses" />);+ const scope = await view.findByText(long.action.scope);+ expect(scope.className).toContain("line-clamp-none");+ expect(scope.className).toContain("break-all");+});++test("only what this Bot waits on is shown, and it can be decided here", async () => {+ inbox = {+ ...base,+ requests: [request("r1", "expenses"), request("r2", "knowledge")],+ questions: [+ {+ id: "q1",+ botId: "expenses",+ threadId: "thread",+ question: "Which card?",+ createdAt: "2026-10-09T10:00:00Z",+ },+ {+ id: "q2",+ botId: "knowledge",+ threadId: "thread",+ question: "Which wiki?",+ createdAt: "2026-10-09T10:00:00Z",+ },+ ],+ };+ serving();+ const view = draw(<BotNeedsYou agentId="expenses" />);+ expect(await view.findByText("Needs you")).toBeTruthy();+ expect(view.getByText(/Which card\?/)).toBeTruthy();+ expect(view.queryByText(/Which wiki\?/)).toBeNull();+ expect(view.getAllByRole("button", { name: "Allow once" })).toHaveLength(1);+ expect(view.getByRole("button", { name: "Always allow here" })).toBeTruthy();+ expect(view.getByRole("button", { name: "Deny" })).toBeTruthy();+ expect(view.getByRole("button", { name: "Send answer" })).toBeTruthy();+ fireEvent.click(view.getByRole("button", { name: "Allow once" }));+ await waitFor(() =>+ expect(sent).toContainEqual({+ path: "/api/approvals/r1/decision",+ method: "POST",+ body: { decision: "allow_once" },+ }),+ );+});++test("a hand-off is marked done by the person, never allowed on their behalf", async () => {+ inbox = {+ ...base,+ requests: [request("r1", "expenses", "hand_off")],+ questions: [],+ };+ serving();+ const view = draw(<BotNeedsYou agentId="expenses" />);+ await view.findByText(/Handed to you: Paying/);+ expect(view.queryByRole("button", { name: "Allow once" })).toBeNull();+ fireEvent.click(view.getByRole("button", { name: "I did it myself" }));+ await waitFor(() =>+ expect(sent).toContainEqual({+ path: "/api/approvals/r1/decision",+ method: "POST",+ body: { decision: "handled" },+ }),+ );+});++test("with nothing waiting on the person, the section is not drawn", async () => {+ inbox = { ...base, requests: [request("r2", "knowledge")], questions: [] };+ serving();+ const view = draw(<BotNeedsYou agentId="expenses" />);+ await new Promise((resolve) => setTimeout(resolve, 100));+ expect(view.queryByText("Needs you")).toBeNull();+});++test("only this Bot's suggestions are shown", async () => {+ inbox = { ...base, requests: [], questions: [] };+ serving();+ const view = draw(<SuggestionsInbox agentId="expenses" />);+ expect(await view.findByText(/Chase the March invoice/)).toBeTruthy();+ expect(view.queryByText(/Archive old pages/)).toBeNull();+});++test("a question asked during a hand-off is on the page of the Bot whose conversation it is", async () => {+ inbox = {+ ...base,+ requests: [],+ questions: [+ {+ id: "q1",+ botId: "knowledge",+ conversationBotId: "expenses",+ threadId: "thread",+ question: "Which ledger?",+ createdAt: "2026-10-09T10:00:00Z",+ },+ ],+ };+ serving();+ const handedOn = draw(<BotNeedsYou agentId="expenses" />);+ expect(await handedOn.findByText(/Which ledger\?/)).toBeTruthy();+ cleanup();+ const asked = draw(<BotNeedsYou agentId="knowledge" />);+ await new Promise((resolve) => setTimeout(resolve, 100));+ expect(asked.queryByText(/Which ledger\?/)).toBeNull();+});++test("with only a question waiting, Needs you says nothing about approvals and has one heading", async () => {+ inbox = {+ ...base,+ requests: [],+ questions: [+ {+ id: "q1",+ botId: "expenses",+ threadId: "thread",+ question: "Which card?",+ createdAt: "2026-10-09T10:00:00Z",+ },+ ],+ };+ serving();+ const view = draw(<BotNeedsYou agentId="expenses" />);+ await view.findByText(/Which card\?/);+ expect(view.queryByText("No actions need your approval.")).toBeNull();+ expect(view.queryByText("Waiting for you")).toBeNull();+});diff --git a/app/tests/bot-profile-active.test.tsx b/app/tests/bot-profile-active.test.tsxnew file mode 100644index 00000000..c3838547--- /dev/null+++ b/app/tests/bot-profile-active.test.tsx@@ -0,0 +1,131 @@+import { afterAll, afterEach, beforeAll, expect, test } from "bun:test";+import { GlobalRegistrator } from "@happy-dom/global-registrator";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import {+ createMemoryHistory,+ createRootRoute,+ createRouter,+ RouterProvider,+} from "@tanstack/react-router";+import { cleanup, fireEvent, render } from "@testing-library/react";+import { BotProfile } from "@/components/bot-profile/profile";+import type { AgentProfile } from "@/lib/agents/queries";+import { settleReactWork } from "./settle-react-work";++/**+ * The Bot page's pause control reads the way its switch sits: titled "Active" and on while the Bot+ * runs, off once it is paused. Titled "Paused", it showed the word "Paused" beside an off switch+ * for a Bot that was running.+ */++beforeAll(() => GlobalRegistrator.register());+afterEach(cleanup);+afterAll(async () => {+ await settleReactWork();+ GlobalRegistrator.unregister();+});++const originalFetch = global.fetch;+afterEach(() => {+ global.fetch = originalFetch;+});++const BOT: AgentProfile = {+ id: "expenses",+ name: "Expenses",+ title: "Finance",+ roleDescription: "Receipts.",+ avatarSeed: "e",+ visibility: "private",+ endpoint: null,+ builtIn: true,+ hasAuth: false,+ hasCallbackToken: false,+ hidden: false,+ pinned: false,+ systemOwned: false,+ canManage: true,+ mine: true,+};++function serving(paused: boolean, writes: string[] = []) {+ global.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ if (init?.method === "POST" && /\/(pause|resume)$/.test(url)) {+ writes.push(url.endsWith("/pause") ? "pause" : "resume");+ return Response.json({+ lifecycle: {+ agentId: "expenses",+ paused: url.endsWith("/pause"),+ pausedAt: null,+ notify: "all",+ },+ });+ }+ if (url.endsWith("/lifecycle")) {+ return Response.json({+ lifecycle: {+ agentId: "expenses",+ paused,+ pausedAt: paused ? "2026-10-09T00:00:00.000Z" : null,+ notify: "all",+ },+ });+ }+ if (url.includes("/shared-use/bot/")) {+ return Response.json({ apps: [], pending: [] });+ }+ if (url.includes("/api/me")) {+ return Response.json({+ user: { id: "me", role: "user", email: "[email protected]", name: "Me" },+ });+ }+ return new Response(null, { status: 404 });+ }) as unknown as typeof fetch;+}++function draw(agent: AgentProfile) {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ const router = createRouter({+ history: createMemoryHistory({ initialEntries: ["/"] }),+ routeTree: createRootRoute({+ component: () => <BotProfile agent={agent} />,+ }),+ });+ return render(+ <QueryClientProvider client={client}>+ <RouterProvider router={router as never} />+ </QueryClientProvider>,+ );+}++const checked = (element: HTMLElement) =>+ element.getAttribute("aria-checked") === "true" ||+ element.hasAttribute("data-checked");++test("a running Bot's row says Active and its switch is on", async () => {+ serving(false);+ const view = draw(BOT);+ const control = await view.findByRole("switch", { name: "Active" });+ expect(checked(control)).toBe(true);+ expect(view.queryByText("Paused")).toBeNull();+});++test("a paused Bot's Active switch is off, and the row says it is paused", async () => {+ serving(true);+ const view = draw(BOT);+ const control = await view.findByRole("switch", { name: "Active" });+ expect(checked(control)).toBe(false);+ expect(await view.findByText(/^Paused\. No routine/)).toBeTruthy();+});++test("switching a running Bot off pauses it", async () => {+ const writes: string[] = [];+ serving(false, writes);+ const view = draw(BOT);+ fireEvent.click(await view.findByRole("switch", { name: "Active" }));+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(writes).toEqual(["pause"]);+});diff --git a/app/tests/bot-profile-notice.test.tsx b/app/tests/bot-profile-notice.test.tsxnew file mode 100644index 00000000..e08a8317--- /dev/null+++ b/app/tests/bot-profile-notice.test.tsx@@ -0,0 +1,115 @@+import { afterAll, afterEach, beforeAll, expect, test } from "bun:test";+import { GlobalRegistrator } from "@happy-dom/global-registrator";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import {+ createMemoryHistory,+ createRootRoute,+ createRouter,+ RouterProvider,+} from "@tanstack/react-router";+import { cleanup, render } from "@testing-library/react";+import { BotProfile } from "@/components/bot-profile/profile";+import type { AgentProfile } from "@/lib/agents/queries";+import { settleReactWork } from "./settle-react-work";++/**+ * A Bot whose Shared-app calls are being refused right now says so on its own page, to whoever may+ * manage it: the refusal is about the Bot's present reach, not only about the moment of publishing.+ */++beforeAll(() => GlobalRegistrator.register());+afterEach(cleanup);+afterAll(async () => {+ await settleReactWork();+ GlobalRegistrator.unregister();+});++const originalFetch = global.fetch;+afterEach(() => {+ global.fetch = originalFetch;+});++const BOT: AgentProfile = {+ id: "expenses",+ name: "Expenses",+ title: "Finance",+ roleDescription: "Receipts.",+ avatarSeed: "e",+ visibility: "private",+ endpoint: null,+ builtIn: true,+ hasAuth: false,+ hasCallbackToken: false,+ hidden: false,+ pinned: false,+ systemOwned: false,+ canManage: true,+ mine: true,+};++function serving() {+ global.fetch = (async (input: RequestInfo | URL) => {+ const url = String(input);+ if (url.includes("/shared-use/bot/")) {+ return Response.json({+ apps: [{ serverId: "gmail", title: "Gmail", covered: false }],+ pending: [],+ });+ }+ if (url.endsWith("/lifecycle")) {+ return Response.json({+ lifecycle: {+ agentId: "expenses",+ paused: false,+ pausedAt: null,+ notify: "all",+ },+ });+ }+ if (url.includes("/api/me")) {+ return Response.json({+ user: { id: "me", role: "user", email: "[email protected]", name: "Me" },+ });+ }+ return new Response(null, { status: 404 });+ }) as unknown as typeof fetch;+}++function draw(agent: AgentProfile) {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ const router = createRouter({+ history: createMemoryHistory({ initialEntries: ["/"] }),+ routeTree: createRootRoute({+ component: () => <BotProfile agent={agent} />,+ }),+ });+ return render(+ <QueryClientProvider client={client}>+ <RouterProvider router={router as never} />+ </QueryClientProvider>,+ );+}++test("whoever manages the Bot is told its Shared-app calls are refused", async () => {+ serving();+ const view = draw(BOT);+ expect(+ await view.findByText(/Gmail calls from this Bot are refused/),+ ).toBeTruthy();+});++test("someone who cannot manage the Bot is not shown the warning", async () => {+ serving();+ const view = draw({ ...BOT, canManage: false, mine: false });+ await new Promise((resolve) => setTimeout(resolve, 100));+ expect(view.queryByText(/calls from this Bot are refused/)).toBeNull();+});++test("the Message row shows the chevron every row that goes somewhere carries", async () => {+ serving();+ const view = draw(BOT);+ const row = (await view.findByText("Message Expenses")).closest("a");+ expect(row?.querySelector(".tabler-icon-chevron-right")).not.toBeNull();+});diff --git a/app/tests/bot-reaching-you.test.tsx b/app/tests/bot-reaching-you.test.tsxnew file mode 100644index 00000000..3494013c--- /dev/null+++ b/app/tests/bot-reaching-you.test.tsx@@ -0,0 +1,234 @@+import { afterAll, afterEach, beforeAll, expect, test } from "bun:test";+import { GlobalRegistrator } from "@happy-dom/global-registrator";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { cleanup, render, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { ReachingYou } from "@/components/delivery/reaching-you";+import { settleReactWork } from "./settle-react-work";++/** A Bot's Reaching you page: where this Bot's conversations continue outside OpenBot. */++beforeAll(() => GlobalRegistrator.register());+afterEach(cleanup);+afterAll(async () => {+ await settleReactWork();+ GlobalRegistrator.unregister();+});++const originalFetch = global.fetch;+afterEach(() => {+ global.fetch = originalFetch;+});++const channel = (id: string, name: string, agentIds: string[]) => ({+ id,+ name,+ agentIds,+ active: true,+ summary: null,+ lastMessage: null,+ lastMessageAgentId: null,+ createdAt: "2026-10-09T10:00:00Z",+ pinned: false,+ lastReadAt: null,+});++const binding = (id: string, agentId: string, address: string) => ({+ id,+ transport: "slack",+ channelId: `channel-${agentId}`,+ agentId,+ address,+ enabled: true,+});++const writes: { request: string; body: unknown }[] = [];+function serving(sms = false) {+ writes.length = 0;+ global.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ const method = init?.method ?? "GET";+ if (method !== "GET") {+ writes.push({+ request: `${method} ${url}`,+ body: typeof init?.body === "string" ? JSON.parse(init.body) : null,+ });+ return Response.json({+ platform: "slack",+ code: "abc",+ command: "link abc",+ expiresInMinutes: 10,+ challengeId: "challenge-1",+ });+ }+ if (url.startsWith("/api/delivery")) {+ return Response.json({+ bindings: [+ binding("b1", "expenses", "finance-bot-dm"),+ binding("b2", "knowledge", "docs-bot-dm"),+ ],+ devices: [],+ deliveries: [],+ available: { slack: true, teams: false, sms, push: false },+ });+ }+ if (url.startsWith("/api/channels")) {+ return Response.json({+ channels: [+ channel("channel-expenses", "Finance desk", ["expenses"]),+ channel("channel-knowledge", "Docs desk", ["knowledge"]),+ ],+ nextCursor: null,+ });+ }+ return Response.json({+ agents: [+ { id: "expenses", name: "Expenses" },+ { id: "knowledge", name: "Knowledge" },+ ],+ });+ }) as unknown as typeof fetch;+}++function draw() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return render(+ <QueryClientProvider client={client}>+ <ReachingYou agentId="expenses" />+ </QueryClientProvider>,+ );+}++test("only this Bot's destinations are listed", async () => {+ serving();+ const view = draw();+ expect(await view.findByText(/^Slack/)).toBeTruthy();+ expect(view.getAllByRole("button", { name: "Disconnect" })).toHaveLength(1);+});++/** The link flow is a dialog: open it from its row, then choose the conversation it continues. */+async function openSlackLink(view: ReturnType<typeof draw>) {+ const user = userEvent.setup({ document });+ await view.findByRole("button", { name: "Disconnect" });+ await user.click(view.getByRole("button", { name: /^Link Slack/ }));+ return user;+}++async function chooseConversation(+ view: ReturnType<typeof draw>,+ user: ReturnType<typeof userEvent.setup>,+ name: string,+) {+ await user.click(view.getByRole("combobox", { name: /^Conversation/ }));+ await user.click(await view.findByRole("option", { name }));+}++test("linking Slack needs only a conversation, and warns that it moves the account", async () => {+ serving();+ const view = draw();+ const user = await openSlackLink(view);+ expect(view.queryByRole("combobox", { name: /^Bot/ })).toBeNull();+ expect(view.getByText(/Linking it here moves it/)).toBeTruthy();+ await user.click(view.getByRole("combobox", { name: /^Conversation/ }));+ const options = (await view.findAllByRole("option")).map(+ (option) => option.textContent,+ );+ expect(options).toContain("Finance desk");+ expect(options).not.toContain("Docs desk");+ await user.click(view.getByRole("option", { name: "Finance desk" }));+ await user.click(view.getByRole("button", { name: "Link Slack" }));+ await waitFor(() =>+ expect(writes).toContainEqual({+ request: "POST /api/delivery/opentag/start",+ body: {+ channelId: "channel-expenses",+ agentId: "expenses",+ platform: "slack",+ },+ }),+ );+ expect(await view.findByText("link abc")).toBeTruthy();+});++test("closing the dialog keeps the link code, so reopening the row shows it again", async () => {+ serving();+ const view = draw();+ const user = await openSlackLink(view);+ await chooseConversation(view, user, "Finance desk");+ await user.click(view.getByRole("button", { name: "Link Slack" }));+ expect(await view.findByText("link abc")).toBeTruthy();+ await user.keyboard("{Escape}");+ await waitFor(() => expect(view.queryByRole("dialog")).toBeNull());+ // The row says a code is waiting, and opening it shows that code without asking for another.+ expect(view.getByText(/A link code is waiting/)).toBeTruthy();+ await user.click(view.getByRole("button", { name: /^Link Slack/ }));+ expect(await view.findByText("link abc")).toBeTruthy();+ // With the conversation it links, so "this conversation" still names one.+ expect(+ view.getByRole("combobox", { name: /^Conversation/ }).textContent,+ ).toContain("Finance desk");+ expect(+ writes.filter(+ (write) => write.request === "POST /api/delivery/opentag/start",+ ),+ ).toHaveLength(1);+});++test("nothing can be linked until a conversation is chosen", async () => {+ serving();+ const view = draw();+ const user = await openSlackLink(view);+ expect(+ view.getByRole("button", { name: "Link Slack" }).hasAttribute("disabled"),+ ).toBe(true);+ await chooseConversation(view, user, "Finance desk");+ await waitFor(() =>+ expect(+ view.getByRole("button", { name: "Link Slack" }).hasAttribute("disabled"),+ ).toBe(false),+ );+});++test("a transport the deployment cannot reach says why instead of opening", async () => {+ serving();+ const view = draw();+ await view.findByRole("button", { name: "Disconnect" });+ expect(+ view.queryByRole("button", { name: /^Link Microsoft Teams/ }),+ ).toBeNull();+ expect(view.getByText(/needs to pair OpenBot with OpenTag/)).toBeTruthy();+});++test("a phone is verified for the chosen conversation, then asks for its code", async () => {+ serving(true);+ sessionStorage.clear();+ const view = draw();+ const user = userEvent.setup({ document });+ await view.findByRole("button", { name: "Disconnect" });+ await user.click(view.getByRole("button", { name: /^Connect a phone/ }));+ await chooseConversation(view, user, "Finance desk");+ await user.type(view.getByLabelText("Phone number"), "+15551234567");+ await user.click(+ view.getByRole("button", { name: "Send verification code" }),+ );+ await waitFor(() =>+ expect(writes).toContainEqual({+ request: "POST /api/delivery/sms/start",+ body: {+ channelId: "channel-expenses",+ agentId: "expenses",+ phone: "+15551234567",+ },+ }),+ );+ await user.type(await view.findByLabelText("Verification code"), "123456");+ await user.click(view.getByRole("button", { name: "Confirm phone" }));+ await waitFor(() =>+ expect(writes).toContainEqual({+ request: "POST /api/delivery/sms/confirm",+ body: { challengeId: "challenge-1", code: "123456" },+ }),+ );+});diff --git a/app/tests/bot-responsibilities.test.tsx b/app/tests/bot-responsibilities.test.tsxnew file mode 100644index 00000000..8780d8df--- /dev/null+++ b/app/tests/bot-responsibilities.test.tsx@@ -0,0 +1,154 @@+import { afterAll, afterEach, beforeAll, expect, test } from "bun:test";+import { GlobalRegistrator } from "@happy-dom/global-registrator";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import {+ createMemoryHistory,+ createRootRoute,+ createRouter,+ RouterProvider,+} from "@tanstack/react-router";+import { cleanup, fireEvent, render, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { BotResponsibilities } from "@/components/responsibilities/responsibilities";+import { settleReactWork } from "./settle-react-work";++/** A Bot's Responsibilities page: its own goals, and a new one that needs no Bot picked. */++beforeAll(() => GlobalRegistrator.register());+afterEach(cleanup);+afterAll(async () => {+ await settleReactWork();+ GlobalRegistrator.unregister();+});++const originalFetch = global.fetch;+afterEach(() => {+ global.fetch = originalFetch;+});++const goal = (id: string, agentId: string, title: string) => ({+ id,+ agentId,+ channelId: `channel-${agentId}`,+ threadId: "thread",+ title,+ instruction: "Do it.",+ successCriteria: "Done.",+ status: "active",+ progress: "",+ lastResult: null,+ subscriptions: [],+ updatedAt: "2026-10-09T10:00:00Z",+});++const channel = (id: string, name: string, agentIds: string[]) => ({+ id,+ name,+ agentIds,+ active: true,+ summary: null,+ lastMessage: null,+ lastMessageAgentId: null,+ createdAt: "2026-10-09T10:00:00Z",+ pinned: false,+ lastReadAt: null,+});++const writes: { request: string; body: unknown }[] = [];+function serving() {+ writes.length = 0;+ global.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ const method = init?.method ?? "GET";+ if (method !== "GET") {+ writes.push({+ request: `${method} ${url}`,+ body: typeof init?.body === "string" ? JSON.parse(init.body) : null,+ });+ return Response.json({ ok: true });+ }+ if (url === "/api/responsibilities") {+ return Response.json({+ responsibilities: [+ goal("g1", "expenses", "Reconcile receipts"),+ goal("g2", "knowledge", "Keep the wiki fresh"),+ ],+ });+ }+ if (url.startsWith("/api/channels")) {+ return Response.json({+ channels: [+ channel("channel-expenses", "Finance desk", ["expenses"]),+ channel("channel-knowledge", "Docs desk", ["knowledge"]),+ ],+ nextCursor: null,+ });+ }+ if (url.startsWith("/api/agents")) {+ return Response.json({+ agents: [+ { id: "expenses", name: "Expenses" },+ { id: "knowledge", name: "Knowledge" },+ ],+ });+ }+ return Response.json({ runs: [], triggers: [], requests: [] });+ }) as unknown as typeof fetch;+}++function draw() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ const router = createRouter({+ history: createMemoryHistory({ initialEntries: ["/"] }),+ routeTree: createRootRoute({+ component: () => <BotResponsibilities agentId="expenses" />,+ }),+ });+ return render(+ <QueryClientProvider client={client}>+ <RouterProvider router={router as never} />+ </QueryClientProvider>,+ );+}++test("only this Bot's responsibilities are listed", async () => {+ serving();+ const view = draw();+ expect(await view.findByText("Reconcile receipts")).toBeTruthy();+ expect(view.queryByText("Keep the wiki fresh")).toBeNull();+});++test("a new responsibility needs no Bot picked, and offers only this Bot's conversations", async () => {+ serving();+ const view = draw();+ await view.findByText("Reconcile receipts");+ const user = userEvent.setup({ document });+ await user.click(view.getByRole("button", { name: /New responsibility/ }));+ expect(view.queryByRole("combobox", { name: /^Bot/ })).toBeNull();+ await user.click(view.getByRole("combobox", { name: /^Conversation/ }));+ const options = (await view.findAllByRole("option")).map(+ (option) => option.textContent,+ );+ expect(options).toContain("Finance desk");+ expect(options).not.toContain("Docs desk");++ await user.click(view.getByRole("option", { name: "Finance desk" }));+ await user.type(view.getByLabelText("Title"), "Close the month");+ await user.type(view.getByLabelText("Instruction"), "Close it.");+ await user.type(view.getByLabelText("Success criteria"), "Closed.");+ fireEvent.submit(+ (view.getByRole("button", { name: /Create/ }) as HTMLButtonElement)+ .form as HTMLFormElement,+ );+ await waitFor(() =>+ expect(writes.map((write) => write.body)).toContainEqual(+ expect.objectContaining({+ agentId: "expenses",+ channelId: "channel-expenses",+ title: "Close the month",+ }),+ ),+ );+});diff --git a/app/tests/bot-roster-groups.test.ts b/app/tests/bot-roster-groups.test.tsnew file mode 100644index 00000000..75d82352--- /dev/null+++ b/app/tests/bot-roster-groups.test.ts@@ -0,0 +1,76 @@+import { expect, test } from "bun:test";+import type { AgentProfile } from "@/lib/agents/queries";+import { groupRoster } from "@/lib/agents/roster";++function bot(overrides: Partial<AgentProfile> & { id: string }): AgentProfile {+ return {+ name: overrides.id,+ title: "Title",+ roleDescription: "Role",+ avatarSeed: "seed",+ visibility: "private",+ endpoint: null,+ builtIn: true,+ hasAuth: false,+ hasCallbackToken: false,+ hidden: false,+ pinned: false,+ systemOwned: false,+ canManage: false,+ mine: false,+ ...overrides,+ };+}++const ids = (list: AgentProfile[]) => list.map((agent) => agent.id);++test("your own Bots are Yours and everyone else's are Shared with you", () => {+ const groups = groupRoster([+ bot({ id: "mine", mine: true, canManage: true }),+ bot({ id: "public", visibility: "public" }),+ bot({ id: "team" }),+ ]);+ expect(ids(groups.yours)).toEqual(["mine"]);+ expect(ids(groups.shared)).toEqual(["public", "team"]);+ expect(groups.pinned).toEqual([]);+});++test("an administrator's Yours holds only the Bots they created", () => {+ const groups = groupRoster([+ bot({ id: "theirs", mine: true, canManage: true }),+ bot({ id: "colleague", canManage: true }),+ ]);+ expect(ids(groups.yours)).toEqual(["theirs"]);+ expect(ids(groups.shared)).toEqual(["colleague"]);+});++test("a pinned Bot is in Pinned only, wherever it would otherwise sit", () => {+ const groups = groupRoster([+ bot({ id: "mine", mine: true, pinned: true }),+ bot({ id: "shared", pinned: true }),+ ]);+ expect(ids(groups.pinned)).toEqual(["mine", "shared"]);+ expect(groups.yours).toEqual([]);+ expect(groups.shared).toEqual([]);+});++test("a Team Bot an administrator assigned to the person is always pinned", () => {+ const groups = groupRoster([bot({ id: "assigned", assignedToMe: true })]);+ expect(ids(groups.pinned)).toEqual(["assigned"]);+ expect(groups.shared).toEqual([]);+});++test("a Bot waiting on the person is in Needs you only, ahead of every other section", () => {+ const waiting = new Set(["pinned-waiting", "mine-waiting"]);+ const groups = groupRoster(+ [+ bot({ id: "pinned-waiting", pinned: true }),+ bot({ id: "mine-waiting", mine: true }),+ bot({ id: "quiet", mine: true }),+ ],+ (id) => (waiting.has(id) ? 1 : 0),+ );+ expect(ids(groups.needsYou)).toEqual(["pinned-waiting", "mine-waiting"]);+ expect(groups.pinned).toEqual([]);+ expect(ids(groups.yours)).toEqual(["quiet"]);+});diff --git a/app/tests/bot-roster.test.tsx b/app/tests/bot-roster.test.tsxnew file mode 100644index 00000000..765eb7eb--- /dev/null+++ b/app/tests/bot-roster.test.tsx@@ -0,0 +1,219 @@+import {+ afterAll,+ afterEach,+ beforeAll,+ beforeEach,+ expect,+ test,+} from "bun:test";+import { GlobalRegistrator } from "@happy-dom/global-registrator";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import {+ createMemoryHistory,+ createRootRoute,+ createRoute,+ createRouter,+ RouterProvider,+} from "@tanstack/react-router";+import { cleanup, fireEvent, render, waitFor } from "@testing-library/react";+import { BotRoster } from "@/components/bots/bot-roster";+import { type AgentProfile, agentKeys } from "@/lib/agents/queries";+import { settleReactWork } from "./settle-react-work";++/**+ * The Bots roster: one list of every Bot a person can reach, replacing the Bots, Agents and Team+ * Bots screens. The harness is this repository's: `GlobalRegistrator` around the file, `cleanup`+ * after each test, a `QueryClient` per test with `retry: false`, and `fetch` stubbed per test.+ */++beforeAll(() => GlobalRegistrator.register());+afterEach(cleanup);+afterAll(async () => {+ await settleReactWork();+ GlobalRegistrator.unregister();+});++const originalFetch = global.fetch;+afterEach(() => {+ global.fetch = originalFetch;+});++function bot(overrides: Partial<AgentProfile> & { id: string }): AgentProfile {+ return {+ name: overrides.id,+ title: "Title",+ roleDescription: "Role",+ avatarSeed: "seed",+ visibility: "private",+ endpoint: null,+ builtIn: true,+ hasAuth: false,+ hasCallbackToken: false,+ hidden: false,+ pinned: false,+ systemOwned: false,+ canManage: true,+ mine: true,+ ...overrides,+ };+}++/** Serves the visible roster, the hidden roster, and an empty attention list. */+function serving(+ visible: AgentProfile[],+ hidden: AgentProfile[],+ attention: Record<string, unknown>[] = [],+) {+ global.fetch = (async (input: RequestInfo | URL) => {+ const url = String(input);+ if (url.includes("/api/bots/attention"))+ return Response.json({ bots: attention });+ return Response.json({+ agents: url.includes("hidden=true") ? hidden : visible,+ });+ }) as unknown as typeof fetch;+}++let queryClient: QueryClient;+beforeEach(() => {+ queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+});++function draw() {+ const rootRoute = createRootRoute();+ const routeTree = rootRoute.addChildren([+ createRoute({+ getParentRoute: () => rootRoute,+ path: "/",+ component: BotRoster,+ }),+ createRoute({+ getParentRoute: () => rootRoute,+ path: "/bots/$agentId",+ component: () => null,+ }),+ ]);+ const router = createRouter({+ routeTree,+ history: createMemoryHistory({ initialEntries: ["/"] }),+ });+ return render(+ <QueryClientProvider client={queryClient}>+ <RouterProvider router={router as never} />+ </QueryClientProvider>,+ );+}++test("sections read Pinned, Yours, Shared with you, and each Bot appears once", async () => {+ serving(+ [+ bot({ id: "favourite", name: "Favourite", pinned: true }),+ bot({ id: "mine", name: "Mine" }),+ bot({ id: "theirs", name: "Theirs", mine: false, canManage: false }),+ ],+ [],+ );+ const view = draw();+ expect(await view.findByText("Theirs")).toBeTruthy();+ const headings = [...view.container.querySelectorAll("h2")].map(+ (heading) => heading.textContent,+ );+ expect(headings).toEqual(["Pinned", "Yours", "Shared with you"]);+ expect(view.getAllByText("Favourite")).toHaveLength(1);+});++test("a row opens the Bot's own page", async () => {+ serving([bot({ id: "mine", name: "Mine" })], []);+ const view = draw();+ const row = (await view.findByText("Mine")).closest("a");+ expect(row?.getAttribute("href")).toBe("/bots/mine");+});++test("with every Bot of yours pinned, Yours says so instead of claiming none", async () => {+ serving([bot({ id: "favourite", name: "Favourite", pinned: true })], []);+ const view = draw();+ expect(await view.findByText("Your Bots are all pinned above.")).toBeTruthy();+ expect(view.queryByText("You have no Bots of your own yet.")).toBeNull();+});++test("a hidden Bot is under Hidden, folded until asked for, and its row opens its page", async () => {+ serving(+ [bot({ id: "mine", name: "Mine" })],+ [bot({ id: "tucked", name: "Tucked", hidden: true })],+ );+ const view = draw();+ expect(await view.findByText("Hidden")).toBeTruthy();+ expect(view.queryByText("Tucked")).toBeNull();+ fireEvent.click(view.getByRole("button", { name: "Show" }));+ const row = view.getByText("Tucked").closest("a");+ expect(row?.getAttribute("href")).toBe("/bots/tucked");+});++test("with nothing hidden there is no Hidden section", async () => {+ serving([bot({ id: "mine", name: "Mine" })], []);+ const view = draw();+ expect(await view.findByText("Mine")).toBeTruthy();+ await waitFor(() =>+ expect(queryClient.getQueryState(agentKeys.list(true))?.status).toBe(+ "success",+ ),+ );+ expect(view.queryByText("Hidden")).toBeNull();+});++test("a roster that never loaded says so, not that you have no Bots", async () => {+ global.fetch = (async () =>+ new Response(null, { status: 500 })) as unknown as typeof fetch;+ const view = draw();+ expect(await view.findByRole("alert")).toBeTruthy();+ expect(view.queryByText("You have no Bots of your own yet.")).toBeNull();+});++test("a failed refetch keeps the roster it already had, not the error", async () => {+ queryClient.setQueryData(agentKeys.list(false), [+ bot({ id: "mine", name: "Mine" }),+ ]);+ global.fetch = (async () =>+ new Response(null, { status: 500 })) as unknown as typeof fetch;+ const view = draw();+ await waitFor(() =>+ expect(queryClient.getQueryState(agentKeys.list(false))?.status).toBe(+ "error",+ ),+ );+ expect(view.getByText("Mine")).toBeTruthy();+ expect(view.queryByRole("alert")).toBeNull();+});++test("a Bot with something waiting comes first, under Needs you, with its count", async () => {+ serving(+ [+ bot({ id: "mine", name: "Mine" }),+ bot({ id: "waiting", name: "Waiting", mine: false }),+ ],+ [],+ [+ {+ agentId: "waiting",+ name: "Waiting",+ questions: 1,+ approvals: 1,+ handoffs: 0,+ unread: 0,+ paused: false,+ notify: "all",+ },+ ],+ );+ const view = draw();+ expect(await view.findByText("Needs you")).toBeTruthy();+ const headings = [...view.container.querySelectorAll("h2")].map(+ (heading) => heading.textContent,+ );+ expect(headings).toEqual(["Needs you", "Yours", "Shared with you"]);+ // Once, under Needs you, not again under Shared with you.+ expect(view.getAllByText("Waiting")).toHaveLength(1);+ expect(view.getByText("2")).toBeTruthy();+});diff --git a/app/tests/bot-route-default-agent.test.tsx b/app/tests/bot-route-default-agent.test.tsxindex 6baa2b40..c9bb15cc 100644--- a/app/tests/bot-route-default-agent.test.tsx+++ b/app/tests/bot-route-default-agent.test.tsx@@ -321,13 +321,9 @@ test("/bot opens a live Computer sidebar with ownership controls and preserves t"/bot?agent=general-assistant",);const toggle = await view.findByRole("button", { name: "Open Computer" });- await waitFor(() =>- expect(- view- .getByRole("button", { name: "Take control" })- .hasAttribute("disabled"),- ).toBe(false),- );+ await waitFor(() => expect(toggle.hasAttribute("disabled")).toBe(false));+ // Taking control is offered inside the Computer, never beside the header's icon.+ expect(view.queryByRole("button", { name: "Take control" })).toBeNull();const chat = view.getByTestId("copilot-chat");fireEvent.change(view.getByRole("textbox", { name: "Chat draft" }), {target: { value: "Keep this conversation" },diff --git a/app/tests/bot-settings-rows.test.tsx b/app/tests/bot-settings-rows.test.tsxnew file mode 100644index 00000000..a47febf4--- /dev/null+++ b/app/tests/bot-settings-rows.test.tsx@@ -0,0 +1,173 @@+import { afterAll, afterEach, beforeAll, expect, test } from "bun:test";+import { GlobalRegistrator } from "@happy-dom/global-registrator";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import {+ createMemoryHistory,+ createRootRoute,+ createRouter,+ RouterProvider,+} from "@tanstack/react-router";+import { cleanup, render } from "@testing-library/react";+import { BotSettingsRows } from "@/components/bot-profile/settings-rows";+import type { AgentProfile } from "@/lib/agents/queries";+import { settleReactWork } from "./settle-react-work";++/** The "Settings for this Bot" card: each row says its current answer and opens its page. */++beforeAll(() => GlobalRegistrator.register());+afterEach(cleanup);+afterAll(async () => {+ await settleReactWork();+ GlobalRegistrator.unregister();+});++const originalFetch = global.fetch;+afterEach(() => {+ global.fetch = originalFetch;+});++const BOT: AgentProfile = {+ id: "expenses",+ name: "Expenses",+ title: "Finance",+ roleDescription: "Receipts.",+ avatarSeed: "e",+ visibility: "public",+ endpoint: null,+ builtIn: true,+ hasAuth: false,+ hasCallbackToken: false,+ hidden: false,+ pinned: false,+ systemOwned: false,+ canManage: true,+ mine: true,+};++function serving(+ role: "admin" | "user",+ teamBots: { id: string; audience: "team" | "people" }[] = [],+) {+ global.fetch = (async (input: RequestInfo | URL) => {+ const url = String(input);+ if (url.includes("/api/routines")) {+ return Response.json({+ routines: [{ id: "r1", agentId: "expenses" }],+ sweep: null,+ });+ }+ if (url.includes("/api/plugins/for/")) {+ return Response.json({ tools: [], skills: [] });+ }+ if (url.includes("/api/team-bots")) {+ return Response.json({ teamBots, publishable: [] });+ }+ if (url === "/api/responsibilities") {+ return Response.json({+ responsibilities: [+ { id: "g1", agentId: "expenses", status: "active" },+ { id: "g2", agentId: "expenses", status: "paused" },+ { id: "g3", agentId: "knowledge", status: "active" },+ ],+ });+ }+ if (url === "/api/delivery") {+ return Response.json({+ bindings: [+ { id: "b1", transport: "slack", agentId: "expenses", enabled: true },+ { id: "b2", transport: "sms", agentId: "knowledge", enabled: true },+ ],+ devices: [],+ deliveries: [],+ available: { slack: true, teams: false, sms: true, push: false },+ });+ }+ if (url === "/api/memory/sources") {+ return Response.json({+ sources: [{ id: "s1", agentId: "expenses", enabled: true }],+ });+ }+ if (url === "/api/proactive/settings") {+ return Response.json({ settings: [] });+ }+ if (url === "/api/approvals") {+ return Response.json({+ enabled: true,+ requests: [],+ questions: [],+ rules: [+ { id: "r1", botId: "expenses" },+ { id: "r2", botId: "*" },+ ],+ teamRules: [],+ });+ }+ return Response.json({+ user: { id: "me", role, email: "[email protected]", name: "Me" },+ });+ }) as unknown as typeof fetch;+}++function draw(agent: AgentProfile) {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ const router = createRouter({+ history: createMemoryHistory({ initialEntries: ["/"] }),+ routeTree: createRootRoute({+ component: () => <BotSettingsRows agent={agent} />,+ }),+ });+ return render(+ <QueryClientProvider client={client}>+ <RouterProvider router={router as never} />+ </QueryClientProvider>,+ );+}++test("the owner sees Sharing, and each row opens its own page", async () => {+ serving("user");+ const view = draw(BOT);+ const sharing = (await view.findByText("Sharing")).closest("a");+ expect(sharing?.getAttribute("href")).toBe("/bots/expenses/sharing");+ expect(view.getByText("Setup").closest("a")?.getAttribute("href")).toBe(+ "/bots/expenses/setup",+ );+ // Public and unpublished: everyone can already use it.+ expect(await view.findByText("Everyone (public)")).toBeTruthy();+});++test("someone who neither owns the Bot nor administers the deployment does not see Sharing", async () => {+ serving("user");+ const view = draw({ ...BOT, mine: false, canManage: false });+ expect(await view.findByText("Setup")).toBeTruthy();+ expect(view.queryByText("Sharing")).toBeNull();+});++test("an administrator sees Sharing on somebody else's Bot", async () => {+ serving("admin");+ const view = draw({ ...BOT, mine: false });+ expect(await view.findByText("Sharing")).toBeTruthy();+});++test("someone a Bot was published to sees Sharing, where its link is", async () => {+ serving("user", [{ id: "expenses", audience: "team" }]);+ const view = draw({ ...BOT, mine: false, canManage: false });+ expect(await view.findByText("Sharing")).toBeTruthy();+ expect(await view.findByText("Whole team")).toBeTruthy();+});++test("the rows for responsibilities, reach, memory and rules say what this Bot has and open their pages", async () => {+ serving("user");+ const view = draw(BOT);+ const row = async (title: string, summary: string, path: string) => {+ expect(await view.findByText(summary)).toBeTruthy();+ expect(view.getByText(title).closest("a")?.getAttribute("href")).toBe(+ `/bots/expenses/${path}`,+ );+ };+ await row("Responsibilities", "1 active", "responsibilities");+ await row("Reaching you", "Slack", "reach");+ await row("Memory", "1 source", "memory");+ await row("Approval rules", "1 rule", "approvals");+});diff --git a/app/tests/agent-dialog-built-in-edit.test.tsx b/app/tests/bot-setup.test.tsxsimilarity index 79%rename from app/tests/agent-dialog-built-in-edit.test.tsxrename to app/tests/bot-setup.test.tsxindex 9b73f5b1..0e6c1189 100644--- a/app/tests/agent-dialog-built-in-edit.test.tsx+++ b/app/tests/bot-setup.test.tsx@@ -16,13 +16,16 @@ import {} from "@tanstack/react-router";import { cleanup, render, waitFor } from "@testing-library/react";import userEvent from "@testing-library/user-event";-import { AgentDialog } from "@/components/agents/agent-dialog";+import { useQuery } from "@tanstack/react-query";+import { SetupSections } from "@/components/bot-profile/setup";+import { agentQueryOptions } from "@/lib/agents/queries";import type { AgentProfileStore } from "../../server/src/agents/profile-store";import type { AgentProfile } from "../../server/src/agents/profile-types";import { createAgentRoutes } from "../../server/src/agents/routes";+import { settleReactWork } from "./settle-react-work";/**- * Editing a coworker that runs on this deployment's own Bot.+ * Editing a Bot that runs on this deployment's own Bot, from its Setup page.** A coworker created as "Built in" on a deployment with a managed Bot is stored pointing at that* Bot's address, and the profile publishes it, with `builtIn` beside it so a screen can tell. The@@ -34,13 +37,16 @@ import { createAgentRoutes } from "../../server/src/agents/routes";* renamed, retitled, redescribed or made public at all.** The routes are the server's own, mounted behind `fetch` the way `agent-api-path.test.ts` mounts- * them, so the refusal is the real one. The dialog is drawn in a router of one route, for the- * `useNavigate` its General section holds.+ * them, so the refusal is the real one. The Setup sections are drawn in a router of one route, as+ * the Bot's Setup page draws them.*/beforeAll(() => GlobalRegistrator.register());afterEach(cleanup);-afterAll(() => GlobalRegistrator.unregister());+afterAll(async () => {+ await settleReactWork();+ GlobalRegistrator.unregister();+});const originalFetch = globalThis.fetch;afterEach(() => {@@ -63,15 +69,15 @@ beforeEach(() => {updates = [];});-function serve(endpoint: string) {+function serve(endpoint: string, ownerUserId = actor.id) {let profile: AgentProfile = {id: "expenses",name: "Expenses",title: "Finance Operations",roleDescription: "Review receipts.",avatarSeed: "expenses",- visibility: "private",- ownerUserId: actor.id,+ ownerUserId,+ visibility: ownerUserId === actor.id ? "private" : "public",systemOwned: false,hidden: false,pinned: false,@@ -126,17 +132,19 @@ function serve(endpoint: string) {);}+/** Loads the profile through the real route, as the Setup page does, then draws its sections. */+function Setup() {+ const agent = useQuery(agentQueryOptions("expenses"));+ return agent.data ? <SetupSections agent={agent.data} /> : null;+}+function draw() {const queryClient = new QueryClient({defaultOptions: { queries: { retry: false } },});const router = createRouter({history: createMemoryHistory({ initialEntries: ["/"] }),- routeTree: createRootRoute({- component: () => (- <AgentDialog agentId="expenses" onClose={() => {}} open />- ),- }),+ routeTree: createRootRoute({ component: Setup }),});return render(<QueryClientProvider client={queryClient}>@@ -147,8 +155,8 @@ function draw() {async function rename(view: ReturnType<typeof draw>, to: string) {const user = userEvent.setup({ document: view.baseElement.ownerDocument });- await user.click(await view.findByRole("button", { name: "Edit name" }));- const field = view.getByDisplayValue("Expenses");+ await user.click(await view.findByRole("button", { name: /^Name/ }));+ const field = await view.findByDisplayValue("Expenses");await user.clear(field);await user.type(field, to);await user.click(view.getByRole("button", { name: "Save" }));@@ -182,3 +190,11 @@ test("a coworker somebody hosts keeps its own endpoint when it is renamed", asynendpoint: "https://agents.example.test/ag-ui",});});++test("someone who cannot manage the Bot reads its setup but cannot open an editor", async () => {+ serve(MANAGED, "someone-else");+ const view = draw();++ expect(await view.findByText("Expenses")).toBeTruthy();+ expect(view.queryByRole("button", { name: /^Name/ })).toBeNull();+});diff --git a/app/tests/bot-sharing.test.tsx b/app/tests/bot-sharing.test.tsxnew file mode 100644index 00000000..a0ff6315--- /dev/null+++ b/app/tests/bot-sharing.test.tsx@@ -0,0 +1,237 @@+import { afterAll, afterEach, beforeAll, expect, test } from "bun:test";+import { GlobalRegistrator } from "@happy-dom/global-registrator";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import {+ createMemoryHistory,+ createRootRoute,+ createRouter,+ RouterProvider,+} from "@tanstack/react-router";+import { cleanup, fireEvent, render, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { SharingSections } from "@/components/bot-profile/sharing";+import type { AgentProfile } from "@/lib/agents/queries";+import type { TeamBot, TeamBotsData } from "@/lib/team-bots";+import { settleReactWork } from "./settle-react-work";++/**+ * A Bot's Sharing page: its owner publishes and unpublishes it, an administrator assigns it to+ * groups. Each is offered only to whoever the server lets do it.+ */++beforeAll(() => GlobalRegistrator.register());+afterEach(cleanup);+afterAll(async () => {+ await settleReactWork();+ GlobalRegistrator.unregister();+});++const originalFetch = global.fetch;+afterEach(() => {+ global.fetch = originalFetch;+});++const BOT: AgentProfile = {+ id: "expenses",+ name: "Expenses",+ title: "Finance",+ roleDescription: "Receipts.",+ avatarSeed: "e",+ visibility: "private",+ endpoint: null,+ builtIn: true,+ hasAuth: false,+ hasCallbackToken: false,+ hidden: false,+ pinned: false,+ systemOwned: false,+ canManage: true,+ mine: true,+};++const PUBLISHED: TeamBot = {+ id: "expenses",+ name: "Expenses",+ title: "Finance",+ roleDescription: "Receipts.",+ mine: true,+ audience: "team",+ publishedAt: "2026-10-01T00:00:00Z",+ assigned: false,+ visibleToTeam: true,+ people: [],+ groups: [],+ assignments: [],+};++const writes: { url: string; method: string; body: unknown }[] = [];++function serving(data: TeamBotsData, role: "admin" | "user") {+ writes.length = 0;+ global.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ if (init?.method && init.method !== "GET") {+ writes.push({+ url,+ method: init.method,+ body: init.body ? JSON.parse(String(init.body)) : undefined,+ });+ return Response.json({});+ }+ if (url.includes("/api/team-bots")) return Response.json(data);+ if (url.includes("/shared-use/bot/")) return Response.json({ apps: [] });+ if (url.includes("/shared-use")) return Response.json({ requests: [] });+ return Response.json({+ user: { id: "me", role, email: "[email protected]", name: "Me" },+ });+ }) as unknown as typeof fetch;+}++function draw(agent: AgentProfile) {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ const router = createRouter({+ history: createMemoryHistory({ initialEntries: ["/"] }),+ routeTree: createRootRoute({+ component: () => <SharingSections agent={agent} />,+ }),+ });+ return render(+ <QueryClientProvider client={client}>+ <RouterProvider router={router as never} />+ </QueryClientProvider>,+ );+}++test("an unpublished Bot of yours offers to publish it", async () => {+ serving(+ {+ teamBots: [],+ publishable: [{ id: "expenses", name: "Expenses", title: "Finance" }],+ },+ "user",+ );+ const view = draw(BOT);+ const user = userEvent.setup({ document });+ await user.click(await view.findByRole("button", { name: /Audience/ }));+ expect(+ await view.findByRole("button", { name: "Publish to team" }),+ ).toBeTruthy();+ expect(view.queryByRole("button", { name: "Unpublish" })).toBeNull();+});++test("publishing to specific people sends them and their groups", async () => {+ serving(+ {+ teamBots: [],+ publishable: [{ id: "expenses", name: "Expenses", title: "Finance" }],+ },+ "user",+ );+ const view = draw(BOT);+ const user = userEvent.setup({ document });+ await user.click(await view.findByRole("button", { name: /Audience/ }));+ await user.click(view.getByRole("combobox", { name: /^Published to/ }));+ await user.click(+ await view.findByRole("option", { name: "Specific people or groups" }),+ );+ await user.type(+ view.getByLabelText("People, by email"),+ );+ await user.type(view.getByLabelText("Groups"), "finance");+ fireEvent.submit(+ (view.getByRole("button", { name: "Publish to team" }) as HTMLButtonElement)+ .form as HTMLFormElement,+ );+ await waitFor(() =>+ expect(writes).toContainEqual({+ url: expect.stringContaining("/publication"),+ method: "PUT",+ body: {+ audience: "people",+ emails: ["[email protected]", "[email protected]"],+ groups: ["finance"],+ },+ }),+ );+});++test("a published Bot of yours can be updated, unpublished and its link copied", async () => {+ serving({ teamBots: [PUBLISHED], publishable: [] }, "user");+ const view = draw(BOT);+ expect(await view.findByRole("button", { name: "Unpublish" })).toBeTruthy();+ expect(view.getByRole("button", { name: "Copy link" })).toBeTruthy();+ // Not an administrator: no group assignment.+ expect(view.queryByRole("button", { name: /Assign to a group/ })).toBeNull();+ const user = userEvent.setup({ document });+ await user.click(view.getByRole("button", { name: /Audience/ }));+ expect(await view.findByRole("button", { name: "Update" })).toBeTruthy();+});++test("an administrator can assign a published Bot to groups but not publish someone else's", async () => {+ serving(+ { teamBots: [{ ...PUBLISHED, mine: false }], publishable: [] },+ "admin",+ );+ const view = draw({ ...BOT, mine: false });+ expect(await view.findByText("Not assigned to any group.")).toBeTruthy();+ expect(view.queryByRole("button", { name: /Audience/ })).toBeNull();+ expect(view.queryByRole("button", { name: "Update" })).toBeNull();+ expect(view.queryByRole("button", { name: "Unpublish" })).toBeNull();+ const user = userEvent.setup({ document });+ await user.click(view.getByRole("button", { name: /Assign to a group/ }));+ await user.type(await view.findByLabelText("Group, or *"), "finance");+ fireEvent.submit(+ (view.getByRole("button", { name: "Assign" }) as HTMLButtonElement)+ .form as HTMLFormElement,+ );+ await waitFor(() =>+ expect(writes).toContainEqual(+ expect.objectContaining({ method: "POST", body: { group: "finance" } }),+ ),+ );+});++test("an administrator removes a group a Bot is assigned to", async () => {+ serving(+ {+ teamBots: [{ ...PUBLISHED, mine: false, assignments: ["*", "finance"] }],+ publishable: [],+ },+ "admin",+ );+ const view = draw({ ...BOT, mine: false });+ expect(await view.findByText("Whole team")).toBeTruthy();+ const user = userEvent.setup({ document });+ await user.click(view.getByRole("button", { name: "Remove finance" }));+ await waitFor(() =>+ expect(writes).toContainEqual(+ expect.objectContaining({ method: "DELETE", body: undefined }),+ ),+ );+ expect(writes.at(-1)?.url).toContain("finance");+});++test("a public Bot that is not published says everyone can already use it", async () => {+ serving(+ {+ teamBots: [],+ publishable: [{ id: "expenses", name: "Expenses", title: "Finance" }],+ },+ "user",+ );+ const view = draw({ ...BOT, visibility: "public" });+ expect(+ await view.findByText(/everyone in the deployment can already use it/),+ ).toBeTruthy();+ expect(view.queryByText(/Only you can use it/)).toBeNull();+});++test("someone else's unpublished private Bot is not described as yours alone", async () => {+ serving({ teamBots: [], publishable: [] }, "admin");+ const view = draw({ ...BOT, mine: false });+ expect(await view.findByText("Not published.")).toBeTruthy();+ expect(view.queryByText(/Only you can use it/)).toBeNull();+});diff --git a/app/tests/bot-summaries.test.ts b/app/tests/bot-summaries.test.tsnew file mode 100644index 00000000..61f4c483--- /dev/null+++ b/app/tests/bot-summaries.test.ts@@ -0,0 +1,68 @@+import { expect, test } from "bun:test";+import {+ accessSummary,+ countLabel,+ memorySummary,+ reachSummary,+ setupSummary,+ sharingSummary,+} from "@/lib/agents/bot-summaries";++test("counts read as words", () => {+ expect(countLabel(0, "routine", "routines", "No routines")).toBe(+ "No routines",+ );+ expect(countLabel(1, "routine", "routines", "No routines")).toBe("1 routine");+ expect(countLabel(3, "routine", "routines", "No routines")).toBe(+ "3 routines",+ );+});++test("access names skills and apps, or says there is nothing", () => {+ expect(accessSummary(0, 0)).toBe("Nothing granted");+ expect(accessSummary(2, 0)).toBe("2 skills");+ expect(accessSummary(0, 1)).toBe("1 app");+ expect(accessSummary(1, 3)).toBe("1 skill, 3 apps");+});++test("sharing names the audience", () => {+ expect(sharingSummary(undefined, "private")).toBe("Not shared");+ expect(sharingSummary({ audience: "team" }, "private")).toBe("Whole team");+ expect(sharingSummary({ audience: "people" }, "private")).toBe(+ "Specific people and groups",+ );+});++test("setup names where it runs", () => {+ expect(+ setupSummary({ builtIn: true, endpoint: "http://localhost:4201/ag-ui" }),+ ).toBe("Built in");+ expect(+ setupSummary({+ builtIn: false,+ endpoint: "https://bots.example.com/ag-ui",+ }),+ ).toBe("bots.example.com");+ expect(setupSummary({ builtIn: false, endpoint: "not a url" })).toBe(+ "not a url",+ );+ expect(setupSummary({ builtIn: false, endpoint: null })).toBe("Built in");+});++test("a public Bot nobody published is still open to everyone, not 'Not shared'", () => {+ expect(sharingSummary(undefined, "public")).toBe("Everyone (public)");+});++test("reach names the places a Bot continues the conversation", () => {+ expect(reachSummary([])).toBe("Only in OpenBot");+ expect(reachSummary(["slack"])).toBe("Slack");+ expect(reachSummary(["sms", "slack", "slack"])).toBe("Slack, SMS");+ expect(reachSummary(["teams"])).toBe("Microsoft Teams");+});++test("memory names the sources and whether research is on", () => {+ expect(memorySummary(0, false)).toBe("Nothing connected");+ expect(memorySummary(2, false)).toBe("2 sources");+ expect(memorySummary(0, true)).toBe("Background research on");+ expect(memorySummary(1, true)).toBe("1 source, background research on");+});diff --git a/app/tests/bots-nav-badge.test.tsx b/app/tests/bots-nav-badge.test.tsxnew file mode 100644index 00000000..1fc6f12e--- /dev/null+++ b/app/tests/bots-nav-badge.test.tsx@@ -0,0 +1,119 @@+import { afterAll, afterEach, beforeAll, expect, test } from "bun:test";+import { GlobalRegistrator } from "@happy-dom/global-registrator";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { act, cleanup, render, waitFor } from "@testing-library/react";+import { BotsNavBadge } from "@/components/bot-profile/attention";+import { botLifecycleKeys } from "@/lib/bot-lifecycle/queries";+import { settleReactWork } from "./settle-react-work";++/**+ * The badge on the sidebar's Bots item: how many things wait on the person across every Bot, or a+ * dot when only something unread does. It replaced one sidebar row per Bot, so it also carries the+ * browser notification those rows used to send.+ */++beforeAll(() => GlobalRegistrator.register());+afterEach(cleanup);+afterAll(async () => {+ await settleReactWork();+ GlobalRegistrator.unregister();+});++const originalFetch = global.fetch;+const originalNotification = globalThis.Notification;+afterEach(() => {+ global.fetch = originalFetch;+ globalThis.Notification = originalNotification;+});++const attention = (+ agentId: string,+ counts: Partial<{+ questions: number;+ approvals: number;+ handoffs: number;+ unread: number;+ }>,+) => ({+ agentId,+ name: agentId === "expenses" ? "Expenses" : "Knowledge",+ questions: 0,+ approvals: 0,+ handoffs: 0,+ unread: 0,+ paused: false,+ notify: "all",+ ...counts,+});++let served: ReturnType<typeof attention>[] = [];+function serving(bots: ReturnType<typeof attention>[]) {+ served = bots;+ global.fetch = (async () =>+ Response.json({ bots: served })) as unknown as typeof fetch;+}++function draw() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ const view = render(+ <QueryClientProvider client={client}>+ <BotsNavBadge />+ </QueryClientProvider>,+ );+ return { view, client };+}++test("the badge adds up what waits on the person across every Bot", async () => {+ serving([+ attention("expenses", { questions: 1, approvals: 1 }),+ attention("knowledge", { handoffs: 1, unread: 4 }),+ ]);+ const { view } = draw();+ const badge = await view.findByText("3");+ expect(badge.getAttribute("aria-label")).toBe("3 things need you");+});++test("with only unread messages the badge is a dot, not a number", async () => {+ serving([attention("expenses", { unread: 2 })]);+ const { view } = draw();+ expect(await view.findByLabelText("Unread messages")).toBeTruthy();+ expect(view.container.textContent).toBe("");+});++test("with nothing waiting there is no badge", async () => {+ serving([attention("expenses", {})]);+ const { view, client } = draw();+ await waitFor(() =>+ expect(client.getQueryState(botLifecycleKeys.attention)?.status).toBe(+ "success",+ ),+ );+ expect(view.container.innerHTML).toBe("");+});++test("a Bot that starts needing the person sends a browser notification", async () => {+ const sent: string[] = [];+ globalThis.Notification = Object.assign(+ function (this: unknown, title: string) {+ sent.push(title);+ },+ { permission: "granted" },+ ) as unknown as typeof Notification;+ serving([attention("expenses", {})]);+ const { client } = draw();+ await waitFor(() =>+ expect(client.getQueryState(botLifecycleKeys.attention)?.status).toBe(+ "success",+ ),+ );+ // The state on arrival is not news.+ expect(sent).toEqual([]);++ served = [attention("expenses", { questions: 1 })];+ await act(async () => {+ await client.refetchQueries({ queryKey: botLifecycleKeys.attention });+ });+ await waitFor(() => expect(sent).toEqual(["Expenses needs you"]));+});diff --git a/app/tests/channel-menu-mutations.test.ts b/app/tests/channel-menu-mutations.test.tsindex dd79240e..4699d11d 100644--- a/app/tests/channel-menu-mutations.test.ts+++ b/app/tests/channel-menu-mutations.test.ts@@ -143,10 +143,21 @@ test("marking read PUTs the read route and patches lastReadAt in place", async (const patched = queryClient.getQueryData<InfiniteData<ChannelPage>>(channelKeys.list(),);- // The dot clears from the cache before the wire answered, and nothing was invalidated:- // there is no onSuccess to queue a refetch that would race the socket's own patches.+ // The dot clears from the cache before the wire answered.expect(patched?.pages[0]?.channels[0]?.lastReadAt).not.toBeNull();- expect(options.onSuccess).toBeUndefined();+});++test("a landed mark-read refreshes the Bots badge, and never the roster the socket patches", async () => {+ capturingFetch(204, undefined);+ const { queryClient, invalidated } = invalidationRecorder();+ const options = markChannelReadMutationOptions(queryClient);+ await options.onSuccess?.(+ undefined,+ "channel-1",+ undefined,+ mutationContext(queryClient),+ );+ expect(invalidated).toEqual([{ queryKey: ["bot-lifecycle", "attention"] }]);});test("a message stamped by a clock ahead of ours still reads as seen after marking", async () => {diff --git a/app/tests/compose-state.test.ts b/app/tests/compose-state.test.tsindex cfb9492c..042f8392 100644--- a/app/tests/compose-state.test.ts+++ b/app/tests/compose-state.test.ts@@ -4,6 +4,8 @@ import {canSend,MAX_RECIPIENTS,removeRecipient,+ startsGroup,+ toFieldChange,} from "../src/components/channels/compose-state";const KNOWLEDGE = { id: "knowledge", name: "Knowledge" };@@ -14,9 +16,19 @@ describe("addRecipient", () => {expect(addRecipient([], KNOWLEDGE)).toEqual([KNOWLEDGE]);});- test("replaces rather than appends once the cap is reached", () => {- // One coworker per channel today; a second pick replaces the first.- expect(addRecipient([KNOWLEDGE], RISK)).toEqual([RISK]);+ test("a second Bot is added after the first, in the order they will answer", () => {+ expect(addRecipient([KNOWLEDGE], RISK)).toEqual([KNOWLEDGE, RISK]);+ });++ test("past the cap, the earliest pick gives way", () => {+ const many = Array.from({ length: MAX_RECIPIENTS }, (_, index) => ({+ id: `bot-${index}`,+ name: `Bot ${index}`,+ }));+ const added = addRecipient(many, RISK);+ expect(added).toHaveLength(MAX_RECIPIENTS);+ expect(added.at(-1)).toEqual(RISK);+ expect(added[0]?.id).toBe("bot-1");});test("adding the coworker already chosen is a no-op", () => {@@ -35,8 +47,9 @@ describe("removeRecipient", () => {});describe("canSend", () => {- test("needs exactly one recipient and some text", () => {+ test("needs at least one recipient and some text", () => {expect(canSend([KNOWLEDGE], "hello")).toBe(true);+ expect(canSend([KNOWLEDGE, RISK], "hello")).toBe(true);});test("refuses with no recipient", () => {@@ -47,7 +60,32 @@ describe("canSend", () => {expect(canSend([KNOWLEDGE], " ")).toBe(false);});- test("cap is one", () => {- expect(MAX_RECIPIENTS).toBe(1);+ test("the cap is the server's limit for a group", () => {+ expect(MAX_RECIPIENTS).toBe(20);+ });+});++describe("startsGroup", () => {+ test("one Bot is a conversation, two or more are a group", () => {+ expect(startsGroup([KNOWLEDGE])).toBe(false);+ expect(startsGroup([KNOWLEDGE, RISK])).toBe(true);+ });+});++describe("toFieldChange", () => {+ test("a pick or a removal in the To: field is kept", () => {+ expect(toFieldChange([KNOWLEDGE], [KNOWLEDGE, RISK], "item-press")).toEqual(+ [KNOWLEDGE, RISK],+ );+ expect(+ toFieldChange([KNOWLEDGE, RISK], [RISK], "chip-remove-press"),+ ).toEqual([RISK]);+ });++ test("Escape does not throw away the Bots already picked", () => {+ expect(toFieldChange([KNOWLEDGE, RISK], [], "escape-key")).toEqual([+ KNOWLEDGE,+ RISK,+ ]);});});diff --git a/app/tests/composing-enter.test.tsx b/app/tests/composing-enter.test.tsxindex 2c7b85a7..bfb55ccb 100644--- a/app/tests/composing-enter.test.tsx+++ b/app/tests/composing-enter.test.tsx@@ -17,7 +17,7 @@ import {import { act, cleanup, fireEvent, render } from "@testing-library/react";import userEvent from "@testing-library/user-event";import type { ComponentType, ReactNode } from "react";-import { AgentDialog } from "@/components/agents/agent-dialog";+import { SetupSections } from "@/components/bot-profile/setup";import { CreateAgentDialog } from "@/components/agents/create-agent-dialog";import { type AgentProfile, agentKeys } from "@/lib/agents/queries";import { computerKeys } from "@/lib/computers/queries";@@ -140,13 +140,12 @@ async function settle() {}test("a coworker's name is not saved by the Enter that confirms a composed character", async () => {- const view = draw(- <AgentDialog agentId={PROFILE.id} onClose={() => {}} open />,- (client) => client.setQueryData(agentKeys.detail(PROFILE.id), PROFILE),+ const view = draw(<SetupSections agent={PROFILE} />, (client) =>+ client.setQueryData(agentKeys.detail(PROFILE.id), PROFILE),);- fireEvent.click(await view.findByRole("button", { name: "Edit name" }));- const field = view.getByDisplayValue(PROFILE.name);+ fireEvent.click(await view.findByRole("button", { name: /^Name/ }));+ const field = await view.findByDisplayValue(PROFILE.name);await type(field, "経費");await confirmComposedCharacter(field);diff --git a/app/tests/computer-control-button.test.tsx b/app/tests/computer-control-button.test.tsxindex 96ef6826..c4c2c09b 100644--- a/app/tests/computer-control-button.test.tsx+++ b/app/tests/computer-control-button.test.tsx@@ -264,7 +264,7 @@ test("a takeover stays shared when chat remounts before its response", async ()expect(await second.findByRole("button", { name: "Hand back" })).toBeTruthy();});-test("the labeled Computer toggle opens and closes without changing ownership", async () => {+test("the header's Computer toggle is an icon alone; taking control lives in the Computer itself", async () => {const backend = server();function Chat() {const [open, setOpen] = useState(false);@@ -280,14 +280,11 @@ test("the labeled Computer toggle opens and closes without changing ownership",);}const view = render(<Chat />);- await waitFor(() =>- expect(- view- .getByRole("button", { name: "Take control" })- .hasAttribute("disabled"),- ).toBe(false),- );- fireEvent.click(view.getByRole("button", { name: "Open Computer" }));+ const toggle = await view.findByRole("button", { name: "Open Computer" });+ await waitFor(() => expect(toggle.hasAttribute("disabled")).toBe(false));+ expect(toggle.textContent).toBe("");+ expect(view.queryByRole("button", { name: "Take control" })).toBeNull();+ fireEvent.click(toggle);expect(view.getByText("Live computer sidebar")).toBeTruthy();fireEvent.click(view.getByRole("button", { name: "Close Computer" }));expect(view.queryByText("Live computer sidebar")).toBeNull();@@ -314,7 +311,9 @@ test("an active human prompt opens once and does not fight closing the Computer"fireEvent.click(view.getByRole("button", { name: "Close Computer" }));view.rerender(<Chat />);expect(view.queryByText("Live computer sidebar")).toBeNull();- expect(view.getByRole("button", { name: "Hand back" })).toBeTruthy();+ // Closed, the icon still says the Computer wants the person; handing back is done inside it.+ expect(view.getByRole("img", { name: "Needs you" })).toBeTruthy();+ expect(view.queryByRole("button", { name: "Hand back" })).toBeNull();});test("both controls stay disabled while the current browser action drains", async () => {diff --git a/app/tests/devices-settings.test.tsx b/app/tests/devices-settings.test.tsxnew file mode 100644index 00000000..369d138a--- /dev/null+++ b/app/tests/devices-settings.test.tsx@@ -0,0 +1,69 @@+import { afterAll, afterEach, beforeAll, expect, test } from "bun:test";+import { GlobalRegistrator } from "@happy-dom/global-registrator";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { cleanup, fireEvent, render, waitFor } from "@testing-library/react";+import type { ReactNode } from "react";+import { NativeDevices, RecentDeliveries } from "@/components/settings/devices";+import { settleReactWork } from "./settle-react-work";++/** Settings → Notifications: the person's phones, and what was recently sent to them. */++beforeAll(() => GlobalRegistrator.register());+afterEach(cleanup);+afterAll(async () => {+ await settleReactWork();+ GlobalRegistrator.unregister();+});++const originalFetch = global.fetch;+afterEach(() => {+ global.fetch = originalFetch;+});++const requests: string[] = [];+function serving() {+ requests.length = 0;+ global.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {+ requests.push(`${init?.method ?? "GET"} ${String(input)}`);+ return Response.json({+ bindings: [],+ devices: [{ id: "d1", platform: "ios", enabled: true }],+ deliveries: [+ {+ id: "x",+ transport: "push",+ kind: "question",+ state: "sent",+ error: null,+ createdAt: "2026-10-09T10:00:00Z",+ },+ ],+ available: { slack: false, teams: false, sms: false, push: true },+ });+ }) as unknown as typeof fetch;+}++function draw(node: ReactNode) {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return render(+ <QueryClientProvider client={client}>{node}</QueryClientProvider>,+ );+}++test("a registered phone is listed and can be removed", async () => {+ serving();+ const view = draw(<NativeDevices />);+ expect(await view.findByText("iOS")).toBeTruthy();+ fireEvent.click(view.getByRole("button", { name: "Remove" }));+ await waitFor(() =>+ expect(requests).toContain("DELETE /api/delivery/devices/d1"),+ );+});++test("recent deliveries are listed", async () => {+ serving();+ const view = draw(<RecentDeliveries />);+ expect(await view.findByText(/push · question/)).toBeTruthy();+});diff --git a/app/tests/form-submit-controls.test.ts b/app/tests/form-submit-controls.test.tsindex 8f1f0f2c..09f05138 100644--- a/app/tests/form-submit-controls.test.ts+++ b/app/tests/form-submit-controls.test.ts@@ -11,6 +11,10 @@ import ts from "typescript";* source, Confirm phone, Turn on background research) and the recorder before them. A plain* `<button>` defaults to submit, so it counts; a `<Button>` counts only with `type="submit"`.*+ * A submit control outside the form counts when it names the form: `form={id}` matching the form's+ * own `id={id}`. A dialog does this to keep its submit in `DialogFooter` while `DialogBody` stays a+ * direct child of `DialogContent`.+ ** A form submitted some other way (the composer's Enter key and send action) names itself here with* a reason, rather than every form losing the check.*/@@ -54,13 +58,27 @@ test("every form with an onSubmit has a control that submits it", async () => {true,ts.ScriptKind.TSX,);+ /** The `form` attribute of every submit control in the file, as written. */+ const named = new Set<string>();+ const collect = (node: ts.Node) => {+ if (+ (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) &&+ submits(node)+ ) {+ const form = attribute(node, "form")?.initializer;+ if (form) named.add(form.getText());+ }+ ts.forEachChild(node, collect);+ };+ collect(source);const visit = (node: ts.Node) => {if (ts.isJsxElement(node) &&node.openingElement.tagName.getText() === "form" &&attribute(node.openingElement, "onSubmit")) {- let found = false;+ const id = attribute(node.openingElement, "id")?.initializer;+ let found = id !== undefined && named.has(id.getText());const inside = (child: ts.Node) => {if (found) return;if (diff --git a/app/tests/github-sources-settings.test.tsx b/app/tests/github-sources-settings.test.tsxnew file mode 100644index 00000000..b5364a6a--- /dev/null+++ b/app/tests/github-sources-settings.test.tsx@@ -0,0 +1,91 @@+import { afterAll, afterEach, beforeAll, expect, test } from "bun:test";+import { GlobalRegistrator } from "@happy-dom/global-registrator";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { cleanup, fireEvent, render, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { GithubSources } from "@/components/settings/github-sources";+import { settleReactWork } from "./settle-react-work";++/** Settings → Connected accounts: the repositories whose events can start a responsibility. */++beforeAll(() => GlobalRegistrator.register());+afterEach(cleanup);+afterAll(async () => {+ await settleReactWork();+ GlobalRegistrator.unregister();+});++const originalFetch = global.fetch;+afterEach(() => {+ global.fetch = originalFetch;+});++const writes: { request: string; body: unknown }[] = [];+function serving() {+ writes.length = 0;+ global.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {+ const method = init?.method ?? "GET";+ if (method !== "GET") {+ writes.push({+ request: `${method} ${String(input)}`,+ body: typeof init?.body === "string" ? JSON.parse(init.body) : null,+ });+ return Response.json({+ binding: {+ id: "g2",+ source: "github",+ repository: "acme/web",+ createdAt: "2026-10-09T10:00:00Z",+ },+ });+ }+ return Response.json({+ bindings: [+ {+ id: "g1",+ source: "github",+ repository: "acme/app",+ createdAt: "2026-10-09T10:00:00Z",+ },+ ],+ });+ }) as unknown as typeof fetch;+}++function draw() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return render(+ <QueryClientProvider client={client}>+ <GithubSources />+ </QueryClientProvider>,+ );+}++test("a connected repository shows the webhook address to paste into GitHub", async () => {+ serving();+ const view = draw();+ expect(await view.findByText("acme/app")).toBeTruthy();+ expect(view.getByText(/\/api\/events\/github\/g1$/)).toBeTruthy();+});++test("connecting a repository sends it with its secret", async () => {+ serving();+ const view = draw();+ const user = userEvent.setup({ document });+ await view.findByText("acme/app");+ await user.click(view.getByRole("button", { name: "Add a repository" }));+ await user.type(+ await view.findByRole("textbox", { name: "Repository" }),+ "acme/web",+ );+ await user.type(view.getByLabelText("Webhook secret"), "s3cret");+ fireEvent.click(view.getByRole("button", { name: "Connect events" }));+ await waitFor(() =>+ expect(writes).toContainEqual({+ request: "POST /api/responsibilities/sources/github",+ body: { repository: "acme/web", secret: "s3cret" },+ }),+ );+});diff --git a/app/tests/group-people.test.tsx b/app/tests/group-people.test.tsxnew file mode 100644index 00000000..fab85ec2--- /dev/null+++ b/app/tests/group-people.test.tsx@@ -0,0 +1,118 @@+import { afterAll, afterEach, beforeAll, expect, test } from "bun:test";+import { GlobalRegistrator } from "@happy-dom/global-registrator";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { cleanup, fireEvent, render, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { GroupPeopleButton } from "@/components/channels/group-people";+import { settleReactWork } from "./settle-react-work";++/**+ * Who is in a group, from a button in its top bar: the people in it, taking someone out or leaving,+ * and adding someone by email. It used to float above the composer.+ */++beforeAll(() => GlobalRegistrator.register());+afterEach(cleanup);+afterAll(async () => {+ await settleReactWork();+ GlobalRegistrator.unregister();+});++const originalFetch = global.fetch;+afterEach(() => {+ global.fetch = originalFetch;+});++let people: Record<string, unknown>[] = [];+const requests: string[] = [];+function serving(initial: Record<string, unknown>[]) {+ people = initial;+ requests.length = 0;+ global.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ const method = init?.method ?? "GET";+ if (method !== "GET") {+ requests.push(`${method} ${url} ${init?.body ?? ""}`);+ if (method === "POST") {+ people = [+ ...people,+ {+ userId: "u3",+ email: "[email protected]",+ name: "Sam",+ creator: false,+ },+ ];+ }+ return Response.json({ ok: true });+ }+ if (url === "/api/me") {+ return Response.json({+ user: { id: "me", role: "user", email: "[email protected]" },+ });+ }+ return Response.json({ bots: [], people, messages: [] });+ }) as unknown as typeof fetch;+}++function draw() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return render(+ <QueryClientProvider client={client}>+ <GroupPeopleButton channelId="group-1" />+ </QueryClientProvider>,+ );+}++const ME = {+ userId: "me",+ email: "[email protected]",+ name: null,+ creator: true,+};+const ALEX = {+ userId: "u2",+ email: "[email protected]",+ name: "Alex",+ creator: false,+};++test("the top bar says how many people are in the group", async () => {+ serving([ME, ALEX]);+ const view = draw();+ expect(await view.findByRole("button", { name: "2 people" })).toBeTruthy();+});++test("the creator sees everyone and can take another person out", async () => {+ serving([ME, ALEX]);+ const view = draw();+ fireEvent.click(await view.findByRole("button", { name: "2 people" }));+ expect(await view.findByText("Alex")).toBeTruthy();+ expect(view.getByText("You")).toBeTruthy();+ fireEvent.click(+ view.getByRole("button", { name: "Remove [email protected]" }),+ );+ await waitFor(() =>+ expect(requests).toContain("DELETE /api/groups/group-1/members/u2 "),+ );+});++test("adding someone by email lists them without reopening the dialog", async () => {+ serving([ME]);+ const view = draw();+ fireEvent.click(await view.findByRole("button", { name: "1 person" }));+ const user = userEvent.setup({ document });+ await user.type(+ await view.findByRole("textbox", { name: "Their email" }),+ "[email protected]",+ );+ fireEvent.click(view.getByRole("button", { name: "Add" }));+ await waitFor(() =>+ expect(requests).toContain(+ 'POST /api/groups/group-1/members {"email":"[email protected]"}',+ ),+ );+ expect(await view.findByText("Sam")).toBeTruthy();+});diff --git a/app/tests/item-disabled.test.tsx b/app/tests/item-disabled.test.tsxnew file mode 100644index 00000000..a8890b0b--- /dev/null+++ b/app/tests/item-disabled.test.tsx@@ -0,0 +1,31 @@+import { afterAll, afterEach, beforeAll, expect, test } from "bun:test";+import { GlobalRegistrator } from "@happy-dom/global-registrator";+import { cleanup, render } from "@testing-library/react";+import { Item, ItemContent, ItemTitle } from "@/components/ui/item";+import { settleReactWork } from "./settle-react-work";++/**+ * A row drawn as a button can be disabled — "Run now" while a run is starting — and has to look it,+ * or it reads as a button that ignores the click.+ */++beforeAll(() => GlobalRegistrator.register());+afterEach(cleanup);+afterAll(async () => {+ await settleReactWork();+ GlobalRegistrator.unregister();+});++test("a row drawn as a disabled button is dimmed and takes no pointer", () => {+ const view = render(+ <Item render={<button disabled type="button" />} size="sm">+ <ItemContent>+ <ItemTitle>Run now</ItemTitle>+ </ItemContent>+ </Item>,+ );+ const row = view.getByRole("button", { name: "Run now" });+ expect(row.hasAttribute("disabled")).toBe(true);+ expect(row.className).toContain("disabled:opacity-50");+ expect(row.className).toContain("disabled:pointer-events-none");+});diff --git a/app/tests/legacy-agent-routes.test.ts b/app/tests/legacy-agent-routes.test.tsnew file mode 100644index 00000000..30bb64db--- /dev/null+++ b/app/tests/legacy-agent-routes.test.ts@@ -0,0 +1,36 @@+import { expect, test } from "bun:test";+import { LEGACY_PAGES, legacyAgentsTarget } from "@/lib/agents/legacy-routes";++test("/agents?agent=<id> opens that Bot's page", () => {+ expect(legacyAgentsTarget({ agent: "agent_1" })).toEqual({+ to: "/bots/$agentId",+ params: { agentId: "agent_1" },+ replace: true,+ });+});++test("/agents?new=true opens the new-Bot wizard on the roster", () => {+ expect(legacyAgentsTarget({ new: true })).toEqual({+ to: "/bots",+ search: { new: true },+ replace: true,+ });+});++test("/agents on its own is the roster", () => {+ expect(legacyAgentsTarget({})).toEqual({ to: "/bots", replace: true });+});++test("creating wins over opening, as it did on /agents", () => {+ expect(legacyAgentsTarget({ new: true, agent: "agent_1" }).to).toBe("/bots");+});++test("pages that left the sidebar send people to where their contents went", () => {+ expect(LEGACY_PAGES).toEqual({+ "/approvals": "/settings/approvals",+ "/memory": "/settings/memory",+ "/reachability": "/settings/notifications",+ "/responsibilities": "/bots",+ "/group/new": "/channel/new",+ });+});diff --git a/app/tests/mark-open-channel-read.test.tsx b/app/tests/mark-open-channel-read.test.tsxnew file mode 100644index 00000000..c04315f5--- /dev/null+++ b/app/tests/mark-open-channel-read.test.tsx@@ -0,0 +1,86 @@+import { afterAll, afterEach, beforeAll, expect, test } from "bun:test";+import { GlobalRegistrator } from "@happy-dom/global-registrator";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { cleanup, render, waitFor } from "@testing-library/react";+import { useMarkOpenChannelRead } from "@/lib/channels/mark-read";+import { settleReactWork } from "./settle-react-work";++/**+ * Having a conversation on screen marks it read — a group as much as a one-Bot conversation — so+ * neither its sidebar dot nor the Bots badge stays lit while the person is looking at the reply.+ */++beforeAll(() => GlobalRegistrator.register());+afterEach(cleanup);+afterAll(async () => {+ await settleReactWork();+ GlobalRegistrator.unregister();+});++const originalFetch = global.fetch;+afterEach(() => {+ global.fetch = originalFetch;+});++const row = (id: string, lastReadAt: string | null) => ({+ id,+ name: "Expense Review, General Assistant",+ agentIds: ["expenses", "general"],+ active: true,+ summary: null,+ lastMessage: "Done.",+ lastMessageAgentId: "expenses",+ lastMessageAt: "2026-10-09T10:00:00.000Z",+ createdAt: "2026-10-09T09:00:00.000Z",+ pinned: false,+ lastReadAt,+});++const writes: string[] = [];+function serving(lastReadAt: string | null) {+ writes.length = 0;+ global.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {+ const method = init?.method ?? "GET";+ if (method !== "GET") {+ writes.push(`${method} ${String(input)}`);+ return new Response(null, { status: 204 });+ }+ return Response.json({+ channels: [row("group-1", lastReadAt)],+ nextCursor: null,+ });+ }) as unknown as typeof fetch;+}++function Open({ channelId }: { channelId: string }) {+ useMarkOpenChannelRead(channelId);+ return null;+}++function draw() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return render(+ <QueryClientProvider client={client}>+ <Open channelId="group-1" />+ </QueryClientProvider>,+ );+}++test("an open group with a Bot's reply the person has not seen is marked read, once", async () => {+ serving(null);+ draw();+ await waitFor(() =>+ expect(writes).toEqual(["PUT /api/channels/group-1/read"]),+ );+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(writes).toHaveLength(1);+});++test("an open group already read is left alone", async () => {+ serving("2026-10-09T11:00:00.000Z");+ draw();+ await new Promise((resolve) => setTimeout(resolve, 100));+ expect(writes).toEqual([]);+});diff --git a/app/tests/memory-settings.test.tsx b/app/tests/memory-settings.test.tsxnew file mode 100644index 00000000..d24557b9--- /dev/null+++ b/app/tests/memory-settings.test.tsx@@ -0,0 +1,155 @@+import { afterAll, afterEach, beforeAll, expect, test } from "bun:test";+import { GlobalRegistrator } from "@happy-dom/global-registrator";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { cleanup, fireEvent, render, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import type { ReactNode } from "react";+import { MemoryList, RememberFact } from "@/components/memory/memories";+import { settleReactWork } from "./settle-react-work";++/** Settings → Memory: what the person's Bots know about them, and which Bot learned it. */++beforeAll(() => GlobalRegistrator.register());+afterEach(cleanup);+afterAll(async () => {+ await settleReactWork();+ GlobalRegistrator.unregister();+});++const originalFetch = global.fetch;+afterEach(() => {+ global.fetch = originalFetch;+});++const memory = (overrides: Record<string, unknown>) => ({+ id: "m1",+ content: "I prefer mornings.",+ provenance: "You told a Bot",+ sourceId: null,+ enabled: true,+ reviewState: "confirmed",+ formedBy: "person",+ formedByAgentId: null,+ sourceApp: null,+ sourceLink: null,+ observedAt: null,+ updatedAt: "2026-10-09T10:00:00Z",+ ...overrides,+});++const writes: { request: string; body: unknown }[] = [];+/** A refusal the server gives the next write, or none. */+let refuseWrite: string | null = null;+function serving() {+ writes.length = 0;+ refuseWrite = null;+ global.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ const method = init?.method ?? "GET";+ if (method !== "GET") {+ writes.push({+ request: `${method} ${url}`,+ body: typeof init?.body === "string" ? JSON.parse(init.body) : null,+ });+ if (refuseWrite) {+ const error = refuseWrite;+ refuseWrite = null;+ return Response.json({ error }, { status: 400 });+ }+ return Response.json({ ok: true });+ }+ if (url.startsWith("/api/agents")) {+ return Response.json({+ agents: [{ id: "expenses", name: "Expenses", mine: true }],+ });+ }+ return Response.json({+ memories: [+ memory({}),+ memory({+ id: "m2",+ content: "Receipts go to finance@.",+ formedBy: "bot",+ formedByAgentId: "expenses",+ sourceApp: "Gmail",+ reviewState: "unreviewed",+ }),+ ],+ });+ }) as unknown as typeof fetch;+}++function draw(node: ReactNode) {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return render(+ <QueryClientProvider client={client}>{node}</QueryClientProvider>,+ );+}++test("a memory a Bot formed names the Bot that formed it", async () => {+ serving();+ const view = draw(<MemoryList />);+ expect(await view.findByText(/Formed by Expenses/)).toBeTruthy();+});++test("remembering a fact saves it", async () => {+ serving();+ const view = draw(<RememberFact />);+ const user = userEvent.setup({ document });+ // The form lives in a dialog behind the page's action, not on the page.+ fireEvent.click(view.getByRole("button", { name: "Remember a fact" }));+ await user.type(+ await view.findByRole("textbox", {+ name: "Something you want your Bots to know",+ }),+ "I work from Lisbon.",+ );+ fireEvent.click(view.getByRole("button", { name: "Remember" }));+ await waitFor(() =>+ expect(writes).toContainEqual({+ request: "POST /api/memory",+ body: { content: "I work from Lisbon." },+ }),+ );+});++test("each memory's switch is named for the memory it turns on or off", async () => {+ serving();+ const view = draw(<MemoryList />);+ expect(+ await view.findByRole("switch", {+ name: "Use this memory: I prefer mornings.",+ }),+ ).toBeTruthy();+ expect(+ view.getByRole("switch", {+ name: "Use this memory: Receipts go to finance@.",+ }),+ ).toBeTruthy();+});++test("reopening Remember a fact after a failure starts clean", async () => {+ serving();+ refuseWrite = "Memory is full.";+ const view = draw(<RememberFact />);+ const user = userEvent.setup({ document });+ await user.click(view.getByRole("button", { name: "Remember a fact" }));+ await user.type(+ await view.findByRole("textbox", {+ name: "Something you want your Bots to know",+ }),+ "I work from Lisbon.",+ );+ await user.click(view.getByRole("button", { name: "Remember" }));+ expect((await view.findByRole("alert")).textContent).toBe("Memory is full.");+ await user.keyboard("{Escape}");+ await waitFor(() => expect(view.queryByRole("dialog")).toBeNull());+ await user.click(view.getByRole("button", { name: "Remember a fact" }));+ const field = (await view.findByRole("textbox", {+ name: "Something you want your Bots to know",+ })) as HTMLTextAreaElement;+ expect(field.value).toBe("");+ expect(view.queryByRole("alert")).toBeNull();+});diff --git a/app/tests/proposed-bot-card.test.tsx b/app/tests/proposed-bot-card.test.tsxindex c34a6295..b9fde267 100644--- a/app/tests/proposed-bot-card.test.tsx+++ b/app/tests/proposed-bot-card.test.tsx@@ -80,7 +80,7 @@ function routed(node: ReactNode) {}),createRoute({getParentRoute: () => rootRoute,- path: "/agents",+ path: "/bots/$agentId",component: () => null,}),]);@@ -88,7 +88,7 @@ function routed(node: ReactNode) {routeTree,history: createMemoryHistory({ initialEntries: ["/"] }),});- // The app's router is registered globally for typing; this one only has to resolve /agents.+ // The app's router is registered globally for typing; this one only has to resolve /bots/$agentId.return render(<RouterProvider router={router as never} />);}@@ -293,7 +293,7 @@ test("a completed card links to the coworker, rebuilt from the answer alone", as);const link = await view.findByText("Open Renewal Desk");- expect(link.closest("a")?.getAttribute("href")).toContain("agent=agent_1");+ expect(link.closest("a")?.getAttribute("href")).toBe("/bots/agent_1");});/**@@ -311,3 +311,12 @@ test("the created answer carries an id the card can read back", () => {expect(wasCreated(botCardAnswer.declined())).toBe(false);expect(createdBotIdIn(botCardAnswer.declined())).toBeNull();});++test("an answer written before Bot pages existed still links to the coworker it made", () => {+ // Conversations people scroll back through still hold the old sentence.+ expect(+ createdBotIdIn(+ "Created. Tell the person that its profile is at /agents?agent=agent_9.",+ ),+ ).toBe("agent_9");+});diff --git a/app/tests/start-group.test.ts b/app/tests/start-group.test.tsnew file mode 100644index 00000000..130195b1--- /dev/null+++ b/app/tests/start-group.test.ts@@ -0,0 +1,98 @@+import { expect, test } from "bun:test";+import { startGroupWith } from "../src/lib/channels/start";++/**+ * A conversation started with two or more Bots in the To: field is a group: created with the Bots in+ * the order they were picked, then given the first message, then opened. Nothing is sent if the+ * group could not be made.+ */++test("creates the group in pick order, sends the first message, then opens it", async () => {+ const calls: string[] = [];+ await startGroupWith({+ agentIds: ["knowledge", "risk-analyst"],+ text: "Compare the two policies.",+ create: async (agentIds) => {+ calls.push(`create ${agentIds.join(",")}`);+ return { id: "channel-1" };+ },+ send: async (channelId, text) => {+ calls.push(`send ${channelId} ${text}`);+ },+ discard: async (channelId) => {+ calls.push(`discard ${channelId}`);+ },+ open: async (channelId) => {+ calls.push(`open ${channelId}`);+ },+ });+ expect(calls).toEqual([+ "create knowledge,risk-analyst",+ "send channel-1 Compare the two policies.",+ "open channel-1",+ ]);+});++test("a first message that does not send discards the empty group and opens nothing", async () => {+ const calls: string[] = [];+ await expect(+ startGroupWith({+ agentIds: ["knowledge", "risk-analyst"],+ text: "Compare the two policies.",+ create: async () => {+ calls.push("create");+ return { id: "channel-1" };+ },+ send: async () => {+ throw new Error("Your message could not be sent to the group.");+ },+ discard: async (channelId) => {+ calls.push(`discard ${channelId}`);+ },+ open: async () => {+ calls.push("open");+ },+ }),+ ).rejects.toThrow("Your message could not be sent to the group.");+ expect(calls).toEqual(["create", "discard channel-1"]);+});++test("a discard that also fails still reports the message's failure, not the discard's", async () => {+ await expect(+ startGroupWith({+ agentIds: ["knowledge", "risk-analyst"],+ text: "Hello.",+ create: async () => ({ id: "channel-1" }),+ send: async () => {+ throw new Error("Your message could not be sent to the group.");+ },+ discard: async () => {+ throw new Error("Could not delete this channel");+ },+ open: async () => undefined,+ }),+ ).rejects.toThrow("Your message could not be sent to the group.");+});++test("a group that could not be made sends nothing and opens nothing", async () => {+ const calls: string[] = [];+ await expect(+ startGroupWith({+ agentIds: ["knowledge", "risk-analyst"],+ text: "Hello.",+ create: async () => {+ throw new Error("The group could not be started.");+ },+ send: async () => {+ calls.push("send");+ },+ discard: async () => {+ calls.push("discard");+ },+ open: async () => {+ calls.push("open");+ },+ }),+ ).rejects.toThrow("The group could not be started.");+ expect(calls).toEqual([]);+});diff --git a/app/tests/update-routing-configured.test.tsx b/app/tests/update-routing-configured.test.tsxnew file mode 100644index 00000000..02299540--- /dev/null+++ b/app/tests/update-routing-configured.test.tsx@@ -0,0 +1,87 @@+import { afterAll, afterEach, beforeAll, expect, test } from "bun:test";+import { GlobalRegistrator } from "@happy-dom/global-registrator";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { cleanup, render } from "@testing-library/react";+import { UpdateRoutingSection } from "@/components/settings/update-routing";+import { settleReactWork } from "./settle-react-work";++/**+ * Settings → Notifications only shows a channel as on when this deployment has set it up. A channel+ * that is not configured is off, disabled and says so, whatever the stored preference says.+ */++beforeAll(() => GlobalRegistrator.register());+afterEach(cleanup);+afterAll(async () => {+ await settleReactWork();+ GlobalRegistrator.unregister();+});++const originalFetch = global.fetch;+afterEach(() => {+ global.fetch = originalFetch;+});++function serving(available: {+ slack: boolean;+ teams: boolean;+ sms: boolean;+ push: boolean;+}) {+ global.fetch = (async (input: RequestInfo | URL) => {+ const url = String(input);+ if (url.endsWith("/api/bots/routing")) {+ return Response.json({+ routing: { progress: "all", decision: "all", question: "all" },+ });+ }+ if (url.endsWith("/api/delivery")) {+ return Response.json({+ bindings: [],+ devices: [],+ deliveries: [],+ available,+ });+ }+ return new Response(null, { status: 404 });+ }) as unknown as typeof fetch;+}++function draw() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return render(+ <QueryClientProvider client={client}>+ <UpdateRoutingSection />+ </QueryClientProvider>,+ );+}++const checked = (element: HTMLElement) =>+ element.getAttribute("aria-checked") === "true" ||+ element.hasAttribute("data-checked");+const disabled = (element: HTMLElement) =>+ element.getAttribute("aria-disabled") === "true" ||+ element.hasAttribute("data-disabled") ||+ element.hasAttribute("disabled");++test("channels the deployment has not set up are off, disabled and say so", async () => {+ serving({ slack: false, teams: false, sms: false, push: true });+ const view = draw();+ const slack = await view.findByRole("switch", { name: "Progress by Slack" });+ expect(checked(slack)).toBe(false);+ expect(disabled(slack)).toBe(true);+ expect(view.getAllByText("Not set up").length).toBe(9);+ const push = view.getByRole("switch", { name: "Progress by Push" });+ expect(checked(push)).toBe(true);+ expect(disabled(push)).toBe(false);+});++test("a configured channel shows the person's preference", async () => {+ serving({ slack: true, teams: true, sms: true, push: true });+ const view = draw();+ const slack = await view.findByRole("switch", { name: "Progress by Slack" });+ expect(checked(slack)).toBe(true);+ expect(view.queryByText("Not set up")).toBeNull();+});diff --git a/app/tests/update-routing-settings.test.tsx b/app/tests/update-routing-settings.test.tsxnew file mode 100644index 00000000..7126af01--- /dev/null+++ b/app/tests/update-routing-settings.test.tsx@@ -0,0 +1,68 @@+import { afterAll, afterEach, beforeAll, expect, test } from "bun:test";+import { GlobalRegistrator } from "@happy-dom/global-registrator";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { cleanup, fireEvent, render, waitFor } from "@testing-library/react";+import { UpdateRoutingSection } from "@/components/settings/update-routing";+import { settleReactWork } from "./settle-react-work";++/**+ * Where updates go, now in Settings: one decision for all of a person's Bots, so it is no longer+ * repeated on every Bot's page.+ */++beforeAll(() => GlobalRegistrator.register());+afterEach(cleanup);+afterAll(async () => {+ await settleReactWork();+ GlobalRegistrator.unregister();+});++const originalFetch = global.fetch;+afterEach(() => {+ global.fetch = originalFetch;+});++const writes: { request: string; body: unknown }[] = [];+function serving() {+ writes.length = 0;+ global.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {+ const method = init?.method ?? "GET";+ if (method !== "GET") {+ writes.push({+ request: `${method} ${String(input)}`,+ body: typeof init?.body === "string" ? JSON.parse(init.body) : null,+ });+ return Response.json({ ok: true });+ }+ // A deployment with every channel set up, so each switch reflects the person's preference.+ if (String(input).endsWith("/api/delivery")) {+ return Response.json({+ bindings: [],+ devices: [],+ deliveries: [],+ available: { slack: true, teams: true, sms: true, push: true },+ });+ }+ return Response.json({+ routing: { progress: ["push"], decision: "all", question: "all" },+ });+ }) as unknown as typeof fetch;+}++test("switching a transport on for one kind of update saves that kind's transports", async () => {+ serving();+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ const view = render(+ <QueryClientProvider client={client}>+ <UpdateRoutingSection />+ </QueryClientProvider>,+ );+ fireEvent.click(await view.findByRole("switch", { name: "Progress by SMS" }));+ await waitFor(() => expect(writes).toHaveLength(1));+ expect(writes[0]).toEqual({+ request: "PUT /api/bots/routing/progress",+ body: { transports: ["push", "sms"] },+ });+});diff --git a/desktop/src-tauri/src/desktop_host_access.rs b/desktop/src-tauri/src/desktop_host_access.rsindex 44a26140..6318f18d 100644--- a/desktop/src-tauri/src/desktop_host_access.rs+++ b/desktop/src-tauri/src/desktop_host_access.rs@@ -168,7 +168,7 @@ impl<R: tauri::Runtime> HostApprovalUi for NativeApproval<R> {)} else {format!(- "Your OpenBot setting: {}. Change it in Approvals.",+ "Your OpenBot setting: {}. Change it in Settings → Approvals.",request.command_policy.label())};diff --git a/docs/configuration.md b/docs/configuration.mdindex 8a0141f0..c914468f 100644--- a/docs/configuration.md+++ b/docs/configuration.md@@ -450,7 +450,7 @@ zero or more: a deployment that typed `two` and silently got the default would bcap.Which Bots may address which is a grant, not a variable, and no Bot may address any other until one-is made. It is made on the Bot's own screen: open it from **Agents**, and switch on each Bot under+is made. It is made on the Bot's own page: open it from **Bots**, choose **Skills and access**, and switch on each Bot under**Bots it may ask**. The pair is directional: that list is who this Bot may ask, not who may ask it,so letting them ask each other is two switches. Only an administrator may change it; anyone who cansee the Bot can read it.@@ -471,7 +471,7 @@ Slack app of its own.| `OPENTAG_BOT_ICON_URL_TEMPLATE` | Optional `https` PNG URL with `{seed}` (the Bot's avatar seed) or `{agentId}`, used as the Bot's Slack icon on proactive posts. |Point OpenTag's `AGENT_URL` at `<public URL>/api/delivery/webhooks/opentag/agent`. A person links-their Slack or Teams identity from **Reachability**: OpenBot shows a one-time `link <code>` message,+their Slack or Teams identity from a Bot's page, under **Reaching you**: OpenBot shows a one-time `link <code>` message,valid for ten minutes, which they send to the OpenTag app. After that, only that person's messagesreach their chosen Bot, in their own OpenBot conversation, with learning, governance, approvals andaudit on every turn. Anyone unlinked is told how to link and nothing runs. Approval requests appear@@ -496,7 +496,7 @@ some of a provider's variables and not all of them stops the server at start-up| `DELIVERY_PUBLIC_URL` | The public origin providers call back on, such as a tunnel or an ingress. Twilio signs each request over the URL it was given, so this has to be the address Twilio was configured with. Unset, OpenBot uses `OPENBOT_PUBLIC_URL`, then `BETTER_AUTH_URL`. It must be an `http(s)` URL or the server does not start. || `TWILIO_ACCOUNT_SID` | Twilio account SID. One of the four SMS settings, which are set together. || `TWILIO_AUTH_TOKEN` | Twilio auth token. Used to send and to check the signature on every request Twilio makes. |-| `TWILIO_VERIFY_SERVICE_SID` | The Twilio Verify service that texts the code a person enters on **Reachability** to confirm their number. |+| `TWILIO_VERIFY_SERVICE_SID` | The Twilio Verify service that texts the code a person enters under a Bot's **Reaching you** to confirm their number. || `TWILIO_FROM_NUMBER` | The Twilio number OpenBot sends from. || `EXPO_PROJECT_ID` | The native app's EAS project id, a UUID. Switches on push notifications and sign-in from the native app (without it, the server does not trust the app's `openbotmobile://` sign-in redirect). A device registers only when the app reports this same project id; any other value is refused. A value that is not a UUID stops the server at start-up. || `EXPO_ACCESS_TOKEN` | Optional. Sent as `Authorization: Bearer` on every request to Expo's push service; without it those requests carry no token. |diff --git a/docs/coworkers.md b/docs/coworkers.mdindex d641ec80..6fbc209c 100644--- a/docs/coworkers.md+++ b/docs/coworkers.md@@ -45,7 +45,7 @@ The message is ordinary AG-UI system content, so it works with any AG-UI-compatiFiltering happens in server/database queries. Package-provided agents cannot be edited or deleted through the product.An owner can also publish a Bot as a Team Bot, to everybody signed in or to named people and groups-(`/api/team-bots`, the **Team Bots** screen). Publishing is a separate, revocable record; the Bot's own+(`/api/team-bots`, the Bot's **Sharing** page). Publishing is a separate, revocable record; the Bot's ownvisibility is unchanged by it. A published Bot stays invisible to teammates until it has a roledescription and a name other than a placeholder such as "New Bot".@@ -65,7 +65,7 @@ Each channel routes through a channel-local proxy agent id, pinned to that channDeleting is soft. The coworker stops running, but existing channels remain readable for their members and restore as tombstones.-Hiding and pinning are personal roster state. Hiding removes the coworker from one user's list without disabling the coworker for anyone else; pinning moves it into the **Pinned** section at the top of `/agents` for that user only.+Hiding and pinning are personal roster state. Hiding removes the coworker from one user's list without disabling the coworker for anyone else; pinning moves it into the **Pinned** section at the top of `/bots` for that user only. A Team Bot an administrator assigned to a group is always pinned for its members.## Default endpoint@@ -98,7 +98,7 @@ agents:endpoint: http://risk.internal/ag-ui```-In the product, create or edit a coworker from `/agents` and set:+In the product, create a coworker from `/bots` and edit it from its page's **Setup**, and set:- name;- title;diff --git a/examples/pydantic-ai-bot/README.md b/examples/pydantic-ai-bot/README.mdindex e5aea19c..db8a5bee 100644--- a/examples/pydantic-ai-bot/README.md+++ b/examples/pydantic-ai-bot/README.md@@ -46,7 +46,7 @@ that require Responses.## Register it-Give a coworker this endpoint, either from `/agents` in the UI or as a `remote-ag-ui` agent in a+Give a coworker this endpoint, either from `/bots` in the UI or as a `remote-ag-ui` agent in atenant package:```yamldiff --git a/scripts/start.sh b/scripts/start.shindex 237e8d61..d8a2fed1 100755--- a/scripts/start.sh+++ b/scripts/start.sh@@ -424,7 +424,7 @@ $(green "Ready. http://localhost:$APP_PORT")Next steps:- Direct Bot chat: http://localhost:$APP_PORT/bot- - Coworkers: http://localhost:$APP_PORT/agents+ - Bots: http://localhost:$APP_PORT/bots- Audit trail: http://localhost:$APP_PORT/admin/audit- Boundaries/policy: http://localhost:$APP_PORT/admin/boundaries- Setup docs: README.md@@ -433,7 +433,7 @@ Next steps:Try:1. Open /bot and ask: Open news.ycombinator.com and tell me the top story.- 2. Create a coworker in /agents and start a channel with it.+ 2. Create a Bot in /bots and start a channel with it.3. Review browser/file actions in /admin/audit.4. Add a deny rule in /admin/boundaries, then retry the same action.diff --git a/server/src/agents/handoff-tool.ts b/server/src/agents/handoff-tool.tsindex c078e778..53c1301a 100644--- a/server/src/agents/handoff-tool.ts+++ b/server/src/agents/handoff-tool.ts@@ -253,7 +253,7 @@ async function sharePermission(return `${input.refused}: ${verdict.message}`;const initiator = continuation?.initiator;if (initiator && initiator.kind !== "person") throw verdict.suspension;- return `${input.refused} yet: ${verdict.message} Tell the person you are waiting for their permission in Approvals.`;+ return `${input.refused} yet: ${verdict.message} Tell the person you are waiting for their permission on your page in OpenBot.`;}/** Re-exported so callers of this module do not need to know where it is declared. */diff --git a/server/src/approvals/questions.ts b/server/src/approvals/questions.tsindex 1246b5ae..c3de0b2c 100644--- a/server/src/approvals/questions.ts+++ b/server/src/approvals/questions.ts@@ -42,6 +42,31 @@ export const questionResponseMessage = (role: "user" as const,content: `In response to your question: ${question.question}\n\n${response}`,});+/**+ * A waiting question as the person's inbox lists it, or null for a row that is not one.+ *+ * `conversationBotId` is the Bot whose conversation the question belongs to: for a hand-off, the Bot+ * that handed the work on, not the one that asked. It is the Bot the attention badge and the Bot's+ * activity count the question under, so a screen showing one Bot's questions filters on it.+ */+export function listedQuestion(row: {+ key: string;+ payload: unknown;+ createdAt: Date;+}) {+ const value = questionSchema.safeParse(row.payload);+ return value.success+ ? {+ id: row.key,+ botId: value.data.botId,+ conversationBotId: questionConversationBot(value.data),+ threadId: value.data.threadId,+ question: value.data.question,+ why: value.data.why,+ createdAt: row.createdAt,+ }+ : null;+}export type ApprovalQuestions = ReturnType<typeof createApprovalQuestions>;export function createApprovalQuestions(database: Database,@@ -61,21 +86,7 @@ export function createApprovalQuestions(.where(and(owned(owner), isNull(workItems.finishedAt))).orderBy(desc(workItems.createdAt)).limit(100);- return rows- .map((row) => {- const value = questionSchema.safeParse(row.payload);- return value.success- ? {- id: row.key,- botId: value.data.botId,- threadId: value.data.threadId,- question: value.data.question,- why: value.data.why,- createdAt: row.createdAt,- }- : null;- })- .filter((row) => row !== null);+ return rows.map(listedQuestion).filter((row) => row !== null);},async respond(owner: string, id: string, response: string) {const answer = z.string().trim().min(1).max(6000).parse(response);diff --git a/server/src/approvals/service.ts b/server/src/approvals/service.tsindex 295446f1..e66c34fa 100644--- a/server/src/approvals/service.ts+++ b/server/src/approvals/service.ts@@ -40,7 +40,7 @@ export const DECLINED_BY_PERSON ="The person declined this action when you asked for their approval, so it was not done. This was their decision, not a policy or a boundary. Do not try this action, or anything equivalent, again in this conversation unless the person asks you to in words; tell them you did not do it because they declined.";/** What a Bot retrying an action that is still waiting is told, instead of opening a second request. */export const ALREADY_WAITING =- "An identical request is already waiting for the person's decision in Approvals, so this was not done and no second request was made. Do not repeat it; wait for their answer.";+ "An identical request is already waiting for the person's decision on the Bot's page in OpenBot, so this was not done and no second request was made. Do not repeat it; wait for their answer.";export const WITHDRAWN_APPROVALS_OFF ="Not done: this request was withdrawn because the person switched off asking before changes. Try the action again if it is still needed.";export const WITHDRAWN_RULE_ALLOWS =@@ -362,7 +362,7 @@ export function createApprovalService(const handOff = request.action.policy?.behaviour === "hand_off";throw new HeadlessToolSuspension(handOff- ? `This needs you: ${request.action.policy?.reason} Do it yourself, then mark it done in Approvals.`+ ? `This needs you: ${request.action.policy?.reason} Do it yourself, then mark it done on the Bot's page in OpenBot.`: "This action is waiting for your approval.",{kind: "approval",diff --git a/server/src/approvals/types.ts b/server/src/approvals/types.tsindex 5a902ee5..9393db0d 100644--- a/server/src/approvals/types.ts+++ b/server/src/approvals/types.ts@@ -315,7 +315,7 @@ export function approvalAction(candidate: ApprovalCandidate): ApprovalAction {!continuation.toolCallId)throw new ApprovalRefusedError(- "This action needs your approval, but it was not started from a conversation that can ask you. Nothing was done. Ask for it in a chat with this Bot, or change your rules in Approvals.",+ "This action needs your approval, but it was not started from a conversation that can ask you. Nothing was done. Ask for it in a chat with this Bot, or change your rules in Settings → Approvals.",);if (![diff --git a/server/src/delivery/opentag-agent.ts b/server/src/delivery/opentag-agent.tsindex a3d1494f..544a86c9 100644--- a/server/src/delivery/opentag-agent.ts+++ b/server/src/delivery/opentag-agent.ts@@ -100,7 +100,7 @@ const platformName = (transport: ChatTransport) =>transport === "teams" ? "Microsoft Teams" : "Slack";export function linkInstructions(transport: ChatTransport) {- return `I don't know who you are in OpenBot yet, so I did not run anything. In OpenBot, open Reachability, choose the conversation and Bot, pick ${platformName(transport)}, and send me the \`link <code>\` message it shows you.`;+ return `I don't know who you are in OpenBot yet, so I did not run anything. In OpenBot, open the Bot's page, choose Reaching you and the conversation, pick ${platformName(transport)}, and send me the \`link <code>\` message it shows you.`;}export async function handleOpenTagRun(@@ -273,11 +273,11 @@ async function answer(const card = await approvalCard(deps, result.binding, approvalId);if (result.extras.approvals.length > 1)parts.push(- `${result.extras.approvals.length - 1} more approval request(s) are waiting in your OpenBot approval inbox.`,+ `${result.extras.approvals.length - 1} more approval request(s) are waiting on the Bot's page in OpenBot.`,);if (card) return { text: parts.join("\n\n"), interrupt: card };parts.push(- "Your Bot is waiting for an approval. Open your OpenBot approval inbox to review it.",+ "Your Bot is waiting for an approval. Open the Bot's page in OpenBot to review it.",);} else if (result.kind === "waiting" && !parts.length) {parts.push("Your Bot is waiting for a person. Open OpenBot to continue.");@@ -324,7 +324,7 @@ async function answerPrivately(for (const approvalId of result.extras.approvals)await deps.router.notify(scope, {id: approvalId,- text: `${bot?.name ?? "Your Bot"} is waiting for your approval. Open your OpenBot approval inbox to review it.`,+ text: `${bot?.name ?? "Your Bot"} is waiting for your approval. Open the Bot's page in OpenBot to review it.`,kind: "approval",requestId: approvalId,});@@ -430,12 +430,12 @@ async function decideFromCard(};if (!deps.approvals)return {- text: "Approvals from chat are unavailable on this deployment. Decide in your OpenBot approval inbox.",+ text: "Approvals from chat are unavailable on this deployment. Decide on the Bot's page in OpenBot.",};const person = parseChannelUser(resume.by);if (!person)return {- text: "This approval card did not say who answered it, so nothing was decided. Update OpenTag, or decide in your OpenBot approval inbox.",+ text: "This approval card did not say who answered it, so nothing was decided. Update OpenTag, or decide on the Bot's page in OpenBot.",};// The clicker is mapped exactly like a message sender; OpenTag already refused anyone but the// named approver, and OpenBot then decides only as that binding's owner.diff --git a/server/src/host-access/broker.ts b/server/src/host-access/broker.tsindex e457657d..e55042b4 100644--- a/server/src/host-access/broker.ts+++ b/server/src/host-access/broker.ts@@ -292,7 +292,7 @@ export function createHostAccessBroker(: "ask";if (commandPolicy === "never")throw new HostAccessRefusedError(- "Commands on your computer are set to never run, by you or by your team. Change it in Approvals if you want Bots to run commands here.",+ "Commands on your computer are set to never run, by you or by your team. Change it in Settings → Approvals if you want Bots to run commands here.",);// Safety requirements, rules and auto-review apply whatever the command policy is.const approval =diff --git a/server/src/index.ts b/server/src/index.tsindex 7ea845e5..d038b09c 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -547,7 +547,7 @@ const approvalService = createApprovalService(id: request.id,kind: "approval",requestId: request.id,- text: `${botName} asks for approval to use ${action.toolRef}. Open your OpenBot approval inbox to review this action.`,+ text: `${botName} asks for approval to use ${action.toolRef}. Open the Bot's page in OpenBot to review this action.`,},);}diff --git a/server/src/proactive/engine.ts b/server/src/proactive/engine.tsindex 7db2dd96..2d852a28 100644--- a/server/src/proactive/engine.ts+++ b/server/src/proactive/engine.ts@@ -222,7 +222,7 @@ export function createProactiveEngine(deps: ProactiveEngineDeps) {await deps.notify(scope, {id: `suggestion:${suggestion.id}`,kind: "reply",- text: `Suggested next step: ${suggestion.title}\n${suggestion.detail}${suggestion.sourceApp ? `\nFrom ${suggestion.sourceApp}` : ""}\nStart or dismiss it in OpenBot under Memory.`,+ text: `Suggested next step: ${suggestion.title}\n${suggestion.detail}${suggestion.sourceApp ? `\nFrom ${suggestion.sourceApp}` : ""}\nStart or dismiss it on the Bot's page in OpenBot.`,});await deps.store.markDelivered(suggestion.id);}diff --git a/server/src/responsibilities/trigger-tools.ts b/server/src/responsibilities/trigger-tools.tsindex 78c9873c..9ab35db7 100644--- a/server/src/responsibilities/trigger-tools.ts+++ b/server/src/responsibilities/trigger-tools.ts@@ -65,7 +65,7 @@ export const TRIGGER_TOOLS: readonly McpToolShape[] = Object.freeze(["`fieldPath`/`fieldEquals` pair such as `data.team.key` = `ENG`.","","You never see or handle a secret. The result gives the URL (or address); tell the person to open",- "the responsibility's card on the Responsibilities page to copy the key, or to paste the vendor's",+ "the responsibility's card on the Bot's Responsibilities page to copy the key, or to paste the vendor's","signing secret there for Linear, Sentry and PagerDuty. Never ask them to paste a secret into chat.","","Slack needs `teamId` and `mode` (`mention`, `phrase` with `phrases`, `reaction` with optional",@@ -249,10 +249,10 @@ export async function callTriggerTool();const next =trigger.kind === "webhook" || trigger.kind === "github"- ? "Ask the person to open this responsibility's card on the Responsibilities page to copy the key (and, for a webhook, the Authorization header). Do not ask for the key in chat."+ ? "Ask the person to open this responsibility's card on the Bot's Responsibilities page to copy the key (and, for a webhook, the Authorization header). Do not ask for the key in chat.": trigger.kind === "email" || trigger.kind === "slack"? "It is ready."- : "Ask the person to paste the provider's signing secret on this responsibility's card on the Responsibilities page. Until then deliveries are refused. Do not ask for the secret in chat.";+ : "Ask the person to paste the provider's signing secret on this responsibility's card on the Bot's Responsibilities page. Until then deliveries are refused. Do not ask for the secret in chat.";return `Added a ${trigger.kind} trigger to "${goal.title}" (id: ${trigger.id}). ${where(deps, trigger)}. ${next}`;}if (name === "pause_trigger" || name === "resume_trigger") {diff --git a/server/src/responsibilities/triggers.ts b/server/src/responsibilities/triggers.tsindex e95e2da7..43adc03d 100644--- a/server/src/responsibilities/triggers.ts+++ b/server/src/responsibilities/triggers.ts@@ -325,7 +325,7 @@ export async function slackAccessAllows(return "Slack triggers are not available on this deployment: the Slack pairing is not connected.";const slackUserId = await access.linkedIdentity(ownerUserId, teamId);if (!slackUserId)- return "Link your own Slack account in that workspace first (Reachability), so the trigger only hears channels you are in.";+ return "Link your own Slack account in that workspace first (the Bot's Reaching you page in OpenBot), so the trigger only hears channels you are in.";if (!access.isMember)return "Slack channel membership cannot be checked on this deployment yet, so Slack triggers are refused.";for (const channelId of channelIds)diff --git a/server/tests/approvals-question-resume.integration.test.ts b/server/tests/approvals-question-resume.integration.test.tsindex 76c92b4d..b39a90b7 100644--- a/server/tests/approvals-question-resume.integration.test.ts+++ b/server/tests/approvals-question-resume.integration.test.ts@@ -23,7 +23,7 @@ import type { TurnRunner } from "../src/routines/runner";import { TEST_POOL, testDatabaseUrl } from "./support/database";/**- * A responsibility's run asked the person a question; the person answered in Approvals. The answer+ * A responsibility's run asked the person a question; the person answered on the Bot's page. The answer* must resume that responsibility's work, with its tools and initiator, in the same conversation.*/diff --git a/server/tests/approvals-questions.test.ts b/server/tests/approvals-questions.test.tsindex fcf6e1ce..418ab49f 100644--- a/server/tests/approvals-questions.test.ts+++ b/server/tests/approvals-questions.test.ts@@ -1,5 +1,6 @@import { expect, test } from "bun:test";import {+ listedQuestion,questionConversationBot,questionResponseMessage,} from "../src/approvals/questions";@@ -25,3 +26,31 @@ test("a delegated question response belongs to the original source Bot and inclu"delegate",);});++test("a listed question names the Bot whose conversation it belongs to, not only the Bot that asked", () => {+ const createdAt = new Date("2026-10-09T10:00:00Z");+ const listed = listedQuestion({+ key: "q1",+ createdAt,+ payload: {+ actorId: "owner",+ botId: "delegate",+ sourceBotId: "source",+ channelId: "channel",+ threadId: "source-thread",+ runId: "delegated-run",+ question: "Which date should I use?",+ mode: "completed_question",+ },+ });+ expect(listed).toMatchObject({+ id: "q1",+ botId: "delegate",+ conversationBotId: "source",+ question: "Which date should I use?",+ createdAt,+ });+ expect(+ listedQuestion({ key: "q2", createdAt, payload: { nonsense: true } }),+ ).toBeNull();+});