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.
Let each person pick a skin: OpenDuet, OpenDots or OpenMuse (#856)
David McKay830116374bd6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 72acb7c2..61b727af 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -65,6 +65,18 @@ nothing changed. A deployment whose `OPENAI_BASE_URL` points at an OpenAI-compatthan OpenAI or Azure now reaches `openai/...` models through Chat Completions; a gateway that onlyspeaks the Responses API needs `COPILOTKIT_OPENAI_API=responses`.+### Pick a skin: OpenDuet, OpenDots or OpenMuse++Settings → Preferences → Skin changes how OpenBot looks for you, and nothing about what it does.+Three skins draw the open-source templates' looks over OpenBot's own features: OpenDuet (one+phone-width column with Chat and Tasks), OpenDots (a rail, a sidebar of Bots with their avatars, and+the Bot's computer beside the chat) and OpenMuse (one Bot at the centre, with Chat, Activity, Ideas,+Goals and Apps). Every skin keeps your deployment's name from `brand.yaml`, OpenBot's own mark and+each Bot's own avatar; only the look changes. The choice is saved on your account, so it follows+you to every device, and changes nothing for anybody else. The templates' own features that+OpenBot has no server for, such as OpenDots' Spaces, OpenDuet's morning brief and OpenMuse's mail and+calendar, are not part of the skins.+### The audit log reads like a logAdmin → Audit fills the window and runs the table across the whole pane, with the title, the viewsdiff --git a/app/index.html b/app/index.htmlindex 56293c4b..a839d57c 100644--- a/app/index.html+++ b/app/index.html@@ -11,6 +11,8 @@const dark = window.localStorage.getItem("openbot-theme") === "dark";document.documentElement.classList.toggle("dark", dark);document.documentElement.style.colorScheme = dark ? "dark" : "light";+ const skin = window.localStorage.getItem("openbot-skin");+ if (skin && skin !== "openbot") document.documentElement.dataset.skin = skin;} catch {}</script></head>diff --git a/app/src/components/app-sidebar/app-sidebar.tsx b/app/src/components/app-sidebar/app-sidebar.tsxindex 30087fc6..77ab33f7 100644--- a/app/src/components/app-sidebar/app-sidebar.tsx+++ b/app/src/components/app-sidebar/app-sidebar.tsx@@ -1,13 +1,4 @@-import {- IconBolt,- IconBox,- IconLogout,- IconPlug,- IconPlus,- IconSearch,- IconSettings,- IconShieldLock,-} from "@tabler/icons-react";+import { IconLogout, IconPlus, IconSearch } from "@tabler/icons-react";import {useInfiniteQuery,useMutation,@@ -54,6 +45,7 @@ import {import { useChannelEvents } from "@/lib/channels/use-channel-events";import { appConfig } from "@/lib/generated/application-config";import { EASE_OUT, ENTRANCE_SECONDS } from "@/lib/motion";+import { navigationFor } from "@/lib/navigation";import { relativeTime } from "@/lib/relative-time";import {type MessageListEmphasis,@@ -66,8 +58,6 @@ import { Channel } from "./channel";import { ChannelPagination } from "./channel-pagination";const appLinkOptions = { to: "/" } satisfies LinkOptions;-const adminLinkOptions = { to: "/admin" } satisfies LinkOptions;-const settingsLinkOptions = { to: "/settings" } satisfies LinkOptions;const userMenuItemClassName = "gap-2 px-2 py-1.5";@@ -238,6 +228,7 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {*/const animateOrder =!searching && (channels.data?.length ?? 0) <= MAX_ANIMATED_ROWS;+ const navigation = navigationFor(currentUser?.role);const handleSignOut = async () => {await signOut.mutateAsync();@@ -349,68 +340,29 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {</SidebarContent><SidebarFooter><SidebarMenu className="gap-px">- <SidebarMenuItem>- <SidebarMenuButton- className="hover:bg-foreground/5 h-10"- render={(props) => (- <Link- {...props}- to="/bots"- activeProps={{ className: "bg-foreground/5" }}- />- )}- >- <div className="size-[28px] flex items-center justify-center">- <IconBolt />- </div>- <span className="text-sm">Bots</span>- {/* What waits on you across every Bot; Bots lists them first. */}- <BotsNavBadge />- </SidebarMenuButton>- </SidebarMenuItem>- {/*- * Beside Bots rather than inside Admin: each is somebody's own. Capabilities are your skills- * and what your Bots remember about you; Connections are the apps a Bot reaches as you.- * Capabilities links to `/capabilities` rather than a tab, so it stays lit on both tabs.- */}- <SidebarMenuItem>- <SidebarMenuButton- className="hover:bg-foreground/5 h-10"- render={(props) => (- <Link- {...props}- to="/capabilities"- activeProps={{- className: "bg-foreground/5",- }}- />- )}- >- <div className="size-[28px] flex items-center justify-center">- <IconBox />- </div>- <span className="text-sm trackint-tight">Capabilities</span>- </SidebarMenuButton>- </SidebarMenuItem>- <SidebarMenuItem>- <SidebarMenuButton- className="hover:bg-foreground/5 h-10"- render={(props) => (- <Link- {...props}- to="/connections"- activeProps={{- className: "bg-foreground/5",- }}- />- )}- >- <div className="size-[28px] flex items-center justify-center">- <IconPlug />- </div>- <span className="text-sm trackint-tight">Connections</span>- </SidebarMenuButton>- </SidebarMenuItem>+ {navigation+ .filter((item) => item.section === "primary")+ .map((item) => (+ <SidebarMenuItem key={item.id}>+ <SidebarMenuButton+ className="hover:bg-foreground/5 h-10"+ render={(props) => (+ <Link+ {...props}+ to={item.to}+ activeProps={{ className: "bg-foreground/5" }}+ />+ )}+ >+ <div className="size-[28px] flex items-center justify-center">+ <item.icon />+ </div>+ <span className="text-sm">{item.label}</span>+ {/* What waits on you across every Bot; Bots lists them first. */}+ {item.id === "bots" ? <BotsNavBadge /> : null}+ </SidebarMenuButton>+ </SidebarMenuItem>+ ))}<SidebarMenuItem><DropdownMenu><DropdownMenuTrigger@@ -429,23 +381,18 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {side="top"sideOffset={8}>- {/* Admin routes are server-guarded; hide the entry for users who cannot open them. */}- {currentUser?.role === "admin" ? (- <DropdownMenuItem- className={userMenuItemClassName}- render={<Link {...adminLinkOptions} />}- >- <IconShieldLock />- Admin- </DropdownMenuItem>- ) : null}- <DropdownMenuItem- className={userMenuItemClassName}- render={<Link {...settingsLinkOptions} />}- >- <IconSettings />- Settings- </DropdownMenuItem>+ {navigation+ .filter((item) => item.section === "account")+ .map((item) => (+ <DropdownMenuItem+ className={userMenuItemClassName}+ key={item.id}+ render={<Link to={item.to} />}+ >+ <item.icon />+ {item.label}+ </DropdownMenuItem>+ ))}<DropdownMenuItemclassName={userMenuItemClassName}disabled={signOut.isPending}diff --git a/app/src/components/channels/composer/composer.tsx b/app/src/components/channels/composer/composer.tsxindex 22d12e02..f33ca00e 100644--- a/app/src/components/channels/composer/composer.tsx+++ b/app/src/components/channels/composer/composer.tsx@@ -1345,6 +1345,7 @@ export function Composer({<Buttonaria-label="Stop the Bot"className={actionClassName}+ data-slot="composer-stop"data-testid="composer-stop"onClick={onStop}size="icon"@@ -1374,6 +1375,7 @@ export function Composer({<Buttonaria-label={sendLabel}className={actionClassName}+ data-slot="composer-send"disabled={!canSend}size="icon"type="submit"@@ -1479,6 +1481,7 @@ export function Composer({{tooManyStagedNotice}<formaria-busy={isBusy}+ data-slot="composer"className={cn(/** `py-3` IS LOAD-BEARING ONCE THE TEXT WRAPS. On one line `min-h-14` and the controls@@ -1520,6 +1523,7 @@ export function Composer({<Buttonaria-label="Attach a file"className="self-end"+ data-slot="composer-attach"// The button stays, and stays labelled: a conversation that cannot take another// message has not lost the ability to attach, it has lost the message. Swapping it// for the "unavailable" placeholder would say the wrong thing about why.@@ -1543,23 +1547,26 @@ export function Composer({<IconPlus className="size-5" /></Button>)}- <PromptArea- aria-label="Message"- className={cn(- "min-w-0 flex-1 border-0 bg-transparent p-0 text-sm shadow-none",- editorClassName,- )}- disabled={disabled}- maxHeight={COMPACT_MAX_HEIGHT_PX}- minHeight={COMPACT_MIN_HEIGHT_PX}- onChange={handleChange}- onImagePaste={canAttach ? stagePastedImage : undefined}- onSubmit={submitDraft}- placeholder="Ask anything"- ref={promptAreaRef}- triggers={triggers}- value={value}- />+ {/* The slot is ours: `PromptArea` passes no attribute through to its own box. */}+ <div className="min-w-0 flex-1" data-slot="composer-input">+ <PromptArea+ aria-label="Message"+ className={cn(+ "w-full border-0 bg-transparent p-0 text-sm shadow-none",+ editorClassName,+ )}+ disabled={disabled}+ maxHeight={COMPACT_MAX_HEIGHT_PX}+ minHeight={COMPACT_MIN_HEIGHT_PX}+ onChange={handleChange}+ onImagePaste={canAttach ? stagePastedImage : undefined}+ onSubmit={submitDraft}+ placeholder="Ask anything"+ ref={promptAreaRef}+ triggers={triggers}+ value={value}+ />+ </div><DictationButtondictation={dictation}disabled={disabled || voiceCall?.active === true}@@ -1585,6 +1592,7 @@ export function Composer({<formaria-busy={isBusy}className="overflow-hidden rounded-2xl border border-border bg-card"+ data-slot="composer"onSubmit={handleFormSubmit}><DictationSurface@@ -1600,23 +1608,25 @@ export function Composer({images={images}onRemove={discardAttachment}/>- <PromptArea- aria-label="Message"- autoGrow- className={cn(- "w-full border-0 bg-transparent p-0 text-sm shadow-none",- editorClassName,- )}- disabled={disabled}- maxHeight={MAX_HEIGHT_PX}- onChange={handleChange}- onImagePaste={canAttach ? stagePastedImage : undefined}- onSubmit={submitDraft}- placeholder="Ask anything"- ref={promptAreaRef}- triggers={triggers}- value={value}- />+ <div data-slot="composer-input">+ <PromptArea+ aria-label="Message"+ autoGrow+ className={cn(+ "w-full border-0 bg-transparent p-0 text-sm shadow-none",+ editorClassName,+ )}+ disabled={disabled}+ maxHeight={MAX_HEIGHT_PX}+ onChange={handleChange}+ onImagePaste={canAttach ? stagePastedImage : undefined}+ onSubmit={submitDraft}+ placeholder="Ask anything"+ ref={promptAreaRef}+ triggers={triggers}+ value={value}+ />+ </div></div><div className="flex items-center justify-between">@@ -1624,6 +1634,7 @@ export function Composer({<Buttonaria-label="Attach a file"className="size-7 rounded-full p-0"+ data-slot="composer-attach"disabled={disabled}onClick={() => fileInputRef.current?.click()}type="button"diff --git a/app/src/components/channels/composer/dictation-controls.tsx b/app/src/components/channels/composer/dictation-controls.tsxindex 07536e09..2cd2a7c6 100644--- a/app/src/components/channels/composer/dictation-controls.tsx+++ b/app/src/components/channels/composer/dictation-controls.tsx@@ -26,6 +26,7 @@ export function DictationButton({return (<Buttonaria-label="Dictate a message"+ data-slot="composer-dictate"title={dictation.supported? "Dictate a message"@@ -119,6 +120,7 @@ function RecordingControls({<Buttonref={cancel}aria-label="Cancel dictation"+ data-slot="composer-dictate-cancel"title="Cancel dictation"size="icon"type="button"@@ -190,6 +192,7 @@ function RecordingControls({<div className="flex shrink-0 items-center gap-2"><Buttonaria-label="Stop and transcribe"+ data-slot="composer-dictate-stop"title="Stop and add to draft"disabled={!recording}size="icon"diff --git a/app/src/components/channels/conversation-view.tsx b/app/src/components/channels/conversation-view.tsxindex 9c804d2c..f0ff124a 100644--- a/app/src/components/channels/conversation-view.tsx+++ b/app/src/components/channels/conversation-view.tsx@@ -438,7 +438,10 @@ export function ConversationView({working={working}/></div>- <div className="max-w-2xl mx-auto w-full px-0 pb-4 shrink-0">+ <div+ className="max-w-2xl mx-auto w-full px-0 pb-4 shrink-0"+ data-slot="composer-column"+ >{notice}<Composeragents={agents}diff --git a/app/src/components/layout/detail-panel.tsx b/app/src/components/layout/detail-panel.tsxindex 2d326c82..8795daf9 100644--- a/app/src/components/layout/detail-panel.tsx+++ b/app/src/components/layout/detail-panel.tsx@@ -97,11 +97,18 @@ export function DetailPanel({><divclassName="flex h-full flex-col bg-sidebar border-l border-border"+ data-slot="detail-pane"style={{ width: detailWidth }}>{/* Rendered for the whole animation, so the way out is available immediately. */}- <div className="h-12 shrink-0 sticky top-0 flex flex-row items-center justify-between px-2 gap-2">- <div className="flex min-w-0 w-full items-center gap-1.5">+ <div+ className="h-12 shrink-0 sticky top-0 flex flex-row items-center justify-between px-2 gap-2"+ data-slot="detail-pane-header"+ >+ <div+ className="flex min-w-0 w-full items-center gap-1.5"+ data-slot="detail-pane-title"+ >{title}</div><div className="flex flex-row gap-1.5">diff --git a/app/src/components/layout/page-shell.tsx b/app/src/components/layout/page-shell.tsxindex 7fbca5c2..d643881b 100644--- a/app/src/components/layout/page-shell.tsx+++ b/app/src/components/layout/page-shell.tsx@@ -83,9 +83,11 @@ export function PageShell({const bar = showToggle || !!backButton;const header = (- <header className="flex flex-col gap-2">+ <header className="flex flex-col gap-2" data-slot="page-header"><div className="flex flex-row items-center justify-between gap-4">- <h1 className="font-bold text-2xl">{title}</h1>+ <h1 className="font-bold text-2xl" data-slot="page-title">+ {title}+ </h1>{action}</div>{description ? (diff --git a/app/src/lib/auth/mutations.ts b/app/src/lib/auth/mutations.tsindex 771ee0df..04181397 100644--- a/app/src/lib/auth/mutations.ts+++ b/app/src/lib/auth/mutations.ts@@ -1,5 +1,6 @@import { mutationOptions, type QueryClient } from "@tanstack/react-query";import { client } from "@/lib/client";+import { clearSkin } from "@/skins/store";import { authKeys } from "./queries";async function signOut() {@@ -9,9 +10,19 @@ async function signOut() {});}+/**+ * Every way out of OpenBot signs out through here, the skins' own menus included.+ *+ * The skin is the account's, and this browser only caches it to paint before the preferences load.+ * Clearing it here means the next person on a shared machine starts from the default rather than+ * from the last person's skin.+ */export function signOutMutationOptions(queryClient: QueryClient) {return mutationOptions({mutationFn: signOut,- onSuccess: () => queryClient.removeQueries({ queryKey: authKeys.all }),+ onSuccess: () => {+ clearSkin();+ queryClient.removeQueries({ queryKey: authKeys.all });+ },});}diff --git a/app/src/lib/navigation.ts b/app/src/lib/navigation.tsnew file mode 100644index 00000000..cd39386b--- /dev/null+++ b/app/src/lib/navigation.ts@@ -0,0 +1,87 @@+import {+ IconBolt,+ IconBox,+ type Icon,+ IconPlug,+ IconSettings,+ IconShieldLock,+} from "@tabler/icons-react";+import { useQuery } from "@tanstack/react-query";+import { currentUserQueryOptions } from "@/lib/auth/queries";++/**+ * Where a person can go in OpenBot, in one list.+ *+ * OpenBot's own sidebar draws it, and so does every skin that replaces the sidebar, so a destination+ * added here reaches every frame at once. One left out of a frame's own copy would simply be+ * missing from that skin, with nothing failing to say so.+ *+ * `section` says where OpenBot's sidebar puts each entry: `primary` destinations sit in its footer,+ * `account` ones in the menu under the person's name. A skin may group them its own way.+ *+ * Bots, Capabilities and Connections are each somebody's own, which is why they sit beside each+ * other and not inside Admin. Capabilities are your skills and what your Bots remember about you;+ * Connections are the apps a Bot reaches as you. Capabilities links to `/capabilities` rather than+ * a tab, so it stays lit on both of its tabs.+ */+export type NavigationItem = {+ id: "bots" | "capabilities" | "connections" | "admin" | "settings";+ label: string;+ to: "/bots" | "/capabilities" | "/connections" | "/admin" | "/settings";+ icon: Icon;+ section: "primary" | "account";+ /** Admin routes are guarded on the server; the entry is hidden from people who cannot open them. */+ adminOnly?: boolean;+};++export const NAVIGATION: readonly NavigationItem[] = [+ {+ id: "bots",+ label: "Bots",+ to: "/bots",+ icon: IconBolt,+ section: "primary",+ },+ {+ id: "capabilities",+ label: "Capabilities",+ to: "/capabilities",+ icon: IconBox,+ section: "primary",+ },+ {+ id: "connections",+ label: "Connections",+ to: "/connections",+ icon: IconPlug,+ section: "primary",+ },+ {+ id: "admin",+ label: "Admin",+ to: "/admin",+ icon: IconShieldLock,+ section: "account",+ adminOnly: true,+ },+ {+ id: "settings",+ label: "Settings",+ to: "/settings",+ icon: IconSettings,+ section: "account",+ },+];++/** The destinations this person may open, in order. */+export function navigationFor(+ role: string | undefined,+): readonly NavigationItem[] {+ return NAVIGATION.filter((item) => !item.adminOnly || role === "admin");+}++/** `navigationFor` the signed-in person. */+export function useNavigationItems(): readonly NavigationItem[] {+ const { data: user } = useQuery(currentUserQueryOptions());+ return navigationFor(user?.role);+}diff --git a/app/src/lib/plugins/listed.ts b/app/src/lib/plugins/listed.tsnew file mode 100644index 00000000..72a21d73--- /dev/null+++ b/app/src/lib/plugins/listed.ts@@ -0,0 +1,58 @@+import type { PluginServer } from "./queries";++/*+ * Which apps the Connections page lists, and in which group. Here and not in the route file, so+ * anything else that lists a person's apps (a skin's own screen) reads the same rules without+ * importing a route, which works against TanStack Router's automatic code splitting.+ */++/**+ * Whether a row came through a broker. A deployment only ever holds rows from one provider, so the+ * page needs to recognise "brokered", not to know which broker.+ */+const isBrokered = (server: PluginServer): boolean =>+ server.provenance === "composio" || server.provenance === "arcade";++/**+ * The brokered apps this page lists, which is not every brokered row.+ *+ * Exported as a function rather than left inline in the render, for the reason `matchingApps` on the+ * Composio picker is: the rule is the thing worth pinning and pinning it needs no DOM, no router and+ * no query client. See its one clause below.+ */+export function brokeredAccountsListedOn(+ servers: PluginServer[],+): PluginServer[] {+ return servers.filter(+ (server) =>+ isBrokered(server) &&+ server.authScheme !== "NO_AUTH" &&+ server.accountMode !== "shared",+ );+}++/**+ * The servers this page may list at all: none reached through Composio when the deployment has no+ * Composio key.+ *+ * An app an administrator enabled while a key was set keeps its row after the key is removed, and+ * listing it offered a person an account they cannot connect, under a sentence about an environment+ * variable only an administrator can set. Without the broker there is nothing for them to decide.+ */+export function serversListedFor(page: {+ servers: PluginServer[];+ composioConfigured: boolean;+}): PluginServer[] {+ return page.composioConfigured+ ? page.servers+ : page.servers.filter((server) => server.provenance !== "composio");+}++/** Apps whose account is the organisation's, shown so a person knows a Bot does not act as them there. */+export function sharedAccountsListedOn(+ servers: PluginServer[],+): PluginServer[] {+ return servers.filter(+ (server) => isBrokered(server) && server.accountMode === "shared",+ );+}diff --git a/app/src/lib/settings/message-list.ts b/app/src/lib/settings/message-list.tsindex f8f155c7..36d65328 100644--- a/app/src/lib/settings/message-list.ts+++ b/app/src/lib/settings/message-list.ts@@ -6,7 +6,8 @@ import {} from "@tanstack/react-query";import { currentUserQueryOptions } from "@/lib/auth/queries";import { client } from "@/lib/client";-import type { UserPreferences } from "@openbot/shared/user-preferences";+import type { SkinId, UserPreferences } from "@openbot/shared/user-preferences";+import { getSkinId, setSkin } from "@/skins/store";import { settingsKeys } from "./queries";export type { MessageListEmphasis } from "@openbot/shared/user-preferences";@@ -96,3 +97,51 @@ export function saveUserPreferencesMutationOptions(),});}++/** Held while a skin save is out, so the account sync can tell its own write from a stale read. */+export const saveSkinMutationKey = [+ ...settingsKeys.all,+ "preferences",+ "skin",+] as const;++/**+ * Choose how OpenBot looks for this person, on every device they sign in from.+ *+ * The skin is drawn the moment it is picked, and the cached preferences are patched to match, so+ * `SkinAccountSync` agrees with the picker while the save is out. A read already in flight is+ * cancelled first, or it would land the old skin over the new one. A failed save puts back both the+ * skin and the cache, and the picker says so. The reply seeds the cache with what the server stored.+ */+export function saveSkinMutationOptions(+ queryClient: QueryClient,+ userId: string | undefined,+) {+ const queryKey = userPreferencesQueryOptions(userId).queryKey;+ return mutationOptions({+ mutationKey: saveSkinMutationKey,+ mutationFn: (skin: SkinId): Promise<UserPreferences> => {+ if (!userId) throw new Error("Sign in to save your preferences.");+ return client("/api/settings/preferences", "preferences", {+ method: "PATCH",+ body: { skin },+ fallback: "Could not save your skin",+ });+ },+ onMutate: async (skin) => {+ const previousSkin = getSkinId();+ setSkin(skin);+ await queryClient.cancelQueries({ queryKey });+ const previous = queryClient.getQueryData(queryKey);+ if (previous) queryClient.setQueryData(queryKey, { ...previous, skin });+ return { previous, previousSkin };+ },+ onError: (_error, _skin, context) => {+ if (!context) return;+ if (context.previous)+ queryClient.setQueryData(queryKey, context.previous);+ setSkin(context.previousSkin);+ },+ onSuccess: (preferences) => queryClient.setQueryData(queryKey, preferences),+ });+}diff --git a/app/src/routeTree.gen.ts b/app/src/routeTree.gen.tsindex 87fdb447..de90ab8c 100644--- a/app/src/routeTree.gen.ts+++ b/app/src/routeTree.gen.ts@@ -54,6 +54,7 @@ import { Route as AuthedAppConnectionsIndexRouteImport } from './routes/_authed/import { Route as AuthedAppConnectionsKeyRouteImport } from './routes/_authed/_app/connections.$key'import { Route as AuthedAppGroupChannelIdRouteImport } from './routes/_authed/_app/group/$channelId'import { Route as AuthedAppGroupNewRouteImport } from './routes/_authed/_app/group/new'+import { Route as AuthedAppSScreenRouteImport } from './routes/_authed/_app/s/$screen'import { Route as AuthedAdminBoundariesIndexRouteImport } from './routes/_authed/admin/boundaries_.$index'import { Route as AuthedAdminBoundariesNewRouteImport } from './routes/_authed/admin/boundaries_.new'import { Route as AuthedAdminComponentsIndexRouteImport } from './routes/_authed/admin/components/index'@@ -311,6 +312,11 @@ const AuthedAppGroupNewRoute = AuthedAppGroupNewRouteImport.update({path: '/group/new',getParentRoute: () => AuthedAppRoute,} as any)+const AuthedAppSScreenRoute = AuthedAppSScreenRouteImport.update({+ id: '/s/$screen',+ path: '/s/$screen',+ getParentRoute: () => AuthedAppRoute,+} as any)const AuthedAdminBoundariesIndexRoute =AuthedAdminBoundariesIndexRouteImport.update({id: '/boundaries_/$index',@@ -500,6 +506,7 @@ export interface FileRoutesByFullPath {'/connections/$key': typeof AuthedAppConnectionsKeyRoute'/group/$channelId': typeof AuthedAppGroupChannelIdRoute'/group/new': typeof AuthedAppGroupNewRoute+ '/s/$screen': typeof AuthedAppSScreenRoute'/admin/boundaries/$index': typeof AuthedAdminBoundariesIndexRoute'/admin/boundaries/new': typeof AuthedAdminBoundariesNewRoute'/admin/components/$name': typeof AuthedAdminComponentsNameRoute@@ -567,6 +574,7 @@ export interface FileRoutesByTo {'/connections/$key': typeof AuthedAppConnectionsKeyRoute'/group/$channelId': typeof AuthedAppGroupChannelIdRoute'/group/new': typeof AuthedAppGroupNewRoute+ '/s/$screen': typeof AuthedAppSScreenRoute'/admin/boundaries/$index': typeof AuthedAdminBoundariesIndexRoute'/admin/boundaries/new': typeof AuthedAdminBoundariesNewRoute'/admin/components/$name': typeof AuthedAdminComponentsNameRoute@@ -640,6 +648,7 @@ export interface FileRoutesById {'/_authed/_app/connections/$key': typeof AuthedAppConnectionsKeyRoute'/_authed/_app/group/$channelId': typeof AuthedAppGroupChannelIdRoute'/_authed/_app/group/new': typeof AuthedAppGroupNewRoute+ '/_authed/_app/s/$screen': typeof AuthedAppSScreenRoute'/_authed/admin/boundaries_/$index': typeof AuthedAdminBoundariesIndexRoute'/_authed/admin/boundaries_/new': typeof AuthedAdminBoundariesNewRoute'/_authed/admin/components/$name': typeof AuthedAdminComponentsNameRoute@@ -712,6 +721,7 @@ export interface FileRouteTypes {| '/connections/$key'| '/group/$channelId'| '/group/new'+ | '/s/$screen'| '/admin/boundaries/$index'| '/admin/boundaries/new'| '/admin/components/$name'@@ -779,6 +789,7 @@ export interface FileRouteTypes {| '/connections/$key'| '/group/$channelId'| '/group/new'+ | '/s/$screen'| '/admin/boundaries/$index'| '/admin/boundaries/new'| '/admin/components/$name'@@ -851,6 +862,7 @@ export interface FileRouteTypes {| '/_authed/_app/connections/$key'| '/_authed/_app/group/$channelId'| '/_authed/_app/group/new'+ | '/_authed/_app/s/$screen'| '/_authed/admin/boundaries_/$index'| '/_authed/admin/boundaries_/new'| '/_authed/admin/components/$name'@@ -1204,6 +1216,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof AuthedAppGroupNewRouteImportparentRoute: typeof AuthedAppRoute}+ '/_authed/_app/s/$screen': {+ id: '/_authed/_app/s/$screen'+ path: '/s/$screen'+ fullPath: '/s/$screen'+ preLoaderRoute: typeof AuthedAppSScreenRouteImport+ parentRoute: typeof AuthedAppRoute+ }'/_authed/admin/boundaries_/$index': {id: '/_authed/admin/boundaries_/$index'path: '/boundaries/$index'@@ -1501,6 +1520,7 @@ interface AuthedAppRouteChildren {AuthedAppConnectionsKeyRoute: typeof AuthedAppConnectionsKeyRouteAuthedAppGroupChannelIdRoute: typeof AuthedAppGroupChannelIdRouteAuthedAppGroupNewRoute: typeof AuthedAppGroupNewRoute+ AuthedAppSScreenRoute: typeof AuthedAppSScreenRouteAuthedAppAgentsIndexRoute: typeof AuthedAppAgentsIndexRouteAuthedAppBotsIndexRoute: typeof AuthedAppBotsIndexRouteAuthedAppConnectionsIndexRoute: typeof AuthedAppConnectionsIndexRoute@@ -1532,6 +1552,7 @@ const AuthedAppRouteChildren: AuthedAppRouteChildren = {AuthedAppConnectionsKeyRoute: AuthedAppConnectionsKeyRoute,AuthedAppGroupChannelIdRoute: AuthedAppGroupChannelIdRoute,AuthedAppGroupNewRoute: AuthedAppGroupNewRoute,+ AuthedAppSScreenRoute: AuthedAppSScreenRoute,AuthedAppAgentsIndexRoute: AuthedAppAgentsIndexRoute,AuthedAppBotsIndexRoute: AuthedAppBotsIndexRoute,AuthedAppConnectionsIndexRoute: AuthedAppConnectionsIndexRoute,diff --git a/app/src/routes/_authed.tsx b/app/src/routes/_authed.tsxindex 2e34d837..8eb42381 100644--- a/app/src/routes/_authed.tsx+++ b/app/src/routes/_authed.tsx@@ -2,6 +2,7 @@ import { createFileRoute, Outlet, redirect } from "@tanstack/react-router";import { currentUserQueryOptions, needsOnboarding } from "../lib/auth/queries";import { CopilotProvider } from "../lib/copilot/provider";import { AppHotkeys } from "../lib/hotkeys/app-hotkeys";+import { SkinAccountSync } from "../skins/account-sync";export const Route = createFileRoute("/_authed")({beforeLoad: async ({ context, location }) => {@@ -25,6 +26,8 @@ export const Route = createFileRoute("/_authed")({component: () => (<CopilotProvider><AppHotkeys />+ {/* The skin saved on the account, drawn over the browser's cached one once it loads. */}+ <SkinAccountSync /><Outlet /></CopilotProvider>),diff --git a/app/src/routes/_authed/_app.tsx b/app/src/routes/_authed/_app.tsxindex 0868efca..4c7af727 100644--- a/app/src/routes/_authed/_app.tsx+++ b/app/src/routes/_authed/_app.tsx@@ -2,12 +2,23 @@ import { createFileRoute, Outlet } from "@tanstack/react-router";import { AppSidebar } from "@/components/app-sidebar/app-sidebar";import { SelfHostBanner } from "@/components/layout/self-host-banner";import { SidebarShell } from "@/components/layout/sidebar-shell";+import { useActiveSkin } from "@/skins/registry";export const Route = createFileRoute("/_authed/_app")({component: RouteComponent,});function RouteComponent() {+ const { Frame } = useActiveSkin();++ if (Frame) {+ return (+ <Frame>+ <Outlet />+ </Frame>+ );+ }+return (// One viewport, never scrolls: panes scroll inside it. A growable shell lets the transcript's// scroller size against the page, grow it, and grow again.diff --git a/app/src/routes/_authed/_app/channel/$channelId.tsx b/app/src/routes/_authed/_app/channel/$channelId.tsxindex 7ef1c5fd..5cc23c2d 100644--- a/app/src/routes/_authed/_app/channel/$channelId.tsx+++ b/app/src/routes/_authed/_app/channel/$channelId.tsx@@ -106,7 +106,10 @@ function RouteComponent() {}><div className="flex flex-col">- <div className="min-h-12 border-b border-border sticky top-0 flex flex-row flex-wrap items-center justify-between px-3 py-2 gap-2">+ <div+ className="min-h-12 border-b border-border sticky top-0 flex flex-row flex-wrap items-center justify-between px-3 py-2 gap-2"+ data-slot="conversation-header"+ >{/* Keyed on the displayed name so cold channel loads animate the resolved name, not the id. */}<div className="flex min-w-0 items-center gap-1.5"><SidebarToggle />diff --git a/app/src/routes/_authed/_app/channel/new.tsx b/app/src/routes/_authed/_app/channel/new.tsxindex a7fbeedb..f5231720 100644--- a/app/src/routes/_authed/_app/channel/new.tsx+++ b/app/src/routes/_authed/_app/channel/new.tsx@@ -124,7 +124,10 @@ function RouteComponent() {return (<div className="flex h-full flex-col">- <div className="h-12 border-b border-border sticky top-0 flex flex-row px-2 items-center">+ <div+ className="h-12 border-b border-border sticky top-0 flex flex-row px-2 items-center"+ data-slot="conversation-header"+ ><SidebarToggle className="mr-1" /><span className="text-sm text-muted-foreground">To:</span><Comboboxdiff --git a/app/src/routes/_authed/_app/connections.index.tsx b/app/src/routes/_authed/_app/connections.index.tsxindex fd9144b4..b789b234 100644--- a/app/src/routes/_authed/_app/connections.index.tsx+++ b/app/src/routes/_authed/_app/connections.index.tsx@@ -38,9 +38,13 @@ import {linkedAccountsQueryOptions,} from "@/lib/identity/queries";import { keyedLookup } from "@/lib/lookup";+import {+ brokeredAccountsListedOn,+ serversListedFor,+ sharedAccountsListedOn,+} from "@/lib/plugins/listed";import {connectionsQueryOptions,- type PluginServer,personalConnections,pluginsPageQueryOptions,} from "@/lib/plugins/queries";@@ -191,57 +195,6 @@ const MARKS: ReadonlyMap<* this page's decision. */const markFor = (key: string) => keyedLookup(MARKS, key) ?? IconPlug;-/**- * Whether a row came through a broker. A deployment only ever holds rows from one provider, so the- * page needs to recognise "brokered", not to know which broker.- */-const isBrokered = (server: PluginServer): boolean =>- server.provenance === "composio" || server.provenance === "arcade";--/**- * The brokered apps this page lists, which is not every brokered row.- *- * Exported as a function rather than left inline in the render, for the reason `matchingApps` on the- * Composio picker is: the rule is the thing worth pinning and pinning it needs no DOM, no router and- * no query client. See its one clause below.- */-export function brokeredAccountsListedOn(- servers: PluginServer[],-): PluginServer[] {- return servers.filter(- (server) =>- isBrokered(server) &&- server.authScheme !== "NO_AUTH" &&- server.accountMode !== "shared",- );-}--/**- * The servers this page may list at all: none reached through Composio when the deployment has no- * Composio key.- *- * An app an administrator enabled while a key was set keeps its row after the key is removed, and- * listing it offered a person an account they cannot connect, under a sentence about an environment- * variable only an administrator can set. Without the broker there is nothing for them to decide.- */-export function serversListedFor(page: {- servers: PluginServer[];- composioConfigured: boolean;-}): PluginServer[] {- return page.composioConfigured- ? page.servers- : page.servers.filter((server) => server.provenance !== "composio");-}--/** Apps whose account is the organisation's, shown so a person knows a Bot does not act as them there. */-export function sharedAccountsListedOn(- servers: PluginServer[],-): PluginServer[] {- return servers.filter(- (server) => isBrokered(server) && server.accountMode === "shared",- );-}-function RouteComponent() {const { connected: outcome, authorized, linked } = Route.useSearch();/*diff --git a/app/src/routes/_authed/_app/group/$channelId.tsx b/app/src/routes/_authed/_app/group/$channelId.tsxindex c8ce2fa0..e59dd199 100644--- a/app/src/routes/_authed/_app/group/$channelId.tsx+++ b/app/src/routes/_authed/_app/group/$channelId.tsx@@ -19,7 +19,10 @@ function RouteComponent() {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">+ <div+ className="sticky top-0 flex min-h-12 flex-row items-center gap-1.5 border-b border-border px-3 py-2"+ data-slot="conversation-header"+ ><SidebarToggle /><ChannelAvatarparticipantIds={channel.data?.agentIds ?? []}diff --git a/app/src/routes/_authed/_app/s/$screen.tsx b/app/src/routes/_authed/_app/s/$screen.tsxnew file mode 100644index 00000000..4fa21a13--- /dev/null+++ b/app/src/routes/_authed/_app/s/$screen.tsx@@ -0,0 +1,20 @@+import { createFileRoute, Navigate } from "@tanstack/react-router";+import { useActiveSkin } from "@/skins/registry";++/*+ * Screens that only a skin has (OpenDuet's Tasks, OpenMuse's Ideas) live here, so a skin adds+ * screens without adding routes. Switching to a skin without this screen, or following an old link+ * to it, goes home rather than to an empty page.+ */+export const Route = createFileRoute("/_authed/_app/s/$screen")({+ component: RouteComponent,+});++function RouteComponent() {+ const { screen } = Route.useParams();+ const Screen = useActiveSkin().screens?.[screen];++ if (!Screen) return <Navigate replace to="/" />;++ return <Screen />;+}diff --git a/app/src/routes/_authed/settings/index.tsx b/app/src/routes/_authed/settings/index.tsxindex ef6309e5..9d52eb00 100644--- a/app/src/routes/_authed/settings/index.tsx+++ b/app/src/routes/_authed/settings/index.tsx@@ -19,6 +19,7 @@ import {import { Separator } from "@/components/ui/separator";import { Switch } from "@/components/ui/switch";import { formatHotkey, HOTKEYS } from "@/lib/hotkeys/hotkeys";+import { SkinPicker } from "@/skins/skin-picker";export const Route = createFileRoute("/_authed/settings/")({component: RouteComponent,@@ -37,7 +38,7 @@ function RouteComponent() {*/return (<PageShell- description="Customize OpenBot’s appearance and message display. Message settings apply to your account; the theme applies only to this browser."+ description="Customize OpenBot’s appearance and message display. Your skin and message settings apply to your account; the theme applies only to this browser."title="Preferences"><ProfileSettings />@@ -58,6 +59,8 @@ function RouteComponent() {/></ItemActions></Item>+ <Separator />+ <SkinPicker /></PageRows><MessageListPreference /></PageSection>diff --git a/app/src/skins/account-sync.tsx b/app/src/skins/account-sync.tsxnew file mode 100644index 00000000..f04851a1--- /dev/null+++ b/app/src/skins/account-sync.tsx@@ -0,0 +1,29 @@+import { useIsMutating } from "@tanstack/react-query";+import { useEffect } from "react";+import {+ saveSkinMutationKey,+ useUserPreferences,+} from "@/lib/settings/message-list";+import { parseStoredSkin, setSkin } from "./store";++/**+ * Draws the skin saved on the person's account, whenever their preferences load or change.+ *+ * The browser's cache paints first, so a reload never flashes the default. When the account says+ * otherwise (the person chose another skin on another device, or somebody else used this browser+ * before them), the account wins. Mounted once, inside the signed-in boundary.+ *+ * While the person's own save is out it stands aside: the picker already drew their choice, and a+ * read that started before the save would otherwise put the old skin back for a moment.+ */+export function SkinAccountSync() {+ const accountSkin = useUserPreferences().data?.skin;+ const saving = useIsMutating({ mutationKey: saveSkinMutationKey }) > 0;++ useEffect(() => {+ if (saving || accountSkin === undefined) return;+ setSkin(parseStoredSkin(accountSkin));+ }, [accountSkin, saving]);++ return null;+}diff --git a/app/src/skins/opendots/computer-pane.tsx b/app/src/skins/opendots/computer-pane.tsxnew file mode 100644index 00000000..a181d7f9--- /dev/null+++ b/app/src/skins/opendots/computer-pane.tsx@@ -0,0 +1,93 @@+import { IconDeviceDesktop, IconX } from "@tabler/icons-react";+import { useQuery } from "@tanstack/react-query";+import { useState } from "react";+import { ComputerViewPanel } from "@/components/computer/computer-panel";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { agentListQueryOptions } from "@/lib/agents/queries";+import { IconAction } from "./sidebar";++/**+ * OpenDots' right pane, showing OpenBot's own computer for one Bot.+ *+ * OpenDots' pane has a Brief tab beside the computer; OpenBot keeps no brief, so the computer is+ * the pane's only tab. Which Bot's computer it shows starts as the Bot the page is about and can be+ * changed, the way OpenDots' "Computer for" picker does.+ */+export function ComputerPane({+ defaultBotId,+ onClose,+}: {+ defaultBotId: string | undefined;+ onClose: () => void;+}) {+ const agents = useQuery(agentListQueryOptions());+ const [chosen, setChosen] = useState<string | undefined>();+ const bots = agents.data ?? [];+ const bot =+ bots.find((agent) => agent.id === chosen) ??+ bots.find((agent) => agent.id === defaultBotId) ??+ bots[0];+ return (+ <aside+ aria-label="Computer"+ className="flex h-full min-h-0 flex-col bg-(--opendots-pane)"+ data-testid="opendots-computer-pane"+ >+ <div className="sticky top-0 z-[2] flex h-14 shrink-0 items-center justify-between border-b border-(--opendots-line) bg-(--opendots-pane) px-4 py-3">+ <div className="flex min-w-0 gap-1.5">+ <span className="flex min-w-0 items-center gap-2 rounded-[9px] bg-(--opendots-tab) px-[9px] py-[7px] text-[13px] text-foreground">+ <IconDeviceDesktop className="size-[15px] shrink-0" />+ <span className="truncate">+ {bot ? `${bot.name}’s computer` : "Computer"}+ </span>+ </span>+ </div>+ <IconAction label="Close computer" onClick={onClose}>+ <IconX className="size-4" />+ </IconAction>+ </div>+ {agents.isPending ? null : !bot ? (+ <p className="px-[18px] py-3.5 text-[13px] text-(--opendots-muted)">+ Create a Bot to give it a computer.+ </p>+ ) : (+ <div className="min-h-0 flex-1 overflow-y-auto">+ {bots.length > 1 ? (+ <div className="flex items-center gap-2 px-[18px] pt-2.5 text-[13px] text-(--opendots-muted)">+ <span>Computer for</span>+ <Select+ onValueChange={(value) => {+ if (typeof value === "string") setChosen(value);+ }}+ value={bot.id}+ >+ <SelectTrigger+ aria-label="Select Bot computer"+ className="h-7 border-0 bg-transparent px-1.5 text-[13px] text-foreground shadow-none dark:bg-transparent"+ size="sm"+ >+ <SelectValue>{bot.name}</SelectValue>+ </SelectTrigger>+ <SelectContent>+ {bots.map((agent) => (+ <SelectItem key={agent.id} value={agent.id}>+ {agent.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ ) : null}+ {/* Keyed so switching Bots tears down one screen stream before opening the next. */}+ <ComputerViewPanel agentId={bot.id} key={bot.id} name={bot.name} />+ </div>+ )}+ </aside>+ );+}diff --git a/app/src/skins/opendots/frame.tsx b/app/src/skins/opendots/frame.tsxnew file mode 100644index 00000000..a63809e3--- /dev/null+++ b/app/src/skins/opendots/frame.tsx@@ -0,0 +1,464 @@+import {+ IconClockHour3,+ IconDeviceDesktop,+ IconLayoutSidebar,+ IconLogout,+ IconMenu2,+ IconPlayerPause,+ IconPlayerPlay,+ IconPlus,+} from "@tabler/icons-react";+import { useMutation, useQuery } from "@tanstack/react-query";+import {+ Link,+ type LinkProps,+ useNavigate,+ useRouterState,+} from "@tanstack/react-router";+import { type ReactNode, useEffect, useState } from "react";+import AgentOrb from "@/components/agents/orb/agent-orb";+import { BotsNavBadge } from "@/components/bot-profile/attention";+import { SelfHostBanner } from "@/components/layout/self-host-banner";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@/components/ui/tooltip";+import { useIsMobile } from "@/hooks/use-mobile";+import { agentListQueryOptions } from "@/lib/agents/queries";+import { signOutMutationOptions } from "@/lib/auth/mutations";+import { currentUserQueryOptions } from "@/lib/auth/queries";+import { setBotPausedMutationOptions } from "@/lib/bot-lifecycle/mutations";+import { botLifecycleQueryOptions } from "@/lib/bot-lifecycle/queries";+import { useChannelEvents } from "@/lib/channels/use-channel-events";+import { appConfig } from "@/lib/generated/application-config";+import { type NavigationItem, useNavigationItems } from "@/lib/navigation";+import { cn } from "@/lib/utils";+import { queryClient } from "@/query-client";+import { ComputerPane } from "./computer-pane";+import { CoworkerPersona } from "./persona";+import { botName, type Place, usePlace } from "./place";+import { IconAction, initialsOf, OpenDotsSidebar } from "./sidebar";++/** The rail's square buttons: 36px, borderless, a grey glyph that darkens on hover. */+const railButton =+ "grid size-9 place-items-center rounded-lg text-(--opendots-rail-icon) outline-none transition-colors hover:bg-(--opendots-hover) hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring [&_svg]:size-[18px] [&_svg]:stroke-[1.75]";++function RailTip({+ label,+ children,+}: {+ label: string;+ children: React.ReactElement;+}) {+ return (+ <Tooltip>+ <TooltipTrigger render={children} />+ <TooltipContent side="right">{label}</TooltipContent>+ </Tooltip>+ );+}++/** Who is signed in, and the way out, at the foot of the rail as OpenBot keeps it in its sidebar. */+function RailUserMenu() {+ const user = useQuery(currentUserQueryOptions());+ const navigate = useNavigate();+ const signOut = useMutation(signOutMutationOptions(queryClient));+ if (!user.data) return null;+ return (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <button+ aria-label="Account"+ className="grid size-[29px] place-items-center rounded-full border border-(--opendots-avatar-line) bg-(--opendots-avatar) text-[10px] text-(--opendots-avatar-ink) outline-none focus-visible:ring-2 focus-visible:ring-ring"+ type="button"+ />+ }+ >+ {initialsOf(user.data)}+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="p-1.5" side="right">+ <DropdownMenuGroup>+ <DropdownMenuLabel className="max-w-56 truncate">+ {user.data.name?.trim() || user.data.email}+ </DropdownMenuLabel>+ </DropdownMenuGroup>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ className="gap-2 px-2 py-1.5"+ disabled={signOut.isPending}+ onClick={async () => {+ await signOut.mutateAsync();+ await navigate({ to: "/sign" });+ }}+ variant="destructive"+ >+ <IconLogout />+ Sign out+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}++/** The 48px strip at the far left: the brand, the sidebar toggle, and the few places used most. */+/** One of OpenBot's destinations as a rail button, with the Bots badge on Bots. */+function RailDestination({+ item,+ showBadge,+}: {+ item: NavigationItem;+ showBadge: boolean;+}) {+ const Icon = item.icon;+ return (+ <RailTip label={item.label}>+ <Link+ aria-label={item.label}+ className={cn(railButton, "relative")}+ to={item.to}+ >+ <Icon />+ {item.id === "bots" && showBadge ? (+ // What waits on you across every Bot. OpenBot's own badge, which also sends the+ // browser notification, so exactly one is ever mounted.+ <span className="pointer-events-none absolute -top-1 -right-1 flex">+ <BotsNavBadge />+ </span>+ ) : null}+ </Link>+ </RailTip>+ );+}++function Rail({+ newChat,+ navCollapsed,+ onToggleNav,+ showBadge,+}: {+ newChat: LinkProps;+ navCollapsed: boolean;+ onToggleNav: () => void;+ /** Whether the rail carries the Bots badge: at desktop width, where the rail is on screen. */+ showBadge: boolean;+}) {+ const navigation = useNavigationItems();+ return (+ <nav+ aria-label="Workspace navigation"+ data-opendots-chrome+ className="flex w-12 shrink-0 flex-col items-center gap-3 border-r border-(--opendots-line) bg-(--opendots-rail) px-[5px] py-4 max-md:hidden"+ >+ {/* OpenBot's own mark where OpenDots puts its monogram; the deployment owns the identity. */}+ <Link+ aria-label={`${appConfig.brand.productName} home`}+ className="mb-3 grid size-9 shrink-0 place-items-center rounded-lg outline-none focus-visible:ring-2 focus-visible:ring-ring"+ to="/"+ >+ <AgentOrb size="26px" />+ </Link>+ <RailTip label={navCollapsed ? "Expand sidebar" : "Collapse sidebar"}>+ <button+ aria-controls="opendots-sidebar"+ aria-expanded={!navCollapsed}+ aria-label={navCollapsed ? "Expand sidebar" : "Collapse sidebar"}+ className={railButton}+ onClick={onToggleNav}+ type="button"+ >+ <IconLayoutSidebar />+ </button>+ </RailTip>+ <RailTip label="New chat">+ <Link {...newChat} aria-label="New chat" className={railButton}>+ <IconPlus className="size-[19px]!" />+ </Link>+ </RailTip>+ <RailTip label="Routines">+ <Link+ aria-label="Routines"+ className={railButton}+ params={{ screen: "routines" }}+ to="/s/$screen"+ >+ <IconClockHour3 />+ </Link>+ </RailTip>+ {/* OpenBot's own destinations, from the one list every frame reads. */}+ {navigation+ .filter((item) => item.section === "primary")+ .map((item) => (+ <RailDestination item={item} key={item.id} showBadge={showBadge} />+ ))}+ <div className="mt-auto flex flex-col items-center gap-3">+ {navigation+ .filter((item) => item.section === "account")+ .map((item) => (+ <RailDestination item={item} key={item.id} showBadge={false} />+ ))}+ <RailUserMenu />+ </div>+ </nav>+ );+}++/**+ * Pause and resume for the one Bot the page is about. OpenDots pauses every Dot at once; OpenBot+ * pauses each Bot on its own, so this is that Bot's switch and only appears where there is one.+ */+function PauseControl({ botId, name }: { botId: string; name: string }) {+ const lifecycle = useQuery(botLifecycleQueryOptions(botId));+ const setPaused = useMutation(setBotPausedMutationOptions(queryClient));+ if (!lifecycle.data) return null;+ const paused = lifecycle.data.paused;+ return (+ <button+ aria-label={paused ? `Resume ${name}` : `Pause ${name}`}+ className="inline-flex items-center gap-[5px] rounded-md p-1 text-[12px] text-(--opendots-pause-ink) outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50 [&_svg]:size-3.5"+ disabled={setPaused.isPending}+ onClick={() => setPaused.mutate({ agentId: botId, paused: !paused })}+ title={+ paused+ ? `${name} is paused. Nothing runs for you until you resume it.`+ : `Pause ${name}. Nothing runs for you until you resume it.`+ }+ type="button"+ >+ {paused ? <IconPlayerPlay /> : <IconPlayerPause />}+ <span className="max-md:hidden">{paused ? "Resume" : "Pause"}</span>+ </button>+ );+}++function Topbar({+ place,+ navCollapsed,+ onToggleNav,+ computerOpen,+ onToggleComputer,+}: {+ place: Place;+ navCollapsed: boolean;+ onToggleNav: () => void;+ computerOpen: boolean;+ onToggleComputer: () => void;+}) {+ const agents = useQuery(agentListQueryOptions());+ const name = botName(agents.data, place.botId);+ return (+ <header+ data-opendots-chrome+ className="flex h-16 shrink-0 items-center gap-4 border-b border-(--opendots-line) bg-(--opendots-topbar) px-[22px] max-md:pr-[15px] max-md:pl-12"+ >+ <button+ aria-controls="opendots-sidebar"+ aria-expanded={!navCollapsed}+ aria-label={navCollapsed ? "Show navigation" : "Hide navigation"}+ className="grid size-10 shrink-0 place-items-center rounded-lg text-(--opendots-toggle-ink) outline-none transition-colors hover:bg-(--opendots-hover) focus-visible:ring-2 focus-visible:ring-ring max-md:hidden [&_svg]:size-[18px]"+ onClick={onToggleNav}+ type="button"+ >+ <IconLayoutSidebar />+ </button>+ <nav+ aria-label="Breadcrumb"+ className="flex min-w-0 flex-1 items-center gap-[13px] text-[13px] text-(--opendots-crumb) max-md:gap-[7px]"+ >+ <span className="shrink-0 max-md:hidden">Bots</span>+ <span aria-hidden className="shrink-0 max-md:hidden">+ /+ </span>+ <strong+ className="min-w-0 truncate font-medium text-(--opendots-crumb-ink)"+ data-testid="opendots-crumb"+ >+ {place.label}+ </strong>+ {place.detail ? (+ <>+ <span aria-hidden className="shrink-0">+ /+ </span>+ <strong className="min-w-0 truncate font-medium text-(--opendots-crumb-ink)">+ {place.detail}+ </strong>+ </>+ ) : null}+ </nav>+ <div className="flex shrink-0 items-center gap-[15px] max-md:gap-3">+ {place.botId && name ? (+ <PauseControl botId={place.botId} name={name} />+ ) : null}+ <IconAction+ aria-expanded={computerOpen}+ className={cn(+ "size-8 [&_svg:not([class*='size-'])]:size-[18px]",+ computerOpen && "bg-(--opendots-tab) text-foreground",+ )}+ label={computerOpen ? "Hide computer" : "Show computer"}+ onClick={onToggleComputer}+ >+ <IconDeviceDesktop />+ </IconAction>+ </div>+ </header>+ );+}++/**+ * OpenDots' frame around every OpenBot page: the icon rail, the Dots sidebar, a top bar with+ * breadcrumbs and the computer toggle, and the computer pane on the right. The page itself, chat+ * included, is OpenBot's own and renders as `children`.+ */+export function OpenDotsFrame({ children }: { children: ReactNode }) {+ // One socket for the app, opened where the roster is kept live, as OpenBot's own sidebar does.+ useChannelEvents();+ const place = usePlace();+ const navigate = useNavigate();+ const [mobileOpen, setMobileOpen] = useState(false);+ const [navCollapsed, setNavCollapsed] = useState(false);+ const [paneOpen, setPaneOpen] = useState(false);+ const href = useRouterState({ select: (state) => state.location.href });++ // OpenBot's own breakpoint, so the drawer and OpenBot's pages agree about what a phone is.+ const isMobile = useIsMobile();++ // A page chosen from the drawer replaces it, as tapping a row in OpenDots' drawer does.+ // biome-ignore lint/correctness/useExhaustiveDependencies: closing on every navigation is the point.+ useEffect(() => {+ setMobileOpen(false);+ }, [href]);++ /** New chat is with the Bot on screen when there is one, as OpenDots starts it with the open one. */+ const newChat: LinkProps =+ place.section === "chat" && place.botId+ ? { to: "/channel/new", search: { agent: place.botId } }+ : { to: "/channel/new" };++ /*+ * A conversation draws OpenBot's own Computer pane, opened by its `?watch` flag, and opens it by+ * itself when the Bot starts using the browser. The toggle drives that pane there rather than+ * opening a second screen beside it; everywhere else it opens the frame's own.+ */+ const computerOpen = place.ownsWatch ? place.watching : paneOpen;+ const toggleComputer = () => {+ if (!place.ownsWatch) {+ setPaneOpen((open) => !open);+ return;+ }+ void navigate({+ to: ".",+ search: (previous: Record<string, unknown>) => ({+ ...previous,+ settings: undefined,+ watch: place.watching ? undefined : true,+ }),+ });+ };++ return (+ <div+ className="flex h-svh overflow-hidden bg-background text-foreground"+ data-opendots-frame+ >+ <Rail+ navCollapsed={navCollapsed}+ newChat={newChat}+ onToggleNav={() => setNavCollapsed((collapsed) => !collapsed)}+ showBadge={!isMobile}+ />+ {isMobile ? (+ <>+ <button+ aria-expanded={mobileOpen}+ aria-label="Open navigation"+ className="fixed top-3.5 left-2.5 z-20 grid size-9 place-items-center rounded-lg text-(--opendots-menu-ink) outline-none focus-visible:ring-2 focus-visible:ring-ring [&_svg]:size-[21px]"+ data-opendots-chrome+ onClick={() => setMobileOpen(true)}+ type="button"+ >+ <IconMenu2 />+ {/* On a phone the rail is gone, so the Bots badge rides on the menu button. */}+ <span className="pointer-events-none absolute -top-0.5 -right-0.5 flex">+ <BotsNavBadge />+ </span>+ </button>+ {/* OpenBot's own sheet: it traps focus, closes on Escape and on the scrim. */}+ <Sheet onOpenChange={setMobileOpen} open={mobileOpen}>+ <SheetContent+ className="w-[252px] max-w-[85vw] gap-0 border-(--opendots-line) bg-(--opendots-sidebar) p-0 text-foreground"+ data-opendots-chrome+ showCloseButton={false}+ side="left"+ >+ <SheetTitle className="sr-only">Navigation</SheetTitle>+ <OpenDotsSidebar+ newChat={newChat}+ onNavigate={() => setMobileOpen(false)}+ place={place}+ />+ </SheetContent>+ </Sheet>+ </>+ ) : (+ <aside+ aria-label="Sidebar"+ className="w-[220px] shrink-0 border-r border-(--opendots-line) bg-(--opendots-sidebar)"+ data-opendots-chrome+ hidden={navCollapsed}+ id="opendots-sidebar"+ >+ <OpenDotsSidebar+ newChat={newChat}+ onNavigate={() => setMobileOpen(false)}+ place={place}+ />+ </aside>+ )}+ <div className="flex min-w-0 flex-1 flex-col">+ <Topbar+ computerOpen={computerOpen}+ navCollapsed={navCollapsed}+ onToggleComputer={toggleComputer}+ onToggleNav={() => setNavCollapsed((collapsed) => !collapsed)}+ place={place}+ />+ <SelfHostBanner />+ <div className="relative flex min-h-0 flex-1">+ <main+ className="relative flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden"+ data-opendots-main+ >+ {children}+ {place.coworkerHome && place.botId ? (+ <CoworkerPersona botId={place.botId} />+ ) : null}+ </main>+ {paneOpen && !place.ownsWatch ? (+ <div+ data-opendots-chrome+ className="w-[clamp(390px,40vw,660px)] shrink-0 border-l border-(--opendots-line) max-[1100px]:fixed max-[1100px]:top-16 max-[1100px]:right-0 max-[1100px]:bottom-0 max-[1100px]:z-[15] max-[1100px]:w-[min(600px,100vw)] max-[1100px]:shadow-(--opendots-pane-shadow)"+ >+ <ComputerPane+ defaultBotId={place.botId}+ onClose={() => setPaneOpen(false)}+ />+ </div>+ ) : null}+ </div>+ </div>+ </div>+ );+}diff --git a/app/src/skins/opendots/index.ts b/app/src/skins/opendots/index.tsnew file mode 100644index 00000000..d2431ccd--- /dev/null+++ b/app/src/skins/opendots/index.ts@@ -0,0 +1,21 @@+import type { Skin } from "../types";+import { OpenDotsFrame } from "./frame";+import { MemoriesScreen, RoutinesScreen } from "./screens";++/*+ * OpenDots over OpenBot. The frame is OpenDots' rail, Dots sidebar, top bar and computer pane; the+ * pages inside it are OpenBot's, chat included, in OpenDots' colours. Left out because OpenBot has+ * nothing behind them: Spaces and their pages, page chats, the Brief, and the pause-everything+ * switch (OpenBot pauses one Bot at a time, which the top bar offers for the Bot on screen).+ */+export const opendots: Skin = {+ id: "opendots",+ name: "OpenDots",+ description:+ "A compact sidebar of your Bots, with each Bot's computer beside the conversation.",+ Frame: OpenDotsFrame,+ screens: {+ routines: RoutinesScreen,+ memories: MemoriesScreen,+ },+};diff --git a/app/src/skins/opendots/persona.tsx b/app/src/skins/opendots/persona.tsxnew file mode 100644index 00000000..e06f46de--- /dev/null+++ b/app/src/skins/opendots/persona.tsx@@ -0,0 +1,46 @@+import { IconDots } from "@tabler/icons-react";+import { useQuery } from "@tanstack/react-query";+import { Link } from "@tanstack/react-router";+import { AbstractAvatar } from "@/components/agents/abstract-avatar";+import { agentListQueryOptions } from "@/lib/agents/queries";++/**+ * OpenDots' coworker home: the Bot you are about to talk to, centred above an empty conversation.+ *+ * Drawn by the frame over OpenBot's own new-conversation page, which leaves that space empty. It+ * holds no state and sends nothing: the To: field and composer beneath are OpenBot's. The stylesheet+ * hides it the moment the page shows a message, so it never sits over a conversation.+ */+export function CoworkerPersona({ botId }: { botId: string }) {+ const agents = useQuery(agentListQueryOptions());+ const bot = agents.data?.find((agent) => agent.id === botId);+ if (!bot) return null;+ return (+ <div+ className="pointer-events-none absolute inset-x-0 top-[73px] z-[1] flex justify-center px-6 max-md:top-16"+ data-opendots-persona+ >+ <div className="flex max-w-[420px] flex-col items-center text-center">+ {/* OpenBot's own avatar for the Bot; the name below is its label. */}+ <span aria-hidden className="mb-2">+ <AbstractAvatar name={bot.name} seed={bot.avatarSeed} size={64} />+ </span>+ <h2 className="mb-1.5 text-[17px] font-[550] tracking-[-0.2px] text-foreground">+ {bot.name}+ </h2>+ {bot.roleDescription ? (+ <p className="mb-2 line-clamp-3 text-[13px] leading-[1.7] text-(--opendots-persona-ink)">+ {bot.roleDescription}+ </p>+ ) : null}+ <Link+ className="pointer-events-auto inline-flex items-center gap-[5px] rounded-md text-[12px] text-(--opendots-text-button) outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"+ params={{ agentId: bot.id }}+ to="/bots/$agentId"+ >+ Edit Bot <IconDots className="size-3.5" />+ </Link>+ </div>+ </div>+ );+}diff --git a/app/src/skins/opendots/place.ts b/app/src/skins/opendots/place.tsnew file mode 100644index 00000000..b9053bed--- /dev/null+++ b/app/src/skins/opendots/place.ts@@ -0,0 +1,171 @@+import { useQuery } from "@tanstack/react-query";+import { useRouterState } from "@tanstack/react-router";+import { type AgentProfile, agentListQueryOptions } from "@/lib/agents/queries";+import { channelQueryOptions } from "@/lib/channels/queries";+import { appConfig } from "@/lib/generated/application-config";++/** Which part of OpenDots' sidebar a page belongs to, so the right row is lit. */+export type Section =+ | "chat"+ | "routines"+ | "memories"+ | "bots"+ | "capabilities"+ | "connections"+ | "other";++/**+ * What the frame needs to know about the page inside it: its name for the breadcrumbs, and the one+ * Bot it is about when it is about exactly one. Read from the URL and the caches the page itself+ * fills, so the frame never asks the server anything the page did not.+ */+export type Place = {+ section: Section;+ /** The page's name, the last breadcrumb. */+ label: string;+ /** A sub-page under the label, such as a Bot page's tab. */+ detail?: string;+ /** The single Bot this page is about, or undefined. */+ botId?: string;+ channelId?: string;+ /**+ * The page draws OpenBot's own Computer pane, opened by `?watch`. The frame's computer toggle+ * drives that pane rather than opening a second one beside it.+ */+ ownsWatch: boolean;+ watching: boolean;+ /** OpenBot's new-conversation page with its Bot already chosen: OpenDots' coworker home. */+ coworkerHome: boolean;+};++type Parsed = Omit<Place, "label" | "botId" | "watching" | "coworkerHome"> & {+ label: string | ((bot: string | undefined) => string);+ agentFromUrl?: string;+};++const BOT_TABS: Record<string, string> = {+ setup: "Setup",+ access: "Access",+ activity: "Activity",+ approvals: "Approvals",+ memory: "Memory",+ reach: "Reach",+ responsibilities: "Responsibilities",+ routines: "Routines",+ sharing: "Sharing",+};++/**+ * The page a pathname is, as OpenDots names its own views: a Bot's name for a chat with it,+ * "Activity" and "Memories" for its two workspace views, and OpenBot's own page names otherwise.+ */+export function parsePlace(+ pathname: string,+ search: { agent?: unknown },+): Parsed {+ const agent = typeof search.agent === "string" ? search.agent : undefined;+ const path = pathname.replace(/\/+$/, "") || "/";+ if (path === "/") {+ return { section: "chat", label: "New chat", ownsWatch: false };+ }+ if (path === "/channel/new") {+ return {+ section: "chat",+ label: (bot) => bot ?? "New chat",+ agentFromUrl: agent,+ ownsWatch: false,+ };+ }+ const channel = path.match(/^\/(channel|group)\/([^/]+)$/);+ if (channel) {+ return {+ section: "chat",+ label: (bot) => bot ?? "Conversation",+ channelId: decodeURIComponent(channel[2]),+ ownsWatch: channel[1] === "channel",+ };+ }+ if (path === "/bot") {+ return {+ section: "chat",+ label: (bot) => bot ?? "Conversation",+ agentFromUrl: agent,+ ownsWatch: true,+ };+ }+ const bot = path.match(/^\/bots\/([^/]+)(?:\/([^/]+))?$/);+ if (bot) {+ return {+ section: "bots",+ label: (name) => name ?? "Bot",+ detail: bot[2] ? (BOT_TABS[bot[2]] ?? bot[2]) : undefined,+ agentFromUrl: decodeURIComponent(bot[1]),+ ownsWatch: false,+ };+ }+ if (path === "/bots" || path === "/agents") {+ return { section: "bots", label: "All Bots", ownsWatch: false };+ }+ if (path === "/s/routines" || path === "/routines") {+ return { section: "routines", label: "Routines", ownsWatch: false };+ }+ if (path === "/s/memories" || path === "/capabilities/memory") {+ return { section: "memories", label: "Memories", ownsWatch: false };+ }+ if (path.startsWith("/capabilities")) {+ return { section: "capabilities", label: "Capabilities", ownsWatch: false };+ }+ if (path.startsWith("/connections")) {+ return { section: "connections", label: "Connections", ownsWatch: false };+ }+ return {+ section: "other",+ label: appConfig.brand.productName,+ ownsWatch: false,+ };+}++export function botName(+ agents: AgentProfile[] | undefined,+ id: string | undefined,+): string | undefined {+ if (!id) return undefined;+ return agents?.find((agent) => agent.id === id)?.name;+}++export function usePlace(): Place {+ const pathname = useRouterState({+ select: (state) => state.location.pathname,+ });+ const agent = useRouterState({+ select: (state) => (state.location.search as { agent?: unknown }).agent,+ });+ const watch = useRouterState({+ select: (state) =>+ (state.location.search as { watch?: unknown }).watch === true,+ });+ const parsed = parsePlace(pathname, { agent });+ const agents = useQuery(agentListQueryOptions());+ // The page reads the same key, so this is the page's own fetch rather than a second one.+ const channel = useQuery({+ ...channelQueryOptions(parsed.channelId ?? ""),+ enabled: parsed.channelId !== undefined,+ });+ const channelBots = parsed.channelId ? channel.data?.agentIds : undefined;+ const botId =+ parsed.agentFromUrl ??+ (channelBots?.length === 1 ? channelBots[0] : undefined);+ const name =+ botName(agents.data, botId) ??+ (parsed.channelId ? channel.data?.name : undefined);+ return {+ section: parsed.section,+ label: typeof parsed.label === "string" ? parsed.label : parsed.label(name),+ detail: parsed.detail,+ botId,+ coworkerHome: pathname.replace(/\/+$/, "") === "/channel/new" && !!botId,+ channelId: parsed.channelId,+ ownsWatch: parsed.ownsWatch,+ watching: parsed.ownsWatch && watch,+ };+}diff --git a/app/src/skins/opendots/screens.tsx b/app/src/skins/opendots/screens.tsxnew file mode 100644index 00000000..03c53335--- /dev/null+++ b/app/src/skins/opendots/screens.tsx@@ -0,0 +1,69 @@+import type { ReactNode } from "react";+import { MemoryList, RememberFact } from "@/components/memory/memories";+import { RoutinesList } from "@/components/routines/routines-list";++/**+ * OpenDots' workspace page: a small eyebrow, a large quiet title and one line under it, with the+ * page's primary action on the title's right. What sits beneath is OpenBot's own list, so every+ * switch, Run now, history and delete OpenBot offers is still there.+ */+function OpenDotsPage({+ eyebrow = "YOUR WORKSPACE",+ title,+ description,+ action,+ children,+}: {+ eyebrow?: string;+ title: string;+ description: string;+ action?: ReactNode;+ children: ReactNode;+}) {+ return (+ <div className="min-h-0 flex-1 overflow-y-auto" data-opendots-page>+ <div className="mx-auto w-full max-w-[1090px] px-[54px] pt-16 pb-9 max-[1150px]:px-8 max-[1150px]:pt-[45px] max-md:px-[22px] max-md:pt-[38px]">+ <header className="mb-[35px] flex items-center justify-between gap-[25px] max-[920px]:items-start max-md:flex-col max-md:items-stretch">+ <div className="min-w-0">+ <span className="text-[10px] font-semibold tracking-[1.5px] text-(--opendots-eyebrow)">+ {eyebrow}+ </span>+ <h1 className="mt-3.5 mb-2 text-[34px] leading-tight font-[550] tracking-[-0.04em] text-foreground max-[920px]:text-[30px]">+ {title}+ </h1>+ <p className="text-[12px] leading-[1.7] text-(--opendots-note)">+ {description}+ </p>+ </div>+ {action ? <div className="shrink-0">{action}</div> : null}+ </header>+ {children}+ </div>+ </div>+ );+}++/** Routines: what each Bot does on a schedule, as OpenBot's routines list. */+export function RoutinesScreen() {+ return (+ <OpenDotsPage+ description="What your Bots do on a schedule. Ask a Bot to set one up. Pause, run or delete one here."+ title="Routines"+ >+ <RoutinesList embedded />+ </OpenDotsPage>+ );+}++/** "Memories": what the person's Bots know about them, as OpenBot's memory. */+export function MemoriesScreen() {+ return (+ <OpenDotsPage+ action={<RememberFact />}+ description="What your Bots know about you."+ title="Memories"+ >+ <MemoryList />+ </OpenDotsPage>+ );+}diff --git a/app/src/skins/opendots/sidebar.tsx b/app/src/skins/opendots/sidebar.tsxnew file mode 100644index 00000000..7011d53d--- /dev/null+++ b/app/src/skins/opendots/sidebar.tsx@@ -0,0 +1,629 @@+import {+ IconBook,+ IconClockHour3,+ IconDots,+ IconLogout,+ IconMessageCircle,+ IconPin,+ IconPinnedOff,+ IconPlus,+ IconSearch,+ IconTrash,+ IconX,+} from "@tabler/icons-react";+import { useInfiniteQuery, useMutation, useQuery } from "@tanstack/react-query";+import { Link, type LinkProps, useNavigate } from "@tanstack/react-router";+import { type ReactNode, useRef, useState } from "react";+import { AbstractAvatar } from "@/components/agents/abstract-avatar";+import {+ isUnread,+ matchingChannels,+ pinnedFirst,+} from "@/components/app-sidebar/app-sidebar";+import { ChannelPagination } from "@/components/app-sidebar/channel-pagination";+import { DeleteConversationDialog } from "@/components/channels/delete-conversation-dialog";+import { Button } from "@/components/ui/button";+import {+ ContextMenu,+ ContextMenuContent,+ ContextMenuItem,+ ContextMenuTrigger,+} from "@/components/ui/context-menu";+import { Input } from "@/components/ui/input";+import { type AgentProfile, agentListQueryOptions } from "@/lib/agents/queries";+import { groupRoster } from "@/lib/agents/roster";+import { signOutMutationOptions } from "@/lib/auth/mutations";+import { currentUserQueryOptions } from "@/lib/auth/queries";+import { setChannelPinnedMutationOptions } from "@/lib/channels/mutations";+import {+ type ChannelSummary,+ channelListQueryOptions,+} from "@/lib/channels/queries";+import { appConfig } from "@/lib/generated/application-config";+import { memoriesQueryOptions } from "@/lib/memory";+import { useNavigationItems } from "@/lib/navigation";+import { routinesQueryOptions } from "@/lib/routines/queries";+import { cn } from "@/lib/utils";+import { queryClient } from "@/query-client";+import type { Place } from "./place";++/** OpenDots' sidebar row: a quiet line of text that lights lavender when it is the page. */+export const navItem =+ "flex w-full min-w-0 items-center gap-[11px] rounded-[7px] px-3.5 py-3 text-left text-[13px] leading-snug text-(--opendots-nav-ink) outline-none transition-colors hover:bg-(--opendots-hover) focus-visible:ring-2 focus-visible:ring-ring [&_svg]:size-[17px] [&_svg]:shrink-0 [&_svg]:stroke-[1.65]";+export const navItemActive =+ "bg-(--opendots-active) text-(--opendots-active-ink) hover:bg-(--opendots-active) [&_svg]:stroke-2";++/** The small grey heading over a group of rows, with its one or two actions on the right. */+function NavLabel({+ children,+ actions,+ className,+}: {+ children: ReactNode;+ actions?: ReactNode;+ className?: string;+}) {+ return (+ <div+ className={cn(+ "mb-[5px] flex min-h-[26px] items-center justify-between pr-[3px] pl-3.5 text-[10px] font-semibold text-(--opendots-label)",+ className,+ )}+ >+ <span>{children}</span>+ {actions ? (+ <span className="flex items-center gap-0.5">{actions}</span>+ ) : null}+ </div>+ );+}++/** OpenDots' bare icon button: no frame, a grey glyph, a soft square on hover. */+export function IconAction({+ label,+ children,+ className,+ ...props+}: {+ label: string;+ children: ReactNode;+ className?: string;+} & Omit<React.ComponentProps<typeof Button>, "children">) {+ return (+ <Button+ aria-label={label}+ className={cn(+ "size-7 rounded-[7px] text-(--opendots-icon) hover:bg-(--opendots-hover) hover:text-foreground [&_svg:not([class*='size-'])]:size-3.5",+ className,+ )}+ size="icon-sm"+ title={label}+ variant="ghost"+ {...props}+ >+ {children}+ </Button>+ );+}++/**+ * The deployment's own name, set in OpenDots' wordmark type, which is also the way home. The name+ * is `brand.yaml`'s, the same one OpenBot's sidebar header shows; a skin changes the look, never+ * whose product it is.+ */+function Wordmark({ onNavigate }: { onNavigate: () => void }) {+ const productName = appConfig.brand.productName;+ return (+ <Link+ aria-label={`${productName} home`}+ className="mb-[23px] flex h-[18px] min-w-0 items-center self-start rounded-lg px-2.5 text-[16px] leading-[18px] font-bold tracking-[-0.5px] text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring"+ data-testid="opendots-wordmark"+ onClick={onNavigate}+ to="/"+ >+ <span className="truncate">{productName}</span>+ </Link>+ );+}++/**+ * The most recent conversation this person has with one Bot alone, from the roster already loaded.+ * Choosing a Dot in OpenDots reopens where you left off with it, and only starts fresh when there+ * is nowhere to go back to.+ */+export function latestChannelWith(+ channels: ChannelSummary[] | undefined,+ agentId: string,+): ChannelSummary | undefined {+ let latest: ChannelSummary | undefined;+ let latestAt = "";+ for (const channel of channels ?? []) {+ if (channel.agentIds.length !== 1 || channel.agentIds[0] !== agentId)+ continue;+ const at = channel.lastMessageAt ?? channel.createdAt;+ if (at > latestAt) {+ latest = channel;+ latestAt = at;+ }+ }+ return latest;+}++/** The Bots a person can talk to, pinned and assigned first, then their own, then shared ones. */+export function dotOrder(agents: readonly AgentProfile[]): AgentProfile[] {+ const roster = groupRoster(agents);+ return [...roster.pinned, ...roster.yours, ...roster.shared];+}++function BotsSection({+ place,+ channels,+ onNavigate,+}: {+ place: Place;+ channels: ChannelSummary[] | undefined;+ onNavigate: () => void;+}) {+ const agents = useQuery(agentListQueryOptions());+ const dots = agents.data ? dotOrder(agents.data) : [];+ const bots = useNavigationItems().find((item) => item.id === "bots");+ return (+ <section aria-label="Bots">+ <NavLabel+ actions={+ <IconAction+ label="Create Bot"+ onClick={onNavigate}+ render={(props) => (+ <Link {...props} search={{ new: true }} to="/bots" />+ )}+ >+ <IconPlus />+ </IconAction>+ }+ >+ BOTS+ </NavLabel>+ {agents.isPending ? null : agents.error ? (+ <p className="px-3.5 py-1.5 text-[12px] text-destructive" role="alert">+ Couldn't load your Bots. Reload the page.+ </p>+ ) : dots.length === 0 ? (+ <p className="px-3.5 py-1.5 text-[12px] leading-relaxed text-(--opendots-faint)">+ No Bots yet. Use + to create one.+ </p>+ ) : (+ <nav+ aria-label="Your Bots"+ className="grid max-h-[32vh] gap-[3px] overflow-y-auto"+ >+ {dots.map((agent) => {+ const latest = latestChannelWith(channels, agent.id);+ const active = place.section === "chat" && place.botId === agent.id;+ return (+ <div className="flex items-center gap-0.5" key={agent.id}>+ <Link+ aria-current={active ? "page" : undefined}+ className={cn(+ navItem,+ "min-h-[42px] gap-[9px] px-2.5 py-1.5 text-[12px] text-(--opendots-dot-ink) hover:bg-(--opendots-hover)",+ // The row's only drawing is the avatar, which keeps its own size.+ "[&_svg]:size-full",+ active &&+ "bg-(--opendots-active) hover:bg-(--opendots-active)",+ )}+ data-testid="opendots-bot"+ onClick={onNavigate}+ {...(latest+ ? {+ to: "/channel/$channelId",+ params: { channelId: latest.id },+ }+ : { to: "/channel/new", search: { agent: agent.id } })}+ >+ {/* OpenBot's own avatar for the Bot; hidden so the row is named once. */}+ <span aria-hidden className="contents">+ <AbstractAvatar+ name={agent.name}+ seed={agent.avatarSeed}+ size={30}+ />+ </span>+ <span className="min-w-0 flex-1 truncate">{agent.name}</span>+ </Link>+ <IconAction+ label={`Open ${agent.name}'s settings`}+ onClick={onNavigate}+ render={(props) => (+ <Link+ {...props}+ params={{ agentId: agent.id }}+ to="/bots/$agentId"+ />+ )}+ >+ <IconDots className="size-[15px]" />+ </IconAction>+ </div>+ );+ })}+ </nav>+ )}+ {bots ? (+ // OpenBot's Bots destination, from the shared list, closing the list of Bots above it.+ <Link+ activeOptions={{ exact: true }}+ activeProps={{ className: navItemActive, "aria-current": "page" }}+ className={cn(navItem, "mt-[3px] py-2.5 text-(--opendots-dot-ink)")}+ onClick={onNavigate}+ to={bots.to}+ >+ <bots.icon />+ <span className="min-w-0 flex-1 truncate">All {bots.label}</span>+ </Link>+ ) : null}+ </section>+ );+}++function ThreadRow({+ channel,+ names,+ open,+ onNavigate,+}: {+ channel: ChannelSummary;+ names: string;+ open: boolean;+ onNavigate: () => void;+}) {+ const navigate = useNavigate();+ const setPinned = useMutation(setChannelPinnedMutationOptions(queryClient));+ const [confirming, setConfirming] = useState(false);+ const [pinProblem, setPinProblem] = useState<string | null>(null);+ const unread = isUnread(channel, open ? channel.id : undefined);+ const title = channel.summary || channel.lastMessage || channel.name;+ const link: LinkProps =+ channel.agentIds.length > 1+ ? { to: "/group/$channelId", params: { channelId: channel.id } }+ : { to: "/channel/$channelId", params: { channelId: channel.id } };+ return (+ <>+ <ContextMenu>+ <ContextMenuTrigger>+ <Link+ {...link}+ aria-current={open ? "page" : undefined}+ className={cn(+ navItem,+ "mb-1 gap-[11px] px-3 py-[9px] [&_svg]:size-[15px]",+ open && navItemActive,+ )}+ data-testid="opendots-thread"+ onClick={onNavigate}+ >+ <IconMessageCircle />+ <span className="flex min-w-0 flex-1 flex-col gap-0.5">+ <span className="truncate">{title}</span>+ <small className="truncate bg-(--opendots-tag) text-[11px] leading-[1.4] text-(--opendots-tag-ink)">+ {names}+ </small>+ </span>+ {channel.pinned ? (+ <IconPin+ aria-label="Pinned"+ className="size-3! text-(--opendots-faint)"+ />+ ) : null}+ {unread ? (+ <span+ aria-label="Unread"+ className="size-1.5 shrink-0 rounded-full bg-(--opendots-teal)"+ role="img"+ />+ ) : null}+ </Link>+ </ContextMenuTrigger>+ <ContextMenuContent>+ <ContextMenuItem+ onClick={() => {+ setPinProblem(null);+ setPinned.mutate(+ { channelId: channel.id, pinned: !channel.pinned },+ { onError: (thrown) => setPinProblem(thrown.message) },+ );+ }}+ >+ {channel.pinned ? <IconPinnedOff /> : <IconPin />}+ {channel.pinned ? "Unpin conversation" : "Pin conversation"}+ </ContextMenuItem>+ <ContextMenuItem+ onClick={() => setConfirming(true)}+ variant="destructive"+ >+ <IconTrash />+ Delete conversation…+ </ContextMenuItem>+ </ContextMenuContent>+ </ContextMenu>+ {pinProblem ? (+ <p className="px-3 pb-1 text-[11px] text-destructive" role="alert">+ {pinProblem}+ </p>+ ) : null}+ <DeleteConversationDialog+ channelId={channel.id}+ leave={open ? () => navigate({ to: "/" }) : undefined}+ name={channel.name}+ onOpenChange={setConfirming}+ open={confirming}+ />+ </>+ );+}++function RecentChats({+ place,+ newChat,+ onNavigate,+}: {+ place: Place;+ newChat: LinkProps;+ onNavigate: () => void;+}) {+ const agents = useQuery(agentListQueryOptions());+ const channels = useInfiniteQuery(channelListQueryOptions());+ const [searching, setSearching] = useState(false);+ const [search, setSearch] = useState("");+ const scrollRoot = useRef<HTMLDivElement>(null);+ const visible = pinnedFirst(matchingChannels(channels.data, search));+ const nameOf = (id: string) =>+ agents.data?.find((agent) => agent.id === id)?.name;+ const closeSearch = () => {+ setSearching(false);+ setSearch("");+ };+ return (+ <section+ aria-label="Recent chats"+ className="mt-4 flex min-h-0 flex-1 flex-col max-md:flex-none"+ >+ <NavLabel+ actions={+ <>+ <IconAction+ aria-pressed={searching}+ label={searching ? "Close search" : "Search conversations"}+ onClick={() => (searching ? closeSearch() : setSearching(true))}+ >+ {searching ? <IconX /> : <IconSearch />}+ </IconAction>+ <IconAction+ label="New conversation"+ onClick={onNavigate}+ render={(props) => <Link {...props} {...newChat} />}+ >+ <IconPlus />+ </IconAction>+ </>+ }+ className="mt-[18px]"+ >+ RECENT CHATS+ </NavLabel>+ {searching ? (+ <div className="mb-2 px-1">+ <Input+ aria-label="Search conversations"+ autoFocus+ className="h-8 rounded-[9px] bg-background text-[13px]"+ onChange={(event) => setSearch(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Escape") closeSearch();+ }}+ placeholder="Find a conversation…"+ value={search}+ />+ </div>+ ) : null}+ <div+ className="min-h-0 flex-1 overflow-y-auto max-md:max-h-[27vh]"+ ref={scrollRoot}+ >+ {channels.isPending ? null : channels.error ? (+ <p className="px-3.5 py-1.5 text-[12px] text-(--opendots-error-ink)">+ Couldn't load your conversations. Reload the page.+ </p>+ ) : visible.length === 0 ? (+ <p className="px-3.5 py-1.5 text-[12px] leading-relaxed text-(--opendots-faint)">+ {search.trim()+ ? `No conversation has “${search.trim()}” in its name or latest message.`+ : "No conversations yet. Start one with New chat."}+ </p>+ ) : (+ visible.map((channel) => (+ <ThreadRow+ channel={channel}+ key={channel.id}+ names={channel.agentIds+ .map((id) => nameOf(id))+ .filter(Boolean)+ .join(", ")}+ onNavigate={onNavigate}+ open={place.channelId === channel.id}+ />+ ))+ )}+ {/* OpenBot's own pager: it loads older conversations as the list scrolls to its end. */}+ <ChannelPagination+ query={channels}+ scrollRoot={scrollRoot}+ searching={search.trim().length > 0}+ />+ </div>+ </section>+ );+}++function Count({ value }: { value: number | undefined }) {+ if (!value) return null;+ return (+ <small className="bg-(--opendots-tag) text-[10px] text-(--opendots-tag-ink) tabular-nums">+ {value}+ </small>+ );+}++function WorkspaceLinks({+ place,+ onNavigate,+}: {+ place: Place;+ onNavigate: () => void;+}) {+ const routines = useQuery(routinesQueryOptions());+ const memories = useQuery(memoriesQueryOptions());+ // OpenDots keeps these rows in the chrome's olive ink; the row you are on only gains the tint.+ const row = (section: string) =>+ cn(+ navItem,+ "text-(--opendots-dot-ink)",+ place.section === section &&+ "bg-(--opendots-active) hover:bg-(--opendots-active) [&_svg]:stroke-2",+ );+ const current = (section: Place["section"]) =>+ place.section === section ? ("page" as const) : undefined;+ /*+ * OpenDots' sidebar ends on a few rows. OpenBot's primary destinations and the person's own menu+ * are in the rail at desktop width, so they join these rows only in the phone drawer, where there+ * is no rail. Bots is the row under the list of Bots above.+ */+ const drawerOnly = "md:hidden";+ const navigation = useNavigationItems().filter((item) => item.id !== "bots");+ return (+ <nav+ aria-label="Workspace"+ className="mt-auto border-t border-(--opendots-line) pt-2.5"+ >+ <Link+ aria-current={current("routines")}+ className={row("routines")}+ onClick={onNavigate}+ params={{ screen: "routines" }}+ to="/s/$screen"+ >+ <IconClockHour3 />+ <span className="min-w-0 flex-1 truncate">Routines</span>+ <Count value={routines.data?.routines.length} />+ </Link>+ <Link+ aria-current={current("memories")}+ className={row("memories")}+ onClick={onNavigate}+ params={{ screen: "memories" }}+ to="/s/$screen"+ >+ <IconBook />+ <span className="min-w-0 flex-1 truncate">Memories</span>+ <Count value={memories.data?.length} />+ </Link>+ {/* OpenBot's own destinations, from the one list every frame reads. */}+ {navigation.map((item) => (+ <Link+ aria-current={place.section === item.id ? "page" : undefined}+ className={cn(row(item.id), item.section === "primary" && drawerOnly)}+ key={item.id}+ onClick={onNavigate}+ to={item.to}+ >+ <item.icon />+ <span className="min-w-0 flex-1 truncate">{item.label}</span>+ </Link>+ ))}+ <UserRow />+ </nav>+ );+}++export function initialsOf(user: { name?: string | null; email: string }) {+ return (+ user.name+ ?.trim()+ .split(/\s+/)+ .slice(0, 2)+ .map((part) => part[0]?.toUpperCase())+ .join("") || user.email.slice(0, 2).toUpperCase()+ );+}++/** Who is signed in, and the way out. OpenBot's sidebar keeps this in its user menu. */+function UserRow() {+ const user = useQuery(currentUserQueryOptions());+ const navigate = useNavigate();+ const signOut = useMutation(signOutMutationOptions(queryClient));+ if (!user.data) return null;+ const name = user.data.name?.trim() || user.data.email;+ const initials = initialsOf(user.data);+ return (+ <div className="mt-1.5 flex items-center gap-2.5 px-2.5 pt-1.5 md:hidden">+ <span+ aria-hidden+ className="grid size-[29px] shrink-0 place-items-center rounded-full border border-(--opendots-avatar-line) bg-(--opendots-avatar) text-[10px] text-(--opendots-avatar-ink)"+ >+ {initials}+ </span>+ <span className="min-w-0 flex-1 truncate text-[12px] text-(--opendots-muted)">+ {name}+ </span>+ <IconAction+ disabled={signOut.isPending}+ label="Sign out"+ onClick={async () => {+ await signOut.mutateAsync();+ await navigate({ to: "/sign" });+ }}+ >+ <IconLogout />+ </IconAction>+ </div>+ );+}++/**+ * OpenDots' sidebar over OpenBot's data: the Bots as Dots, the conversations as recent chats, and+ * the workspace views beneath. Every OpenBot surface the default sidebar reaches is here too.+ */+export function OpenDotsSidebar({+ place,+ newChat,+ onNavigate,+}: {+ place: Place;+ newChat: LinkProps;+ onNavigate: () => void;+}) {+ const channels = useInfiniteQuery(channelListQueryOptions());+ return (+ <div className="flex h-full min-h-0 flex-col px-3 pt-[23px] pb-3 max-md:overflow-y-auto">+ <Wordmark onNavigate={onNavigate} />+ <Link+ {...newChat}+ className={cn(+ navItem,+ "mb-[26px] text-(--opendots-new-chat-ink) hover:bg-(--opendots-hover)",+ )}+ onClick={onNavigate}+ >+ <IconPlus />+ <span>New chat</span>+ </Link>+ <BotsSection+ channels={channels.data}+ onNavigate={onNavigate}+ place={place}+ />+ <RecentChats newChat={newChat} onNavigate={onNavigate} place={place} />+ <WorkspaceLinks onNavigate={onNavigate} place={place} />+ </div>+ );+}diff --git a/app/src/skins/opendots/skin.css b/app/src/skins/opendots/skin.cssnew file mode 100644index 00000000..caaf719f--- /dev/null+++ b/app/src/skins/opendots/skin.css@@ -0,0 +1,325 @@+/*+ * OpenDots tokens: `:root[data-skin="opendots"]` for light and `:root[data-skin="opendots"].dark`+ * for dark.+ *+ * Light is OpenDots' own compact chrome: white canvas, one ink accent (#242424), a pale grey rail+ * and sidebar, lavender for the row you are on, and teal for unread chats and your own messages.+ * Dark is what OpenDots' build-time theme makes of the same colours (src/build/dark-theme.ts flips+ * OKLab lightness, keeps hue, and lifts text to AA), with two departures where the flip loses+ * hierarchy: cards sit a step above the canvas, and the breadcrumb keeps a dim and a bright half.+ *+ * Every text colour meets WCAG AA (4.5:1) on the surface it sits on, and every icon 3:1, in both+ * themes. Where OpenDots' own grey fell short, it is darkened along its own hue until it passes.+ */+:root[data-skin="opendots"] {+ color-scheme: light;+ --background: #ffffff;+ --foreground: #333641;+ --card: #ffffff;+ --card-foreground: #333641;+ --popover: #ffffff;+ --popover-foreground: #333641;+ --primary: #242424;+ --primary-foreground: #ffffff;+ --secondary: #f1f1f1;+ --secondary-foreground: #242424;+ --muted: #f5f5f5;+ --muted-foreground: #6b6b6b;+ --accent: #f1f1f1;+ --accent-foreground: #242424;+ --destructive: #a23d35;+ --success: #3d7e75;+ --border: #e7e7e7;+ --input: #dedede;+ --ring: #242424;+ --chart-1: #3d7e75;+ --chart-2: #7285d5;+ --chart-3: #c98a4b;+ --chart-4: #9b82c9;+ --chart-5: #8cac91;+ --radius: 0.5625rem;+ --sidebar: #f9f9f9;+ --sidebar-foreground: #242424;+ --sidebar-primary: #242424;+ --sidebar-primary-foreground: #ffffff;+ --sidebar-accent: #eeeff7;+ --sidebar-accent-foreground: #596aa9;+ --sidebar-border: #e7e7e7;+ --sidebar-ring: #242424;++ --opendots-font: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;+ --opendots-rail: #f5f5f5;+ --opendots-sidebar: #f9f9f9;+ --opendots-topbar: #ffffff;+ --opendots-pane: #fafafa;+ --opendots-line: #e7e7e7;+ --opendots-hover: #f4f4f9;+ --opendots-active: #eeeff7;+ --opendots-active-ink: #596aa9;+ --opendots-tag: #edf1e7;+ --opendots-tag-ink: #526249;+ --opendots-nav-ink: #6c6d77;+ --opendots-dot-ink: #58634f;+ --opendots-new-chat-ink: #53634d;+ --opendots-label: #646b61;+ --opendots-muted: #707070;+ --opendots-faint: #646d5d;+ --opendots-icon: #878a99;+ --opendots-rail-icon: #555555;+ --opendots-teal: #438c81;+ --opendots-crumb: #636d5b;+ --opendots-crumb-ink: #686b76;+ --opendots-toggle-ink: #575e59;+ --opendots-pause-ink: #53624d;+ --opendots-menu-ink: #333333;+ --opendots-tab: #ededed;+ --opendots-eyebrow: #71747f;+ --opendots-scrim: #2f34464d;+ --opendots-pane-shadow: -8px 0 28px #20263418;+ --opendots-user-bubble: #3d7e75;+ --opendots-user-bubble-ink: #ffffff;+ --opendots-assistant-ink: #373737;+ --opendots-composer-line: #dedede;+ --opendots-composer-shadow: 0 3px 14px #00000006;+ --opendots-composer-focus: #c8c8c8;+ --opendots-send-off: #ececec;+ --opendots-send-off-ink: #9a9a9a;+ --opendots-note: #72737d;+ --opendots-persona-ink: #747474;+ --opendots-text-button: #707484;+ --opendots-avatar: #eeeae1;+ --opendots-avatar-line: #e2dfd8;+ --opendots-avatar-ink: #6d675d;+ --opendots-error-ink: #8b6a61;+}++:root[data-skin="opendots"].dark {+ color-scheme: dark;+ --background: #1b1b1b;+ --foreground: #b2b5c1;+ --card: #222222;+ --card-foreground: #b2b5c1;+ --popover: #242424;+ --popover-foreground: #b2b5c1;+ --primary: #c5c5c5;+ --primary-foreground: #1b1b1b;+ --secondary: #242424;+ --secondary-foreground: #c5c5c5;+ --muted: #212121;+ --muted-foreground: #a4a4a4;+ --accent: #262626;+ --accent-foreground: #c5c5c5;+ --destructive: #e4877d;+ --success: #7bb1a8;+ --border: #2b2b2b;+ --input: #313131;+ --ring: #c5c5c5;+ --chart-1: #7bb1a8;+ --chart-2: #91a2db;+ --chart-3: #d9a06a;+ --chart-4: #b39ddb;+ --chart-5: #92ad96;+ --radius: 0.5625rem;+ --sidebar: #1e1e1e;+ --sidebar-foreground: #c5c5c5;+ --sidebar-primary: #c5c5c5;+ --sidebar-primary-foreground: #1b1b1b;+ --sidebar-accent: #242429;+ --sidebar-accent-foreground: #91a2db;+ --sidebar-border: #2b2b2b;+ --sidebar-ring: #c5c5c5;++ --opendots-font: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;+ --opendots-rail: #212121;+ --opendots-sidebar: #1e1e1e;+ --opendots-topbar: #1b1b1b;+ --opendots-pane: #1e1e1e;+ --opendots-line: #2b2b2b;+ --opendots-hover: #212124;+ --opendots-active: #242429;+ --opendots-active-ink: #f2f2f2;+ --opendots-tag: transparent;+ --opendots-tag-ink: #9caa93;+ --opendots-nav-ink: #a3a3ad;+ --opendots-dot-ink: #9ea996;+ --opendots-new-chat-ink: #9baa96;+ --opendots-label: #a1a79e;+ --opendots-muted: #a4a4a4;+ --opendots-faint: #9fa899;+ --opendots-icon: #a1a4b1;+ --opendots-rail-icon: #9c9c9c;+ --opendots-teal: #76b2a8;+ --opendots-crumb: #9fa898;+ --opendots-crumb-ink: #c7c9d1;+ --opendots-toggle-ink: #a0a6a1;+ --opendots-pause-ink: #9ca996;+ --opendots-menu-ink: #b8b8b8;+ --opendots-tab: #272727;+ --opendots-eyebrow: #a1a4ae;+ --opendots-scrim: #00000080;+ --opendots-pane-shadow: -8px 0 28px #00000026;+ --opendots-user-bubble: #5c9189;+ --opendots-user-bubble-ink: #1b1b1b;+ --opendots-assistant-ink: #b5b5b5;+ --opendots-composer-line: #313131;+ --opendots-composer-shadow: 0 3px 14px #0000000a;+ --opendots-composer-focus: #4a4a4a;+ --opendots-send-off: #272727;+ --opendots-send-off-ink: #646464;+ --opendots-note: #a1a2ab;+ --opendots-persona-ink: #a4a4a4;+ --opendots-text-button: #a1a5b4;+ --opendots-avatar: #2b2823;+ --opendots-avatar-line: #32302b;+ --opendots-avatar-ink: #a9a49b;+ --opendots-error-ink: #bb9d94;+}++/* OpenDots sets its type in the system face, not Inter, at a 14px base. */+:root[data-skin="opendots"],+:root[data-skin="opendots"] body {+ font-family: var(--opendots-font);+ font-synthesis: none;+}++/*+ * OpenBot's pages inside the frame, drawn the OpenDots way. Each rule reaches only into+ * `[data-opendots-main]`, the frame's page slot, so Settings and Admin keep OpenBot's own layout in+ * OpenDots' colours.+ */++/* Your own message is OpenDots' teal bubble with its one squared corner. */+:root[data-skin="opendots"]+ [data-opendots-main]+ [data-slot="bubble"][data-align="end"]+ > [data-slot="bubble-content"] {+ background: var(--opendots-user-bubble);+ color: var(--opendots-user-bubble-ink);+ border-radius: 17px 17px 5px 17px;+ padding: 11px 16px;+ font-size: 14px;+ line-height: 1.75;+}++/* A Bot's message is plain prose on the canvas, a shade softer than the ink. */+:root[data-skin="opendots"]+ [data-opendots-main]+ [data-slot="bubble"][data-align="start"][data-variant="ghost"]+ > [data-slot="bubble-content"] {+ color: var(--opendots-assistant-ink);+ font-size: 14px;+ line-height: 1.75;+}++/*+ * OpenBot's pages are reached through the `data-slot` hooks they publish for skins (`composer`,+ * `composer-send`, `conversation-header`, `composer-column`, `detail-pane*`), never through+ * their Tailwind classes, so restyling a page cannot quietly break the skin.+ */++/* The composer is OpenDots' rounded card on the canvas: a 22px radius, a hairline and a breath of shadow. */+:root[data-skin="opendots"] [data-opendots-main] [data-slot="composer"] {+ background: var(--background);+ border-radius: 22px;+ border-color: var(--opendots-composer-line);+ box-shadow: var(--opendots-composer-shadow);+}++:root[data-skin="opendots"]+ [data-opendots-main]+ [data-slot="composer"]:focus-within {+ border-color: var(--opendots-composer-focus);+ box-shadow: var(--opendots-composer-shadow);+}++/* Until there is something to send, OpenDots' send disc is a pale grey with a grey arrow, not a dimmed ink. */+:root[data-skin="opendots"]+ [data-opendots-main]+ [data-slot="composer-send"]:disabled {+ background: var(--opendots-send-off);+ color: var(--opendots-send-off-ink);+ opacity: 1;+}++/*+ * A conversation's own header row sits directly under the top bar. OpenDots draws no rule under+ * its chat header, so the two read as one band instead of two stacked bars.+ */+:root[data-skin="opendots"]+ [data-opendots-main]+ [data-slot="conversation-header"] {+ border-bottom-color: transparent;+}++/* The coworker home steps aside as soon as the conversation has a message to show. */+:root[data-skin="opendots"]+ [data-opendots-main]:has([data-slot="message"])+ [data-opendots-persona] {+ display: none;+}++/*+ * Where the conversation column is no wider than its composer, OpenDots still keeps the composer+ * and its notices off the edges of the pane; OpenBot's runs them flush. 972px is the widest window+ * at which the 672px column fills the pane beside the rail and sidebar.+ */+@media (max-width: 972px) {+ :root[data-skin="opendots"]+ [data-opendots-main]+ [data-slot="composer-column"] {+ padding-inline: 16px;+ }+}++/*+ * A conversation's own Computer pane, which the top bar's computer toggle opens there, dressed as+ * OpenDots' right pane: its grey ground, a ruled 56px header and the title as the selected tab.+ * Only the Computer gives the pane a title; Bot settings leave it empty and keep a plain header.+ */+:root[data-skin="opendots"] [data-opendots-main] [data-slot="detail-pane"] {+ background: var(--opendots-pane);+ border-left-color: var(--opendots-line);+}++:root[data-skin="opendots"]+ [data-opendots-main]+ [data-slot="detail-pane-header"] {+ height: 56px;+ padding-inline: 16px;+ border-bottom: 1px solid var(--opendots-line);+ background: var(--opendots-pane);+}++:root[data-skin="opendots"]+ [data-opendots-main]+ [data-slot="detail-pane-title"]:not(:empty) {+ width: auto;+ flex: none;+ border-radius: 9px;+ padding: 7px 9px;+ background: var(--opendots-tab);+ color: var(--foreground);+ font-size: 13px;+}++/*+ * Reduced motion. The frame's own chrome (rail, sidebar, top bar, computer pane, phone drawer) and+ * the menus, tooltips, sheets and dialogs it opens stop moving: no transitions, no animations.+ * OpenBot's orb in the rail already stills itself through `useReducedMotion`. No `!important`:+ * this rule sits in no cascade layer, so it outranks every Tailwind utility as it is.+ */+@media (prefers-reduced-motion: reduce) {+ :root[data-skin="opendots"] [data-opendots-chrome],+ :root[data-skin="opendots"] [data-opendots-chrome] *,+ :root[data-skin="opendots"] [data-slot="tooltip-content"],+ :root[data-skin="opendots"] [data-slot="dropdown-menu-content"],+ :root[data-skin="opendots"] [data-slot="context-menu-content"],+ :root[data-skin="opendots"] [data-slot="select-content"],+ :root[data-skin="opendots"] [data-slot="sheet-content"],+ :root[data-skin="opendots"] [data-slot="sheet-overlay"],+ :root[data-skin="opendots"] [data-slot="dialog-content"],+ :root[data-skin="opendots"] [data-slot="dialog-overlay"] {+ animation: none;+ transition: none;+ }+}diff --git a/app/src/skins/openduet/frame.tsx b/app/src/skins/openduet/frame.tsxnew file mode 100644index 00000000..8b8acc7d--- /dev/null+++ b/app/src/skins/openduet/frame.tsx@@ -0,0 +1,102 @@+import { useRouterState } from "@tanstack/react-router";+import { type CSSProperties, type ReactNode, useState } from "react";+import { BotsNavBadge } from "@/components/bot-profile/attention";+import { SelfHostBanner } from "@/components/layout/self-host-banner";+import { useChannelEvents } from "@/lib/channels/use-channel-events";+import { cn } from "@/lib/utils";+import { PageHeader, TabHeader } from "./header";+import { MenuSheet } from "./menu-sheet";+import { columnFor, isSkinScreen, tabForPath } from "./places";+import { TabBar } from "./tab-bar";++/** The height the floating tab bar covers at the column's foot: its 64px and its 22px lift. */+const TAB_SPACE = 86;++/** How wide each kind of column may grow; see `columnFor`. */+const COLUMN_WIDTH = {+ phone: "max-w-[430px]",+ pane: "max-w-[830px]",+ page: "max-w-none",+} as const;++/**+ * OpenDuet's frame around every OpenBot page.+ *+ * Chat and Tasks are one column the width of a phone, centred on a wide screen, with the header+ * floating at the top (the menu, the orb and the person's initial) and the frosted tab bar at the+ * foot. When a conversation opens its Bot's details or computer, the column grows by OpenBot's own+ * 400px pane, so the computer sits beside the conversation as it does in OpenBot. Every other page+ * opens over the app with a back disc and keeps OpenBot's own width, so a Bot's page or Admin is as+ * roomy as OpenBot made it, in OpenDuet's colours and type.+ *+ * The pages inside are OpenBot's own, so its chat, its tools and its approvals run unchanged. The+ * frame keeps the two things OpenBot's sidebar did beyond drawing: the one socket that keeps the+ * conversation list live, and the browser notification when a Bot starts needing the person.+ */+export function OpenDuetFrame({ children }: { children: ReactNode }) {+ const location = useRouterState({ select: (state) => state.location });+ const pathname = location.pathname;+ const tab = tabForPath(pathname);+ const column = columnFor(pathname, location.search);+ const ownScreen = isSkinScreen(pathname);+ const [menuOpen, setMenuOpen] = useState(false);+ // Any navigation closes the menu, including a conversation picked from inside it.+ const [shownPath, setShownPath] = useState(pathname);+ if (shownPath !== pathname) {+ setShownPath(pathname);+ setMenuOpen(false);+ }+ // One socket for the app: it keeps the conversation list and its working dots live.+ useChannelEvents();+ const [main, setMain] = useState<HTMLElement | null>(null);++ return (+ <div+ className="flex h-svh flex-col overflow-hidden bg-openduet-surface text-openduet-ink"+ data-openduet-frame=""+ >+ {/*+ * OpenBot's Bots badge is what sends the browser notification when a Bot starts needing the+ * person. The menu draws its own badge from the same count, so this one is mounted unseen,+ * only to keep that notification coming.+ */}+ <div hidden>+ <BotsNavBadge />+ </div>+ <SelfHostBanner />+ <div+ className={cn(+ "relative mx-auto flex min-h-0 w-full flex-1 flex-col",+ COLUMN_WIDTH[column],+ )}+ data-openduet-column={column}+ data-openduet-page={tab ? undefined : ""}+ data-openduet-tab={tab ?? undefined}+ style={{ "--openduet-tab-space": `${TAB_SPACE}px` } as CSSProperties}+ >+ {tab ? (+ <TabHeader+ floating={ownScreen}+ main={main}+ menuOpen={menuOpen}+ onMenu={() => setMenuOpen(true)}+ />+ ) : (+ <PageHeader main={main} />+ )}+ <main+ className={cn(+ "flex min-h-0 flex-1 flex-col overflow-hidden",+ // An OpenBot page ends above the tab bar, so its composer is never under it.+ tab && !ownScreen && "pb-[92px]",+ )}+ ref={setMain}+ >+ {children}+ </main>+ {tab ? <TabBar current={tab} /> : null}+ </div>+ <MenuSheet onOpenChange={setMenuOpen} open={menuOpen} />+ </div>+ );+}diff --git a/app/src/skins/openduet/header.tsx b/app/src/skins/openduet/header.tsxnew file mode 100644index 00000000..85e81c06--- /dev/null+++ b/app/src/skins/openduet/header.tsx@@ -0,0 +1,300 @@+import { IconChevronLeft } from "@tabler/icons-react";+import { useInfiniteQuery, useQuery } from "@tanstack/react-query";+import {+ Link,+ useCanGoBack,+ useNavigate,+ useParams,+ useRouter,+} from "@tanstack/react-router";+import { useEffect, useState } from "react";+import AgentOrb from "@/components/agents/orb/agent-orb";+import type { AIState } from "@/components/agents/orb/ai-core";+import { currentUserQueryOptions } from "@/lib/auth/queries";+import {+ type ChannelWork,+ channelListQueryOptions,+} from "@/lib/channels/queries";+import { deploymentCapabilitiesQueryOptions } from "@/lib/deployment/queries";+import { appConfig } from "@/lib/generated/application-config";+import { useNavigationItems } from "@/lib/navigation";+import { cn } from "@/lib/utils";+import { IconMenuShort } from "./icons";+import { DISC, FOCUS } from "./kit";+import {+ EDITOR_SELECTOR,+ pressOrb,+ pressOrbWhenReady,+ useComposerPresence,+} from "./orb-dictation";++/** The header's side discs: 46px, past the 44px a finger needs. */+const SIDE = 46;+/** The orb's footprint on a tab. */+const ORB = 62;++/** The person's initial, from their name, or their email when they have none. */+export function initialOf(user: { name?: string | null; email: string }) {+ const source = user.name?.trim() || user.email;+ return (source.match(/\p{L}|\p{N}/u)?.[0] ?? "?").toUpperCase();+}++/**+ * What the open conversation is doing, from the roster OpenBot keeps live over its socket: a turn+ * running, or work it waits on between turns.+ */+function useOpenConversation() {+ const channelId = useParams({+ strict: false,+ select: (params) => (params as { channelId?: string }).channelId,+ });+ const roster = useInfiniteQuery({+ ...channelListQueryOptions(),+ enabled: channelId !== undefined,+ });+ const channel = channelId+ ? roster.data?.find((row) => row.id === channelId)+ : undefined;+ const work: ChannelWork[] = channel?.work ?? [];+ return { busy: (channel?.busy ?? false) || work.length > 0, work };+}++/** What the Bot is doing, in a few words, for the pill under the orb. */+export function doingLine(busy: boolean, work: ChannelWork[]): string | null {+ const first = work[0];+ if (first?.kind === "handoff")+ return `Asking ${first.botName ?? "another Bot"}`;+ if (first?.kind === "routine") return "Running a routine";+ return busy ? "Thinking" : null;+}++/**+ * OpenDuet's header on a tab: the menu in a disc on the left, an orb in the centre, the person's+ * initial in a disc on the right (their settings). The orb is OpenBot's own (`AgentOrb`, as sign-in+ * and onboarding draw it), so the frame carries the deployment's identity, not OpenDuet's. It is the+ * way to talk: pressed, it+ * starts the composer's own dictation, or, on a screen with no composer, opens Chat and starts it+ * there. It looks down while the person types or talks, and thinks while the Bot works, with a pill+ * under it saying what the Bot is doing.+ *+ * `floating` lays it over a screen that scrolls under it, behind a fade. Otherwise it is a bar in+ * the column's flow, over an OpenBot page that owns its own scroller.+ */+export function TabHeader({+ floating,+ menuOpen,+ onMenu,+ main,+}: {+ floating: boolean;+ menuOpen: boolean;+ onMenu: () => void;+ /** The frame's content, where the composer the orb talks through is drawn. */+ main: HTMLElement | null;+}) {+ const { data: user } = useQuery(currentUserQueryOptions());+ // Settings, from OpenBot's one navigation list, behind the person's initial.+ const settings = useNavigationItems().find((item) => item.id === "settings");+ const capabilities = useQuery(deploymentCapabilitiesQueryOptions());+ const canDictate = capabilities.data?.transcription === true;+ const presence = useComposerPresence(main);+ const conversation = useOpenConversation();+ const navigate = useNavigate();+ const [goingToTalk, setGoingToTalk] = useState<(() => void) | null>(null);+ useEffect(() => () => goingToTalk?.(), [goingToTalk]);++ // Working is the composer's own Stop control or the roster's word for a run nobody here started.+ const working = presence.working || conversation.busy;+ const state: AIState = presence.recording+ ? "listening"+ : working+ ? "thinking"+ : presence.typing+ ? "listening"+ : "idle";++ const press = () => {+ if (!main) return;+ if (canDictate && pressOrb(main) !== "none") return;+ // A composer that cannot take dictation right now still takes typing.+ const editor = main.querySelector<HTMLElement>(EDITOR_SELECTOR);+ if (editor) {+ editor.focus();+ return;+ }+ void navigate({ to: "/" }).then(() => {+ if (canDictate) setGoingToTalk(() => pressOrbWhenReady(() => main));+ });+ };++ const label = !canDictate+ ? "Chat"+ : presence.recording+ ? "Stop and add to your message"+ : `Talk to ${appConfig.brand.productName}`;++ return (+ <header+ className={cn(+ "z-20 flex items-start justify-between px-4 pt-3",+ floating+ ? "pointer-events-none absolute inset-x-0 top-0 h-32 bg-(image:--openduet-fade)"+ : "relative h-[84px] shrink-0 bg-openduet-surface",+ )}+ >+ <button+ aria-expanded={menuOpen}+ aria-label="Menu"+ className={cn(DISC, "pointer-events-auto mt-2")}+ onClick={onMenu}+ style={{ width: SIDE, height: SIDE }}+ type="button"+ >+ <IconMenuShort size={21} stroke={1.8} />+ </button>+ {/* The span between the discs, so the pill under the orb never reaches under either. */}+ <div className="flex min-w-0 flex-1 flex-col items-center gap-1 px-2">+ <button+ aria-label={label}+ aria-pressed={canDictate ? presence.recording : undefined}+ className={cn(+ "pointer-events-auto grid shrink-0 place-items-center rounded-full transition-transform active:scale-95 motion-reduce:transition-none motion-reduce:active:scale-100",+ FOCUS,+ )}+ onClick={press}+ style={{ width: ORB, height: ORB }}+ title={label}+ type="button"+ >+ <AgentOrb size={`${ORB - 6}px`} state={state} />+ </button>+ <DoingPill line={doingLine(working, conversation.work)} />+ </div>+ <Link+ aria-label="Your settings"+ to={settings?.to ?? "/settings"}+ className={cn(DISC, "pointer-events-auto mt-2")}+ style={{ width: SIDE, height: SIDE }}+ >+ <span className="openduet-type-nav font-semibold">+ {user ? initialOf(user) : null}+ </span>+ </Link>+ </header>+ );+}++/**+ * What the Bot is doing, in a glass pill under the orb. Always mounted, so the live region is there+ * before the first words arrive and it can fade out as well as in.+ */+function DoingPill({ line }: { line: string | null }) {+ const [held, setHeld] = useState(line);+ if (line !== null && line !== held) setHeld(line);+ const shown = line !== null;+ return (+ <div aria-live="polite" className="flex h-6 max-w-full justify-center">+ <p+ aria-hidden={shown ? undefined : true}+ className="openduet-glass openduet-type-caption flex h-6 max-w-full items-center rounded-full px-2.5 font-semibold text-openduet-ink shadow-openduet-glass transition-opacity duration-200 data-[shown=false]:opacity-0 motion-reduce:transition-none"+ data-shown={shown}+ >+ <span className="tool-line-running truncate">{held}</span>+ </p>+ </div>+ );+}++/** What a page drawn under the chrome says about itself. */+export type PageFacts = {+ /** The page's own title, from its `page-title` hook. */+ title: string | null;+ /** Where the page's own back link goes, and what it calls it, when the page has one. */+ back: { href: string; label: string } | null;+};++/**+ * Read the page's title and its own back link, for the chrome to show in their place. Only read:+ * the page is OpenBot's, rendered by React, and nothing here writes to it. The back link sits in the+ * bar `PageShell` draws above the scroller that holds the page's header.+ */+export function readPageFacts(root: ParentNode): PageFacts {+ const header = root.querySelector('[data-slot="page-header"]');+ const title =+ root.querySelector('[data-slot="page-title"]')?.textContent?.trim() || null;+ const bar = header?.parentElement?.parentElement?.previousElementSibling;+ const link = bar?.querySelector<HTMLAnchorElement>("a[href]");+ const href = link?.getAttribute("href");+ return {+ title,+ back: href ? { href, label: link?.textContent?.trim() ?? "" } : null,+ };+}++function usePageFacts(root: HTMLElement | null): PageFacts {+ const [facts, setFacts] = useState<PageFacts>({ title: null, back: null });+ useEffect(() => {+ if (!root) return;+ const read = () =>+ setFacts((before) => {+ const now = readPageFacts(root);+ return now.title === before.title &&+ now.back?.href === before.back?.href &&+ now.back?.label === before.back?.label+ ? before+ : now;+ });+ read();+ const observer = new MutationObserver(read);+ observer.observe(root, {+ childList: true,+ subtree: true,+ characterData: true,+ });+ return () => observer.disconnect();+ }, [root]);+ return facts;+}++/**+ * The chrome for a page opened over the app: a back disc on the left, the page's title in a glass+ * pill in the middle, and nothing on the right. No menu, no avatar and no tab bar, so a page reads+ * as somewhere you came to and go back from. Back goes where the page's own back link goes when it+ * has one (a Bot's page goes to Bots), back through history otherwise, and to Chat with neither.+ */+export function PageHeader({ main }: { main: HTMLElement | null }) {+ const router = useRouter();+ const canGoBack = useCanGoBack();+ const { title, back } = usePageFacts(main);+ return (+ <header className="relative z-20 flex h-[72px] shrink-0 items-start gap-2 px-4 pt-3">+ <button+ aria-label={back?.label ? `Back to ${back.label}` : "Back"}+ className={DISC}+ onClick={() => {+ if (back) void router.navigate({ href: back.href });+ else if (canGoBack) router.history.back();+ else void router.navigate({ to: "/" });+ }}+ style={{ width: SIDE, height: SIDE }}+ type="button"+ >+ <IconChevronLeft size={22} stroke={1.8} />+ </button>+ <div className="flex min-w-0 flex-1 justify-center">+ {title ? (+ <div className="openduet-glass flex h-[46px] min-w-0 max-w-full items-center justify-center rounded-full px-4 shadow-openduet-glass">+ {/* The page's own title stays for screen readers; this is what the eye reads. */}+ <p+ aria-hidden+ className="openduet-type-sub max-w-full truncate font-semibold text-openduet-ink"+ >+ {title}+ </p>+ </div>+ ) : null}+ </div>+ <span aria-hidden className="shrink-0" style={{ width: SIDE }} />+ </header>+ );+}diff --git a/app/src/skins/openduet/icons.ts b/app/src/skins/openduet/icons.tsnew file mode 100644index 00000000..afa80cac--- /dev/null+++ b/app/src/skins/openduet/icons.ts@@ -0,0 +1,41 @@+import { createReactComponent } from "@tabler/icons-react";++/*+ * Two of OpenDuet's glyphs have no Tabler twin, and they are the two a person sees on every screen:+ * the menu (two long lines over a short one) and the Tasks tab (a box, a check, three lines). They+ * are made as Tabler icons, on Tabler's 24-unit grid with its round caps and props, so they sit in+ * a row of Tabler icons at the same weight. Everything else in the skin is Tabler's own.+ */++export const IconMenuShort = createReactComponent(+ "outline",+ "menu-short",+ "MenuShort",+ [["path", { d: "M4 7h16M4 12h16M4 17h10", key: "menu-short-lines" }]],+);++export const IconTasksList = createReactComponent(+ "outline",+ "tasks-list",+ "TasksList",+ [+ [+ "rect",+ {+ x: "3",+ y: "4",+ width: "6",+ height: "6",+ rx: "1.5",+ key: "tasks-list-box",+ },+ ],+ [+ "path",+ {+ d: "m3 17 2 2 4-4M13 5h8M13 12h8M13 19h8",+ key: "tasks-list-lines",+ },+ ],+ ],+);diff --git a/app/src/skins/openduet/index.ts b/app/src/skins/openduet/index.tsnew file mode 100644index 00000000..9e2315b1--- /dev/null+++ b/app/src/skins/openduet/index.ts@@ -0,0 +1,13 @@+import type { Skin } from "../types";+import { OpenDuetFrame } from "./frame";+import { TASKS_SCREEN } from "./places";+import { TasksScreen } from "./tasks-screen";++export const openduet: Skin = {+ id: "openduet",+ name: "OpenDuet",+ description:+ "Bots that keep you in the loop, in a column shaped like a phone.",+ Frame: OpenDuetFrame,+ screens: { [TASKS_SCREEN]: TasksScreen },+};diff --git a/app/src/skins/openduet/kit.tsx b/app/src/skins/openduet/kit.tsxnew file mode 100644index 00000000..3fe27cc2--- /dev/null+++ b/app/src/skins/openduet/kit.tsx@@ -0,0 +1,19 @@+import { cn } from "@/lib/utils";++/*+ * The two pieces of OpenDuet's chrome the frame's parts share: the focus ring and the glass disc.+ * Everything a screen lists is OpenBot's own component; these only dress the frame around it.+ */++/** The focus ring every control in the frame draws: the accent, soft. */+export const FOCUS =+ "outline-none focus-visible:ring-3 focus-visible:ring-openduet-accent/40";++/**+ * A round glass control over the screen: the header's discs. It gives a little when pressed,+ * unless the person asked for less motion.+ */+export const DISC = cn(+ "openduet-glass grid shrink-0 place-items-center rounded-full text-openduet-ink shadow-openduet-glass transition-transform duration-[120ms] active:scale-95 motion-reduce:transition-none motion-reduce:active:scale-100",+ FOCUS,+);diff --git a/app/src/skins/openduet/menu-sheet.tsx b/app/src/skins/openduet/menu-sheet.tsxnew file mode 100644index 00000000..8e106eb0--- /dev/null+++ b/app/src/skins/openduet/menu-sheet.tsx@@ -0,0 +1,436 @@+import {+ IconChevronRight,+ IconLogout,+ IconPin,+ IconPinFilled,+ IconPinnedOff,+ IconPlus,+ IconStack2,+ IconTrash,+} from "@tabler/icons-react";+import { useInfiniteQuery, useMutation, useQuery } from "@tanstack/react-query";+import { Link, useNavigate, useParams } from "@tanstack/react-router";+import { type ReactNode, useId, useRef, useState } from "react";+import { isUnread, pinnedFirst } from "@/components/app-sidebar/app-sidebar";+import { ChannelPagination } from "@/components/app-sidebar/channel-pagination";+import { needsInput } from "@/components/bot-profile/attention";+import { ChannelAvatar } from "@/components/channels/avatar";+import { DeleteConversationDialog } from "@/components/channels/delete-conversation-dialog";+import {+ ContextMenu,+ ContextMenuContent,+ ContextMenuItem,+ ContextMenuTrigger,+} from "@/components/ui/context-menu";+import {+ Sheet,+ SheetContent,+ SheetDescription,+ SheetHeader,+ SheetTitle,+} from "@/components/ui/sheet";+import { agentListQueryOptions } from "@/lib/agents/queries";+import { signOutMutationOptions } from "@/lib/auth/mutations";+import { currentUserQueryOptions } from "@/lib/auth/queries";+import { botAttentionQueryOptions } from "@/lib/bot-lifecycle/queries";+import { setChannelPinnedMutationOptions } from "@/lib/channels/mutations";+import {+ type ChannelSummary,+ channelListQueryOptions,+} from "@/lib/channels/queries";+import { appConfig } from "@/lib/generated/application-config";+import { useNavigationItems } from "@/lib/navigation";+import { relativeTime } from "@/lib/relative-time";+import { useMessageListEmphasis } from "@/lib/settings/message-list";+import { cn } from "@/lib/utils";+import { queryClient } from "@/query-client";+import { FOCUS } from "./kit";++/** Whether Manage was left open, kept in this browser between visits. */+export const MANAGE_STORAGE_KEY = "openduet.menu-manage";++function rememberedOpen(key: string): boolean {+ try {+ return window.localStorage.getItem(key) === "open";+ } catch {+ return false;+ }+}++function rememberOpen(key: string, open: boolean) {+ try {+ window.localStorage.setItem(key, open ? "open" : "closed");+ } catch {+ // Storage can be refused. The group still opens; it just starts closed next time.+ }+}++/** A row in the menu: a line glyph and the place's name, at least 48px tall. */+const ROW = cn(+ "openduet-type-nav flex min-h-12 w-full items-center gap-3 rounded-[22px] px-3 font-medium text-openduet-ink transition-colors duration-[120ms] motion-reduce:transition-none hover:bg-openduet-tile active:bg-openduet-tile [&_svg]:shrink-0 [&>svg]:text-openduet-ink-2",+ FOCUS,+);+/** A row with a disc, a name and a line under it: Chat and each conversation. */+const TALL_ROW = cn(+ "flex min-h-[52px] w-full items-center gap-3 rounded-[24px] px-2.5 py-1.5 text-left hover:bg-openduet-tile",+ FOCUS,+);+const HERE = { className: "bg-openduet-tile" };++/**+ * The drawer behind the header's left disc. From the top: the product's name and who is signed in;+ * Chat, where a conversation starts; every conversation OpenBot keeps for this person, pinned first+ * and newest after, joined to Chat by a hairline; New conversation; then the pages that set things+ * up, under Manage, closed until somebody opens it; and Settings on its own, never folded, because+ * the skin picker is there.+ *+ * The conversations take the height that is left and scroll by themselves, so the rows above and+ * below stay put, and older ones load as the list nears its end, as OpenBot's sidebar does.+ */+export function MenuSheet({+ open,+ onOpenChange,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+}) {+ const navigate = useNavigate();+ const { data: user } = useQuery(currentUserQueryOptions());+ const signOut = useMutation(signOutMutationOptions(queryClient));+ const channels = useInfiniteQuery(channelListQueryOptions());+ const [manageOpen, setManageOpen] = useState(() =>+ rememberedOpen(MANAGE_STORAGE_KEY),+ );+ const manageId = useId();+ const scrollRoot = useRef<HTMLDivElement>(null);+ const close = () => onOpenChange(false);+ const conversations = pinnedFirst(channels.data ?? []);+ // OpenBot's one navigation list, for this person: Settings on its own, the rest under Manage.+ const navigation = useNavigationItems();+ const settings = navigation.find((item) => item.id === "settings");+ const places = navigation.filter((item) => item.id !== "settings");++ return (+ <Sheet onOpenChange={onOpenChange} open={open}>+ {/* No close button: the drawer closes on the screen beside it, on Escape, and on a row. */}+ <SheetContent+ className="w-[340px] max-w-[calc(100vw-48px)] gap-0 border-openduet-hair bg-openduet-surface p-0 text-openduet-ink sm:max-w-[340px]"+ showCloseButton={false}+ side="left"+ >+ <SheetHeader className="px-5 pt-5 pb-3">+ <SheetTitle className="openduet-type-display font-semibold text-openduet-ink">+ {appConfig.brand.productName}+ </SheetTitle>+ <SheetDescription className="openduet-type-sub truncate text-openduet-ink-2">+ {user?.name || user?.email}+ </SheetDescription>+ </SheetHeader>+ <nav+ aria-label="Menu"+ className="flex min-h-0 flex-1 flex-col px-3 pb-4"+ >+ <Link+ activeOptions={{ exact: true }}+ activeProps={HERE}+ className={TALL_ROW}+ onClick={close}+ to="/"+ >+ <span+ aria-hidden+ className="grid size-6 shrink-0 place-items-center text-openduet-accent"+ >+ <IconStack2 size={24} stroke={1.9} />+ </span>+ <RowText line="Start a conversation with any Bot" name="Chat" />+ </Link>+ <div className="mt-1 flex min-h-0 flex-1 flex-col">+ <div+ className="min-h-0 shrink overflow-y-auto overscroll-contain"+ ref={scrollRoot}+ >+ {channels.isPending ? null : channels.error ? (+ <p+ className="openduet-type-sub px-3 py-2 text-openduet-problem"+ role="alert"+ >+ Couldn't load your conversations. Reload the page.+ </p>+ ) : conversations.length > 0 ? (+ /*+ * Indented under Chat and joined to it by a hairline running down from Chat's glyph:+ * these are the conversations Chat has held, not places beside it.+ */+ <ul+ aria-label="Conversations"+ className="ml-[21px] flex flex-col border-openduet-ink-3/40 border-l pl-1.5"+ >+ {conversations.map((channel) => (+ <li key={channel.id}>+ <ConversationRow channel={channel} onOpen={close} />+ </li>+ ))}+ </ul>+ ) : null}+ <ChannelPagination+ query={channels}+ scrollRoot={scrollRoot}+ searching={false}+ />+ </div>+ <Link+ activeProps={HERE}+ className={cn(ROW, "mt-1 shrink-0")}+ onClick={close}+ to="/channel/new"+ >+ <IconPlus size={22} stroke={1.8} />+ New conversation+ </Link>+ </div>+ <div className="mt-2 flex shrink-0 flex-col border-openduet-hair border-t pt-2">+ <h2>+ <button+ aria-controls={manageId}+ aria-expanded={manageOpen}+ className={ROW}+ onClick={() => {+ rememberOpen(MANAGE_STORAGE_KEY, !manageOpen);+ setManageOpen(!manageOpen);+ }}+ type="button"+ >+ <IconChevronRight+ className={cn(+ "transition-transform motion-reduce:transition-none",+ manageOpen && "rotate-90",+ )}+ size={22}+ stroke={1.8}+ />+ Manage+ {/* Closed, the group would hide what waits on the person, so Manage carries it. */}+ {manageOpen ? null : <AccentBadge />}+ </button>+ </h2>+ <div+ className="flex max-h-[40svh] flex-col overflow-y-auto"+ hidden={!manageOpen}+ id={manageId}+ >+ {places.map((place) => (+ <Link+ activeProps={HERE}+ className={ROW}+ key={place.id}+ onClick={close}+ to={place.to}+ >+ <place.icon size={22} stroke={1.8} />+ {place.label}+ {place.id === "bots" ? <AccentBadge /> : null}+ </Link>+ ))}+ </div>+ {settings ? (+ <Link+ activeProps={HERE}+ className={ROW}+ onClick={close}+ to={settings.to}+ >+ <settings.icon size={22} stroke={1.8} />+ {settings.label}+ </Link>+ ) : null}+ <button+ className={ROW}+ disabled={signOut.isPending}+ onClick={async () => {+ await signOut.mutateAsync();+ close();+ await navigate({ to: "/sign" });+ }}+ type="button"+ >+ <IconLogout size={22} stroke={1.8} />+ {signOut.isPending ? "Signing out…" : "Sign out"}+ </button>+ </div>+ </nav>+ </SheetContent>+ </Sheet>+ );+}++/**+ * What waits on the person across their Bots, from OpenBot's own count (the number its sidebar's+ * Bots badge shows), in OpenDuet's one badge style: the accent, with what sits on it. A dot when the+ * only news is something unread.+ */+function AccentBadge() {+ const attention = useQuery(botAttentionQueryOptions());+ 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="openduet-type-caption ml-auto grid h-5 min-w-5 place-items-center rounded-full bg-openduet-accent px-1.5 font-semibold text-openduet-on-accent 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-openduet-accent"+ role="img"+ />+ );+ return null;+}++/** A name in the row's ink, and one line under it, cut short. */+function RowText({+ name,+ line,+ strong = false,+}: {+ name: ReactNode;+ line: ReactNode;+ strong?: boolean;+}) {+ return (+ <span className="min-w-0 flex-1">+ <span+ className={cn(+ "block truncate text-[18px] text-openduet-ink leading-[22px]",+ strong ? "font-semibold" : "font-medium",+ )}+ >+ {name}+ </span>+ {line ? (+ <span className="block truncate text-[13px] text-openduet-ink-2 leading-[17px]">+ {line}+ </span>+ ) : null}+ </span>+ );+}++/**+ * One conversation: its Bots' avatars on a disc (OpenBot's, from each Bot's seed), then its title and its Bot, in the order the person+ * chose in OpenBot's preferences. A dot when a Bot said something they have not seen; the faces+ * type while a Bot works there. Held down or right-clicked, it pins or deletes, as OpenBot's roster+ * does.+ */+function ConversationRow({+ channel,+ onOpen,+}: {+ channel: ChannelSummary;+ onOpen: () => void;+}) {+ const emphasis = useMessageListEmphasis();+ const navigate = useNavigate();+ const bots = useQuery(agentListQueryOptions());+ // Each Bot's own avatar, drawn from its seed as OpenBot's Bot pages draw it.+ const seeds = channel.agentIds.map(+ (id) => bots.data?.find((bot) => bot.id === id)?.avatarSeed ?? id,+ );+ const isOpen = useParams({+ strict: false,+ select: (params) =>+ (params as { channelId?: string }).channelId === channel.id,+ });+ const unread = isUnread(channel, isOpen ? channel.id : undefined);+ const setPinned = useMutation(setChannelPinnedMutationOptions(queryClient));+ const [confirming, setConfirming] = useState(false);+ const [problem, setProblem] = useState<string | null>(null);+ const title = channel.summary || channel.lastMessage || "New conversation";+ const when = channel.lastMessageAt+ ? relativeTime(channel.lastMessageAt)+ : null;+ const busy = (channel.busy ?? false) || (channel.work?.length ?? 0) > 0;+ const [name, line] =+ emphasis === "agent"+ ? [channel.name, title]+ : [title, when ? `${channel.name} · ${when}` : channel.name];+ const group = channel.agentIds.length > 1;++ return (+ <>+ <ContextMenu>+ <ContextMenuTrigger>+ <Link+ activeProps={HERE}+ className={TALL_ROW}+ onClick={onOpen}+ params={{ channelId: channel.id }}+ to={group ? "/group/$channelId" : "/channel/$channelId"}+ >+ <span className="shrink-0">+ <ChannelAvatar participantIds={seeds} size={28} typing={busy} />+ </span>+ <RowText line={line} name={name} strong={unread} />+ {channel.pinned ? (+ <IconPinFilled+ aria-label="Pinned"+ className="shrink-0 text-openduet-ink-3"+ size={14}+ />+ ) : null}+ {unread ? (+ <span+ aria-label="Unread"+ className="size-2 shrink-0 rounded-full bg-openduet-accent"+ role="img"+ />+ ) : null}+ </Link>+ </ContextMenuTrigger>+ <ContextMenuContent>+ <ContextMenuItem+ onClick={() => {+ setProblem(null);+ setPinned.mutate(+ { channelId: channel.id, pinned: !channel.pinned },+ { onError: (thrown) => setProblem(thrown.message) },+ );+ }}+ >+ {channel.pinned ? <IconPinnedOff /> : <IconPin />}+ {channel.pinned ? "Unpin conversation" : "Pin conversation"}+ </ContextMenuItem>+ <ContextMenuItem+ onClick={() => setConfirming(true)}+ variant="destructive"+ >+ <IconTrash />+ Delete conversation…+ </ContextMenuItem>+ </ContextMenuContent>+ </ContextMenu>+ {problem ? (+ <p+ className="openduet-type-caption px-3 pb-1 text-openduet-problem"+ role="alert"+ >+ {problem}+ </p>+ ) : null}+ <DeleteConversationDialog+ channelId={channel.id}+ leave={isOpen ? () => navigate({ to: "/" }) : undefined}+ name={channel.name}+ onOpenChange={setConfirming}+ open={confirming}+ />+ </>+ );+}diff --git a/app/src/skins/openduet/orb-dictation.ts b/app/src/skins/openduet/orb-dictation.tsnew file mode 100644index 00000000..997645d5--- /dev/null+++ b/app/src/skins/openduet/orb-dictation.ts@@ -0,0 +1,140 @@+import { useEffect, useState } from "react";++/*+ * THE ORB TALKS THROUGH THE COMPOSER'S OWN DICTATION, IT DOES NOT HAVE ONE OF ITS OWN.+ *+ * OpenBot's composer owns dictation end to end (`components/channels/composer/use-dictation.ts`):+ * the recording, the transcription, the waveform, Retry, and where the words land, which is that+ * composer's draft. A second session in the header would have to put text into an editor it does+ * not own, and would race the composer's own. So the orb presses the composer's own control, by+ * the name OpenBot gives it, and reads the composer's own controls back to know it is listening.+ * Everything a person sees while they talk is OpenBot's.+ *+ * Every part of the composer is found by the `data-slot` hooks OpenBot gives skins, never by its+ * classes or its words; `tests/skins-openduet-orb.test.tsx` renders the real composer and holds+ * every one of these to it.+ */++/** The composer's mic button, drawn only where this deployment can transcribe. */+export const DICTATE_SELECTOR = '[data-slot="composer-dictate"]';+/** Drawn by the composer for as long as a recording is open. */+export const RECORDING_SELECTOR = '[data-slot="composer-dictate-cancel"]';+/** Ends the recording and puts the words in the draft. */+export const STOP_SELECTOR = '[data-slot="composer-dictate-stop"]';+/**+ * Drawn by the composer for as long as the Bot's turn runs in this conversation: the most direct+ * word OpenBot has that the Bot is working, and it needs no round trip through the server.+ */+export const WORKING_SELECTOR = '[data-slot="composer-stop"]';+/**+ * How long the Stop control has to stay before the orb reads the Bot as working. Opening a+ * conversation shows it for a moment while OpenBot checks for a turn already running, and an orb+ * that thought for that moment on every open would be a flicker, not news. A real turn runs far+ * longer than this.+ */+export const WORKING_SETTLE_MS = 700;+/** The composer's input, around its editor. */+export const INPUT_SELECTOR = '[data-slot="composer-input"]';+/** The editor itself, which takes the focus. */+export const EDITOR_SELECTOR = `${INPUT_SELECTOR} [contenteditable="true"]`;++function enabled(button: Element | null): HTMLButtonElement | null {+ return button instanceof HTMLButtonElement && !button.disabled+ ? button+ : null;+}++export type OrbPress = "started" | "stopped" | "none";++/**+ * Press the orb over `root`: stop a recording that is open, start one in the composer on screen, or+ * report that there is no composer here to talk into.+ */+export function pressOrb(root: ParentNode): OrbPress {+ const stop = enabled(root.querySelector(STOP_SELECTOR));+ if (stop) {+ stop.click();+ return "stopped";+ }+ if (root.querySelector(RECORDING_SELECTOR)) return "none";+ const dictate = enabled(root.querySelector(DICTATE_SELECTOR));+ if (dictate) {+ dictate.click();+ return "started";+ }+ return "none";+}++/**+ * Start dictating in the composer once it is drawn: after the orb took the person to Chat from a+ * screen with no composer, the next one to mount is the one they meant. Gives up after `timeoutMs`,+ * leaving them in Chat with the composer in front of them.+ */+export function pressOrbWhenReady(+ root: () => ParentNode | null,+ timeoutMs = 3_000,+): () => void {+ const until = Date.now() + timeoutMs;+ let frame = 0;+ const attempt = () => {+ const node = root();+ if (node && pressOrb(node) === "started") return;+ if (Date.now() < until) frame = requestAnimationFrame(attempt);+ };+ frame = requestAnimationFrame(attempt);+ return () => cancelAnimationFrame(frame);+}++/**+ * Whether the composer inside `root` is listening, whether the Bot it talks to is working, and+ * whether the person is typing in it.+ */+export function useComposerPresence(root: HTMLElement | null) {+ const [recording, setRecording] = useState(false);+ const [working, setWorking] = useState(false);+ const [typing, setTyping] = useState(false);++ useEffect(() => {+ if (!root) return;+ // The transcript mutates on every streamed word; only a change in either is news.+ let lastRecording: boolean | null = null;+ let lastWorking: boolean | null = null;+ let settle: ReturnType<typeof setTimeout> | undefined;+ const read = () => {+ const isRecording = root.querySelector(RECORDING_SELECTOR) !== null;+ const isWorking = root.querySelector(WORKING_SELECTOR) !== null;+ if (isRecording !== lastRecording) {+ lastRecording = isRecording;+ setRecording(isRecording);+ }+ if (isWorking !== lastWorking) {+ lastWorking = isWorking;+ clearTimeout(settle);+ if (isWorking)+ settle = setTimeout(() => setWorking(true), WORKING_SETTLE_MS);+ else setWorking(false);+ }+ };+ read();+ const observer = new MutationObserver(read);+ observer.observe(root, { childList: true, subtree: true });+ const inEditor = (target: EventTarget | null) =>+ target instanceof Element && target.closest(INPUT_SELECTOR) !== null;+ const onFocusIn = (event: FocusEvent) => {+ if (inEditor(event.target)) setTyping(true);+ };+ const onFocusOut = (event: FocusEvent) => {+ if (inEditor(event.target)) setTyping(false);+ };+ root.addEventListener("focusin", onFocusIn);+ root.addEventListener("focusout", onFocusOut);+ return () => {+ observer.disconnect();+ clearTimeout(settle);+ root.removeEventListener("focusin", onFocusIn);+ root.removeEventListener("focusout", onFocusOut);+ };+ }, [root]);++ return { recording, working, typing };+}diff --git a/app/src/skins/openduet/places.ts b/app/src/skins/openduet/places.tsnew file mode 100644index 00000000..a8ca874e--- /dev/null+++ b/app/src/skins/openduet/places.ts@@ -0,0 +1,75 @@+import type { LinkOptions } from "@tanstack/react-router";++/*+ * The skin's own places: its tabs, the column each path gets, and its Tasks screen. Where else a+ * person can go is OpenBot's one navigation list (`lib/navigation.ts`), which the menu draws.+ */++/*+ * Where things are in OpenDuet's frame, as plain data, so the frame, the menu and the tests read+ * one list. Nothing here is a new route: every path is one OpenBot already serves, or the skin's own+ * screen at `/s/<key>`.+ */++/** The skin's own screen, served by OpenBot's `/s/$screen`. */+export const TASKS_SCREEN = "tasks";+export const TASKS_PATH = `/s/${TASKS_SCREEN}`;++export type OpenDuetTab = "chat" | "tasks";++/**+ * Which tab a path belongs to, or null for a page opened over the app.+ *+ * Chat is every conversation OpenBot draws: home, where a conversation starts, a conversation with+ * one Bot or several, and the default Bot's own screen. Tasks is the skin's screen. Everything else+ * (Bots, Connections, Skills, Routines and the rest) is a page with a back disc and no tab bar, as+ * OpenDuet opens them.+ */+export function tabForPath(pathname: string): OpenDuetTab | null {+ const path = pathname.replace(/\/+$/, "") || "/";+ if (path === "/" || path === "/bot") return "chat";+ if (/^\/(channel|group)\/[^/]+$/.test(path)) return "chat";+ if (path === TASKS_PATH) return "tasks";+ return null;+}++/**+ * Whether the screen under the frame is one of the skin's own, which scrolls under the floating+ * header and tab bar by itself. OpenBot's pages own their scrollers, so the frame keeps its chrome+ * clear of them instead.+ */+export function isSkinScreen(pathname: string): boolean {+ return pathname.startsWith("/s/");+}++/**+ * How wide the frame's column is. `phone` holds Chat and Tasks to a phone's width. `pane` is a+ * conversation with its Bot's details or computer open: the phone column plus OpenBot's 400px pane+ * beside it (`DetailPanel` lays the pane out beside the conversation once there is room for both).+ * `page` is every other page, at the width OpenBot gave it.+ */+export type OpenDuetColumn = "phone" | "pane" | "page";++export function columnFor(+ pathname: string,+ search: Record<string, unknown> = {},+): OpenDuetColumn {+ const tab = tabForPath(pathname);+ if (!tab) return "page";+ if (tab === "chat" && (search.watch === true || search.settings === true))+ return "pane";+ return "phone";+}++/** The Tasks tab, at the skin's own screen. */+export const TASKS_LINK = {+ to: "/s/$screen",+ params: { screen: TASKS_SCREEN },+} satisfies LinkOptions;++/** The conversation a roster row opens: a group has its own shared transcript. */+export function conversationPath(channel: { id: string; agentIds: string[] }) {+ return channel.agentIds.length > 1+ ? (`/group/${channel.id}` as const)+ : (`/channel/${channel.id}` as const);+}diff --git a/app/src/skins/openduet/skin.css b/app/src/skins/openduet/skin.cssnew file mode 100644index 00000000..333cfcfe--- /dev/null+++ b/app/src/skins/openduet/skin.css@@ -0,0 +1,321 @@+/*+ * OpenDuet: neutral greys with a cool bias, one violet accent used in a few fixed places, four+ * status colours for how work stands, frosted glass for the chrome that floats over a screen, and+ * Inter set with the single-storey a and flat-topped 3. The values are OpenDuet's own+ * (`openduet/openbot/app/src/styles.css`), so a screen drawn here reads as the same product.+ *+ * Light is `:root[data-skin="openduet"]` and dark is `:root[data-skin="openduet"].dark`, and every+ * token is set in both: the skin's selector outranks OpenBot's `.dark`, so a token set only for+ * light would leak into dark.+ */++:root[data-skin="openduet"] {+ color-scheme: light;++ /* OpenBot's shadcn tokens, so every OpenBot page drawn inside the frame wears OpenDuet. */+ --background: #f6f6f8;+ --foreground: #18181b;+ --card: #ffffff;+ --card-foreground: #18181b;+ --popover: #ffffff;+ --popover-foreground: #18181b;+ --primary: #111114;+ --primary-foreground: #ffffff;+ --secondary: #f1f1f4;+ --secondary-foreground: #18181b;+ --muted: #f1f1f4;+ --muted-foreground: #55555e;+ --accent: #f1f1f4;+ --accent-foreground: #18181b;+ --destructive: #b91c1c;+ --success: #147a3a;+ --border: rgb(24 24 27 / 9%);+ --input: rgb(24 24 27 / 12%);+ --ring: #6430ab;+ --radius: 0.875rem;+ --sidebar: #f6f6f8;+ --sidebar-foreground: #18181b;+ --sidebar-primary: #111114;+ --sidebar-primary-foreground: #ffffff;+ --sidebar-accent: #ececf0;+ --sidebar-accent-foreground: #18181b;+ --sidebar-border: rgb(24 24 27 / 9%);+ --sidebar-ring: #6430ab;++ /* OpenDuet's own roles. */+ --openduet-surface: #f6f6f8;+ --openduet-card: #ffffff;+ --openduet-bubble: #ececf0;+ --openduet-ink: #18181b;+ --openduet-ink-2: #55555e;+ --openduet-ink-3: #6b6b75;+ --openduet-hair: rgb(24 24 27 / 9%);+ --openduet-hair-2: rgb(24 24 27 / 6%);+ --openduet-tile: #f1f1f4;+ /* The one accent: the Tasks badge, the unread dot, the focus ring, the Chat row's glyph. */+ --openduet-accent: #6430ab;+ --openduet-accent-soft: #f0ebfa;+ --openduet-on-accent: #ffffff;+ /* How work stands: done, needs you, working, couldn't finish. Only on status. */+ --openduet-done: #147a3a;+ --openduet-done-soft: #e6f4ea;+ --openduet-needs: #a34a06;+ --openduet-needs-soft: #fdf3e1;+ --openduet-working: #1d4ed8;+ --openduet-working-soft: #eaf0fd;+ --openduet-problem: #b91c1c;+ --openduet-problem-soft: #fbeaea;+ /* The primary button: near-black on light, white on dark. */+ --openduet-black: #111114;+ --openduet-on-black: #ffffff;+ --openduet-shadow-float:+ 0 0 0 0.5px rgb(1 5 7 / 10%), 0 1px 1.5px rgb(1 5 7 / 6%),+ 0 4px 12px -4px rgb(1 5 7 / 12%);+ --openduet-shadow-card:+ 0 0 0 1px rgb(24 24 27 / 9%), 0 6px 18px -12px rgb(1 5 7 / 18%);+ --openduet-shadow-raised:+ 0 0 0 1px rgb(24 24 27 / 9%), 0 10px 26px -14px rgb(1 5 7 / 20%);+ /* Glass: frosted chrome over a scrolling screen, about 80% so text under it never competes. */+ --openduet-glass: rgb(255 255 255 / 80%);+ --openduet-veil: rgb(246 246 248 / 74%);+ --openduet-shadow-glass:+ inset 0 0.5px 0 rgb(255 255 255 / 80%), 0 0 0 0.5px rgb(1 5 7 / 10%),+ 0 1px 1.5px rgb(1 5 7 / 6%), 0 4px 12px -4px rgb(1 5 7 / 12%);+ /* The fade behind the floating header, from the surface to nothing. */+ --openduet-fade: linear-gradient(#f6f6f8 55%, rgb(246 246 248 / 0%));+}++:root[data-skin="openduet"].dark {+ color-scheme: dark;++ --background: #111113;+ --foreground: #f4f4f5;+ --card: #1c1c1f;+ --card-foreground: #f4f4f5;+ --popover: #1c1c1f;+ --popover-foreground: #f4f4f5;+ --primary: #f4f4f5;+ --primary-foreground: #111114;+ --secondary: #26262b;+ --secondary-foreground: #f4f4f5;+ --muted: #26262b;+ --muted-foreground: #a1a1aa;+ --accent: #26262b;+ --accent-foreground: #f4f4f5;+ --destructive: #f87171;+ --success: #4ade80;+ --border: rgb(255 255 255 / 10%);+ --input: rgb(255 255 255 / 14%);+ --ring: #b49ae8;+ --radius: 0.875rem;+ --sidebar: #111113;+ --sidebar-foreground: #f4f4f5;+ --sidebar-primary: #f4f4f5;+ --sidebar-primary-foreground: #111114;+ --sidebar-accent: #26262b;+ --sidebar-accent-foreground: #f4f4f5;+ --sidebar-border: rgb(255 255 255 / 10%);+ --sidebar-ring: #b49ae8;++ /* Near-black and neutral, as OpenDuet samples it; the primary action turns light. */+ --openduet-surface: #111113;+ --openduet-card: #1c1c1f;+ --openduet-bubble: #26262b;+ --openduet-ink: #f4f4f5;+ --openduet-ink-2: #a1a1aa;+ --openduet-ink-3: #8e8e98;+ --openduet-hair: rgb(255 255 255 / 10%);+ --openduet-hair-2: rgb(255 255 255 / 7%);+ --openduet-tile: #26262b;+ --openduet-accent: #b49ae8;+ --openduet-accent-soft: #2a2140;+ /* Dark text on the light lilac: white on it is 2.4:1. */+ --openduet-on-accent: #1a1033;+ --openduet-done: #4ade80;+ --openduet-done-soft: #14301f;+ --openduet-needs: #fbbf24;+ --openduet-needs-soft: #3a2a0c;+ --openduet-working: #7aa2ff;+ --openduet-working-soft: #18233d;+ --openduet-problem: #f87171;+ --openduet-problem-soft: #3a1717;+ --openduet-black: #f4f4f5;+ --openduet-on-black: #111114;+ --openduet-shadow-float:+ 0 0 0 0.5px rgb(255 255 255 / 10%), 0 4px 12px -4px rgb(0 0 0 / 50%);+ --openduet-shadow-card: 0 0 0 1px rgb(255 255 255 / 10%);+ --openduet-shadow-raised:+ 0 0 0 1px rgb(255 255 255 / 10%), 0 10px 26px -14px rgb(0 0 0 / 60%);+ --openduet-glass: rgb(28 28 31 / 82%);+ --openduet-veil: rgb(17 17 19 / 72%);+ --openduet-shadow-glass:+ inset 0 0.5px 0 rgb(255 255 255 / 8%), 0 0 0 0.5px rgb(255 255 255 / 10%),+ 0 4px 12px -4px rgb(0 0 0 / 50%);+ --openduet-fade: linear-gradient(#111113 55%, rgb(17 17 19 / 0%));+}++/*+ * The roles as Tailwind colours, so the skin's own components write `bg-openduet-card`. `inline`+ * emits no variables of its own: each utility reads the `--openduet-*` token above, which only+ * exists while this skin is active.+ */+@theme inline {+ --color-openduet-surface: var(--openduet-surface);+ --color-openduet-card: var(--openduet-card);+ --color-openduet-bubble: var(--openduet-bubble);+ --color-openduet-ink: var(--openduet-ink);+ --color-openduet-ink-2: var(--openduet-ink-2);+ --color-openduet-ink-3: var(--openduet-ink-3);+ --color-openduet-hair: var(--openduet-hair);+ --color-openduet-hair-2: var(--openduet-hair-2);+ --color-openduet-tile: var(--openduet-tile);+ --color-openduet-accent: var(--openduet-accent);+ --color-openduet-accent-soft: var(--openduet-accent-soft);+ --color-openduet-on-accent: var(--openduet-on-accent);+ --color-openduet-done: var(--openduet-done);+ --color-openduet-done-soft: var(--openduet-done-soft);+ --color-openduet-needs: var(--openduet-needs);+ --color-openduet-needs-soft: var(--openduet-needs-soft);+ --color-openduet-working: var(--openduet-working);+ --color-openduet-working-soft: var(--openduet-working-soft);+ --color-openduet-problem: var(--openduet-problem);+ --color-openduet-problem-soft: var(--openduet-problem-soft);+ --color-openduet-black: var(--openduet-black);+ --color-openduet-on-black: var(--openduet-on-black);+ --shadow-openduet-float: var(--openduet-shadow-float);+ --shadow-openduet-card: var(--openduet-shadow-card);+ --shadow-openduet-raised: var(--openduet-shadow-raised);+ --shadow-openduet-glass: var(--openduet-shadow-glass);+}++/* Inter as OpenDuet sets it: the single-storey a (cv11) and the flat-topped 3 (ss03). */+:root[data-skin="openduet"] body {+ font-feature-settings: "cv11", "ss03";+}++@layer utilities {+ /*+ * OpenDuet's five sizes, in rem so they follow the person's text size. Weights are not part of+ * a size: 600 for titles, 500 for rows, chips and buttons, 400 otherwise. In the utilities layer,+ * and scoped to the skin, so a size given to one of OpenBot's primitives outranks the primitive's+ * own `text-*`.+ */+ [data-skin="openduet"] .openduet-type-display {+ font-size: 1.5rem;+ line-height: 1.75rem;+ letter-spacing: -0.018em;+ }+ [data-skin="openduet"] .openduet-type-nav {+ font-size: 1.125rem;+ line-height: 1.375rem;+ letter-spacing: -0.011em;+ }+ [data-skin="openduet"] .openduet-type-body {+ font-size: 1.0625rem;+ line-height: 1.4375rem;+ letter-spacing: -0.011em;+ }+ [data-skin="openduet"] .openduet-type-sub {+ font-size: 0.9375rem;+ line-height: 1.25rem;+ letter-spacing: -0.006em;+ }+ [data-skin="openduet"] .openduet-type-caption {+ font-size: 0.8125rem;+ line-height: 1rem;+ letter-spacing: 0;+ }+}++@layer components {+ /*+ * Frosted chrome. The blur is what makes the translucency readable; a browser that cannot blur+ * gets the opaque card instead, never a see-through bar.+ */+ [data-skin="openduet"] .openduet-glass {+ background-color: var(--openduet-card);+ }+ [data-skin="openduet"] .openduet-veil {+ background-color: var(--openduet-surface);+ }+ @supports (backdrop-filter: blur(1px)) or+ (-webkit-backdrop-filter: blur(1px)) {+ [data-skin="openduet"] .openduet-glass {+ background-color: var(--openduet-glass);+ -webkit-backdrop-filter: blur(22px) saturate(180%);+ backdrop-filter: blur(22px) saturate(180%);+ }+ [data-skin="openduet"] .openduet-veil {+ background-color: var(--openduet-veil);+ -webkit-backdrop-filter: blur(28px) saturate(160%);+ backdrop-filter: blur(28px) saturate(160%);+ }+ }+}++/*+ * Inside the frame, OpenBot's own controls take OpenDuet's shape: buttons are pills, and every+ * control is at least 44px to tap, the smallest thing a finger can hit. The primitives mark+ * themselves with `data-slot`, so one rule covers every page without touching any of them. A link+ * drawn as a button sits inside a sentence and keeps its line height.+ */+[data-skin="openduet"] [data-openduet-frame] [data-slot="button"] {+ border-radius: 9999px;+}+[data-skin="openduet"]+ [data-openduet-page]+ [data-slot="button"]:not([data-variant="link"]) {+ min-height: 44px;+}+[data-skin="openduet"] [data-openduet-page] [data-slot="select-trigger"] {+ min-height: 44px;+}+[data-skin="openduet"] [data-openduet-page] [data-slot="input"] {+ min-height: 44px;+}+[data-skin="openduet"] [data-openduet-page] [data-slot="input-group"] {+ min-height: 44px;+}++/*+ * A conversation's composer floats inset from the column's edges, as OpenDuet's does, with its+ * focus ring off the screen's edge. OpenBot draws it in a column with no side padding.+ */+[data-skin="openduet"] [data-openduet-frame] [data-slot="composer-column"] {+ padding-inline: 12px;+}++/*+ * A page opened over the app names itself in the chrome's title pill, read from the page's own+ * title, which stays for screen readers only, as OpenDuet draws a page. The page then starts right+ * under the chrome, and its one action keeps its place on the right of the title's line.+ */+[data-skin="openduet"] [data-openduet-page] [data-slot="page-title"] {+ position: absolute;+ width: 1px;+ height: 1px;+ padding: 0;+ margin: -1px;+ overflow: hidden;+ clip: rect(0, 0, 0, 0);+ white-space: nowrap;+ border: 0;+}+[data-skin="openduet"] [data-openduet-page] [data-slot="page-header"] > div {+ justify-content: flex-end;+}+[data-skin="openduet"]+ [data-openduet-page]+ div:has(> [data-slot="page-header"]) {+ padding-top: 0.5rem;+}++/*+ * The bar a page draws above its scroller holds its own back link. The chrome's back disc goes+ * where that link goes (`header.tsx`), so the bar is not drawn twice.+ */+[data-skin="openduet"]+ [data-openduet-page]+ div:has(+ div > div > [data-slot="page-header"]) {+ display: none;+}diff --git a/app/src/skins/openduet/tab-bar.tsx b/app/src/skins/openduet/tab-bar.tsxnew file mode 100644index 00000000..a11f4cf0--- /dev/null+++ b/app/src/skins/openduet/tab-bar.tsx@@ -0,0 +1,97 @@+import { IconMessageCircle } from "@tabler/icons-react";+import { useQuery } from "@tanstack/react-query";+import { Link } from "@tanstack/react-router";+import { approvalInboxOptions } from "@/lib/approvals";+import { cn } from "@/lib/utils";+import { IconTasksList } from "./icons";+import { FOCUS } from "./kit";+import { type OpenDuetTab, TASKS_LINK } from "./places";+import { waitingCount } from "./tasks-model";++const TAB =+ "relative flex flex-1 flex-col items-center justify-center gap-px rounded-[27px] transition-colors motion-reduce:transition-none";++/**+ * The frosted pill at the foot of the app: Chat and Tasks, the current one on a grey capsule.+ * Tasks carries the number of things waiting on the person, counted the way its Needs input section+ * lists them, so the badge and the screen never disagree.+ */+export function TabBar({ current }: { current: OpenDuetTab }) {+ const inbox = useQuery(approvalInboxOptions());+ const waiting = waitingCount(inbox.data);+ const tabs = [+ { id: "chat" as const, label: "Chat", Glyph: IconMessageCircle, badge: 0 },+ {+ id: "tasks" as const,+ label: "Tasks",+ Glyph: IconTasksList,+ badge: waiting,+ },+ ];+ return (+ <nav+ aria-label="Main"+ className="openduet-glass absolute inset-x-0 bottom-[22px] z-20 mx-auto flex h-16 w-[236px] max-w-[calc(100%-32px)] gap-0.5 rounded-[32px] p-[5px] shadow-openduet-glass"+ >+ {tabs.map(({ id, label, Glyph, badge }) => {+ const on = id === current;+ const body = (+ <>+ <Glyph size={20} stroke={on ? 2.1 : 1.9} />+ <span+ className={cn(+ "openduet-type-caption",+ on ? "font-semibold" : "font-medium",+ )}+ >+ {label}+ </span>+ {badge ? (+ <span+ aria-hidden+ className={cn(+ "openduet-type-caption absolute top-1 left-1/2 ml-[7px] grid h-5 min-w-5 place-items-center rounded-full bg-openduet-accent px-1 font-semibold text-openduet-on-accent tabular-nums",+ on+ ? "shadow-[0_0_0_2px_var(--openduet-tile)]"+ : "shadow-[0_0_0_2px_var(--openduet-card)]",+ )}+ >+ {badge}+ </span>+ ) : null}+ </>+ );+ const className = cn(+ TAB,+ FOCUS,+ on+ ? "bg-openduet-tile text-openduet-ink"+ : "text-openduet-ink-2 hover:text-openduet-ink",+ );+ const name = badge ? `${label}, ${badge} waiting` : label;+ return id === "chat" ? (+ <Link+ activeOptions={{ exact: true }}+ aria-current={on ? "page" : undefined}+ aria-label={name}+ className={className}+ key={id}+ to="/"+ >+ {body}+ </Link>+ ) : (+ <Link+ {...TASKS_LINK}+ aria-current={on ? "page" : undefined}+ aria-label={name}+ className={className}+ key={id}+ >+ {body}+ </Link>+ );+ })}+ </nav>+ );+}diff --git a/app/src/skins/openduet/tasks-model.ts b/app/src/skins/openduet/tasks-model.tsnew file mode 100644index 00000000..71c8d004--- /dev/null+++ b/app/src/skins/openduet/tasks-model.ts@@ -0,0 +1,15 @@+import type { ApprovalInboxData } from "@/lib/approvals";++/**+ * How many things wait on the person, for the Tasks tab's badge and the Needs input heading: the+ * pending approvals and the questions OpenBot's `WaitingForYou` lists, counted the way it filters+ * them, so the badge and the rows never disagree. `tests/skins-openduet-model.test.ts` renders+ * `WaitingForYou` and holds the two to the same number.+ */+export function waitingCount(inbox: ApprovalInboxData | undefined): number {+ if (!inbox) return 0;+ const pending = inbox.requests.filter(+ (request) => request.status === "pending",+ ).length;+ return pending + inbox.questions.length;+}diff --git a/app/src/skins/openduet/tasks-screen.tsx b/app/src/skins/openduet/tasks-screen.tsxnew file mode 100644index 00000000..a1e80fc6--- /dev/null+++ b/app/src/skins/openduet/tasks-screen.tsx@@ -0,0 +1,183 @@+import { useQuery } from "@tanstack/react-query";+import { type ReactNode, useState } from "react";+import { WaitingForYou } from "@/components/approvals/waiting";+import { BotResponsibilities } from "@/components/responsibilities/responsibilities";+import { RoutinesList } from "@/components/routines/routines-list";+import { SuggestionsInbox } from "@/components/suggestions/proactive-panel";+import { approvalInboxOptions } from "@/lib/approvals";+import { routinesQueryOptions } from "@/lib/routines/queries";+import { cn } from "@/lib/utils";+import { FOCUS } from "./kit";+import { waitingCount } from "./tasks-model";++/** Which list Tasks shows: what waits on you and what your Bots carry, or what to start next. */+export type TasksView = "active" | "up_next";++/** Which list was open last, kept in this browser between visits. */+export const TASKS_VIEW_STORAGE_KEY = "openduet.tasks-view";++function rememberedView(): TasksView {+ try {+ return window.localStorage.getItem(TASKS_VIEW_STORAGE_KEY) === "up_next"+ ? "up_next"+ : "active";+ } catch {+ return "active";+ }+}++function rememberView(view: TasksView) {+ try {+ window.localStorage.setItem(TASKS_VIEW_STORAGE_KEY, view);+ } catch {+ // Storage can be refused. The list still switches; it opens on Active next time.+ }+}++/**+ * OpenDuet's Tasks: its two big words, Active and Up next, over OpenBot's own screens.+ *+ * Every list here is OpenBot's component, unchanged: `WaitingForYou` for approvals and questions,+ * `BotResponsibilities` for responsibilities, `RoutinesList` for routines and `SuggestionsInbox`+ * for suggested next steps. So every choice, field and confirmation OpenBot offers is here, and a+ * new one arrives without this screen changing. The skin adds only the switch, the headings and+ * the layout around them.+ */+export function TasksScreen() {+ const [view, setView] = useState<TasksView>(rememberedView);+ const show = (next: TasksView) => {+ setView(next);+ rememberView(next);+ };++ return (+ <div className="relative flex min-h-0 flex-1 flex-col">+ <div className="min-h-0 flex-1 overflow-y-auto px-4 pt-[100px] pb-[calc(var(--openduet-tab-space,86px)+32px)]">+ <TasksSwitch onView={show} view={view} />+ <div+ aria-labelledby={`openduet-tasks-tab-${view}`}+ id="openduet-tasks-panel"+ role="tabpanel"+ >+ {view === "active" ? <ActiveView /> : <SuggestionsInbox />}+ </div>+ </div>+ </div>+ );+}++/**+ * Active and Up next as two large words, the one showing in ink and the other grey. It sticks+ * under the header while the list scrolls, solid up to the discs and fading under.+ */+function TasksSwitch({+ view,+ onView,+}: {+ view: TasksView;+ onView: (view: TasksView) => void;+}) {+ return (+ <div+ className={cn(+ "sticky top-[-20px] z-30 -mx-4 mb-3 bg-openduet-surface px-5 pt-1 pb-2",+ "before:pointer-events-none before:absolute before:inset-x-0 before:bottom-full before:h-[14px] before:bg-openduet-surface before:content-['']",+ "after:pointer-events-none after:absolute after:inset-x-0 after:top-full after:h-4 after:bg-[linear-gradient(var(--openduet-surface),transparent)] after:content-['']",+ )}+ >+ <div+ aria-label="Tasks"+ className="flex min-h-11 min-w-0 flex-wrap items-center gap-x-4"+ role="tablist"+ >+ <SwitchTab id="active" onView={onView} view={view}>+ Active+ </SwitchTab>+ <SwitchTab id="up_next" onView={onView} view={view}>+ Up next+ </SwitchTab>+ </div>+ </div>+ );+}++function SwitchTab({+ id,+ view,+ onView,+ children,+}: {+ id: TasksView;+ view: TasksView;+ onView: (view: TasksView) => void;+ children: ReactNode;+}) {+ const on = id === view;+ return (+ <button+ aria-controls="openduet-tasks-panel"+ aria-selected={on}+ className={cn(+ "openduet-type-display rounded-lg font-semibold transition-colors motion-reduce:transition-none",+ FOCUS,+ on+ ? "text-openduet-ink"+ : "text-openduet-ink-3 hover:text-openduet-ink-2",+ )}+ id={`openduet-tasks-tab-${id}`}+ onClick={() => onView(id)}+ role="tab"+ type="button"+ >+ {children}+ </button>+ );+}++/**+ * Active: what waits on the person, decided in OpenBot's own rows, then the responsibilities and+ * routines their Bots carry, in OpenBot's own lists. Needs input is left out when nothing waits.+ */+function ActiveView() {+ const inbox = useQuery(approvalInboxOptions());+ const routines = useQuery(routinesQueryOptions());+ const waiting = waitingCount(inbox.data);++ return (+ <div className="flex flex-col gap-9">+ {waiting > 0 ? (+ <Section count={waiting} label="Needs input">+ <WaitingForYou />+ </Section>+ ) : null}+ <BotResponsibilities />+ <Section count={routines.data?.routines.length} label="Routines">+ <RoutinesList embedded />+ </Section>+ </div>+ );+}++/** A section heading in OpenDuet's grey, with how many, over an OpenBot list. */+function Section({+ label,+ count,+ children,+}: {+ label: string;+ /** Left off until the list has loaded, so the heading never states a wrong number. */+ count: number | undefined;+ children: ReactNode;+}) {+ return (+ <section aria-label={label} className="flex flex-col">+ <h2 className="openduet-type-body flex min-h-11 items-center px-1 font-normal text-openduet-ink-2">+ {label}+ {count === undefined ? null : (+ <span className="ml-1.5 tabular-nums">{count}</span>+ )}+ </h2>+ {children}+ </section>+ );+}diff --git a/app/src/skins/openmuse/bots-sheet.tsx b/app/src/skins/openmuse/bots-sheet.tsxnew file mode 100644index 00000000..2afc3564--- /dev/null+++ b/app/src/skins/openmuse/bots-sheet.tsx@@ -0,0 +1,150 @@+import {+ IconBolt,+ IconCheck,+ IconPlus,+ IconUserCircle,+} from "@tabler/icons-react";+import { useInfiniteQuery, useQuery } from "@tanstack/react-query";+import { Link, useNavigate, useRouterState } from "@tanstack/react-router";+import { AbstractAvatar } from "@/components/agents/abstract-avatar";+import {+ attentionSummary,+ needsInput,+} from "@/components/bot-profile/attention";+import { Item, ItemContent, ItemTitle } from "@/components/ui/item";+import { agentListQueryOptions } from "@/lib/agents/queries";+import { botAttentionQueryOptions } from "@/lib/bot-lifecycle/queries";+import { channelListQueryOptions } from "@/lib/channels/queries";+import { appConfig } from "@/lib/generated/application-config";+import { cn } from "@/lib/utils";+import { chooseBot } from "./chosen-bot";+import { useMuse } from "./context";+import { mainChannel, tabFor } from "./model";+import { Divider, ErrorNotice, LinkRow, MuseSheet, museText } from "./ui";++/**+ * Who sits at the centre of the frame. This look has one agent; OpenBot has a roster, so this is the+ * one place the difference shows, and it stays a sheet behind the name rather than a fixture.+ */+export function BotsSheet({ onClose }: { onClose: () => void }) {+ const { bot: centre, userId } = useMuse();+ const agents = useQuery(agentListQueryOptions());+ const attention = useQuery(botAttentionQueryOptions());+ const channels = useInfiniteQuery(channelListQueryOptions());+ const pathname = useRouterState({+ select: (state) => state.location.pathname,+ });+ const navigate = useNavigate();++ const choose = (agentId: string) => {+ if (userId) chooseBot(userId, agentId);+ onClose();+ // On Chat, choosing a Bot means talking to it; elsewhere the tab stays and follows the Bot.+ if (tabFor(pathname) !== "chat") return;+ const main = mainChannel(agentId, channels.data);+ void (main+ ? navigate({ to: "/channel/$channelId", params: { channelId: main.id } })+ : navigate({ to: "/channel/new", search: { agent: agentId } }));+ };++ return (+ <MuseSheet+ onClose={onClose}+ subtitle={`Choose who is at the centre of ${appConfig.brand.productName}.`}+ title="Your Bots"+ >+ <div className="flex flex-col gap-3.5">+ {agents.isPending ? null : agents.error ? (+ <ErrorNotice error="Couldn't load your Bots. Reload the page." />+ ) : agents.data.length === 0 ? (+ <p className={museText.muted}>You don't have a Bot yet.</p>+ ) : (+ <div className="flex flex-col">+ {agents.data.map((agent) => {+ const waiting = attention.data?.find(+ (entry) => entry.agentId === agent.id,+ );+ const asks = waiting ? needsInput(waiting) : 0;+ const summary = waiting ? attentionSummary(waiting) : "";+ const selected = agent.id === centre?.id;+ return (+ <Item+ aria-pressed={selected}+ className={cn(+ "flex-nowrap gap-3.5 rounded-[18px] border-0 px-2 py-2 text-left hover:bg-[var(--openmuse-pressed)]",+ selected &&+ "bg-[var(--openmuse-sky)] hover:bg-[var(--openmuse-sky)]",+ )}+ key={agent.id}+ render={+ <button onClick={() => choose(agent.id)} type="button" />+ }+ >+ <AbstractAvatar+ name={agent.name}+ seed={agent.avatarSeed}+ size={44}+ />+ <ItemContent className="min-w-0 gap-0.5">+ <ItemTitle className={cn(museText.body, "font-medium")}>+ {agent.name}+ </ItemTitle>+ <span className={cn(museText.small, "line-clamp-1")}>+ {asks+ ? `Needs you · ${summary}`+ : summary || agent.title || agent.roleDescription}+ </span>+ </ItemContent>+ {selected ? (+ <IconCheck+ aria-hidden="true"+ className="size-[18px] shrink-0 text-[var(--openmuse-accent)]"+ />+ ) : summary ? (+ <span+ aria-hidden="true"+ className="size-2 shrink-0 rounded-full bg-[var(--openmuse-accent)]"+ />+ ) : null}+ </Item>+ );+ })}+ </div>+ )}+ <Divider className="my-1" />+ <div>+ {centre ? (+ <LinkRow+ detail="Setup, access, sharing and activity"+ icon={IconUserCircle}+ render={+ <Link+ onClick={onClose}+ params={{ agentId: centre.id }}+ to="/bots/$agentId"+ />+ }+ title={`${centre.name}'s page`}+ />+ ) : null}+ <LinkRow+ detail="Yours, shared with you, and your team's"+ icon={IconBolt}+ render={<Link onClick={onClose} to="/bots" />}+ tint="plain"+ title="All Bots"+ />+ <LinkRow+ detail="Describe what it should do"+ icon={IconPlus}+ render={+ <Link onClick={onClose} search={{ new: true }} to="/bots" />+ }+ tint="plain"+ title="New Bot"+ />+ </div>+ </div>+ </MuseSheet>+ );+}diff --git a/app/src/skins/openmuse/chosen-bot.ts b/app/src/skins/openmuse/chosen-bot.tsnew file mode 100644index 00000000..8ae26c4e--- /dev/null+++ b/app/src/skins/openmuse/chosen-bot.ts@@ -0,0 +1,57 @@+import { useSyncExternalStore } from "react";++/*+ * Which Bot each person put at the centre of the frame. Kept in this browser, and kept per signed-in+ * person: the key carries their user id, so the next person on a shared machine starts from OpenBot's+ * own default Bot rather than the last person's choice. Choosing a Bot changes nothing on the server.+ */+export function chosenBotKey(userId: string): string {+ return `openmuse-bot:${userId}`;+}++const choices = new Map<string, string | null>();+const listeners = new Set<() => void>();++function read(userId: string): string | null {+ if (!choices.has(userId)) {+ let stored: string | null = null;+ // localStorage throws in some privacy modes; the frame then starts from the default Bot.+ try {+ stored = window.localStorage.getItem(chosenBotKey(userId));+ } catch {}+ choices.set(userId, stored);+ }+ return choices.get(userId) ?? null;+}++export function chooseBot(userId: string, agentId: string) {+ if (read(userId) === agentId) return;+ choices.set(userId, agentId);+ // The choice still holds for this visit when the browser refuses to store it.+ try {+ window.localStorage.setItem(chosenBotKey(userId), agentId);+ } catch {}+ for (const listener of listeners) listener();+}++/** Forgets every choice read into memory, as a new page load would. */+export function forgetChosenBots() {+ choices.clear();+ for (const listener of listeners) listener();+}++function subscribe(listener: () => void) {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+}++/** The Bot this person chose, or null before they choose one or while nobody is known yet. */+export function useChosenBotId(userId: string | undefined): string | null {+ return useSyncExternalStore(+ subscribe,+ () => (userId ? read(userId) : null),+ () => null,+ );+}diff --git a/app/src/skins/openmuse/context.ts b/app/src/skins/openmuse/context.tsnew file mode 100644index 00000000..4a365771--- /dev/null+++ b/app/src/skins/openmuse/context.ts@@ -0,0 +1,21 @@+import { createContext, useContext } from "react";+import type { AgentProfile } from "@/lib/agents/queries";++export type MuseSheetKind = "menu" | "notifications" | "bots";++export type MuseContextValue = {+ /** The Bot at the centre of the frame, or undefined while the roster loads or when there is none. */+ bot: AgentProfile | undefined;+ /** The signed-in person, whose choice of centre Bot this browser remembers. */+ userId: string | undefined;+ openSheet: (sheet: MuseSheetKind) => void;+};++export const MuseContext = createContext<MuseContextValue | null>(null);++export function useMuse(): MuseContextValue {+ const context = useContext(MuseContext);+ if (!context)+ throw new Error("useMuse must be used inside the skin's frame.");+ return context;+}diff --git a/app/src/skins/openmuse/frame.tsx b/app/src/skins/openmuse/frame.tsxnew file mode 100644index 00000000..5108ce9f--- /dev/null+++ b/app/src/skins/openmuse/frame.tsx@@ -0,0 +1,300 @@+import {+ IconBell,+ IconBulb,+ IconChevronDown,+ IconMenu2,+ IconMessageCircle,+ IconSquareCheck,+ IconTable,+ IconTriangleSquareCircle,+} from "@tabler/icons-react";+import { useInfiniteQuery, useQuery } from "@tanstack/react-query";+import { Link, useParams, useRouterState } from "@tanstack/react-router";+import { type ReactNode, useEffect, useState } from "react";+import { AbstractAvatar } from "@/components/agents/abstract-avatar";+import AgentOrb from "@/components/agents/orb/agent-orb";+import { BotsNavBadge } from "@/components/bot-profile/attention";+import { SelfHostBanner } from "@/components/layout/self-host-banner";+import { agentListQueryOptions } from "@/lib/agents/queries";+import { approvalInboxOptions } from "@/lib/approvals";+import { currentUserQueryOptions } from "@/lib/auth/queries";+import { botAttentionQueryOptions } from "@/lib/bot-lifecycle/queries";+import {+ channelListQueryOptions,+ channelQueryOptions,+} from "@/lib/channels/queries";+import { useChannelEvents } from "@/lib/channels/use-channel-events";+import { appConfig } from "@/lib/generated/application-config";+import { cn } from "@/lib/utils";+import { BotsSheet } from "./bots-sheet";+import { chooseBot, useChosenBotId } from "./chosen-bot";+import { MuseContext, type MuseSheetKind } from "./context";+import { MainChatLink } from "./links";+import { MenuSheet } from "./menu-sheet";+import {+ centreBot,+ inColumn,+ type MuseTab,+ statusLine,+ tabFor,+ waitingOnYou,+} from "./model";+import { NotificationsSheet } from "./notifications-sheet";+import { type MuseIcon, RoundButton } from "./ui";++/** The deployment's own name, from its brand.yaml: the name OpenBot's sidebar shows. */+const PRODUCT = appConfig.brand.productName;++const TABS: { id: MuseTab; label: string; icon: MuseIcon }[] = [+ { id: "chat", label: "Chat", icon: IconMessageCircle },+ { id: "activity", label: "Activity", icon: IconTable },+ { id: "ideas", label: "Ideas", icon: IconBulb },+ { id: "goals", label: "Goals", icon: IconSquareCheck },+ { id: "apps", label: "Apps", icon: IconTriangleSquareCircle },+];++/**+ * OpenMuse's shell around every OpenBot page: one centred column, the agent at the top, a bell for+ * what waits on you, and a floating pill of five tabs. The page itself is OpenBot's, untouched —+ * conversations are OpenBot's own chat routes, rendered as `children`.+ */+export function OpenMuseFrame({ children }: { children: ReactNode }) {+ // The roster's socket. OpenBot opens it in its sidebar, which this frame replaces.+ useChannelEvents();+ const pathname = useRouterState({+ select: (state) => state.location.pathname,+ });+ const search = useRouterState({+ select: (state) =>+ state.location.search as {+ agent?: unknown;+ watch?: unknown;+ settings?: unknown;+ },+ });+ const addressed = search.agent;+ const params = useParams({ strict: false }) as {+ channelId?: string;+ agentId?: string;+ };+ const agents = useQuery(agentListQueryOptions());+ const channels = useInfiniteQuery(channelListQueryOptions());+ const conversation = useQuery({+ ...channelQueryOptions(params.channelId ?? ""),+ enabled: Boolean(params.channelId),+ });+ const attention = useQuery(botAttentionQueryOptions());+ const inbox = useQuery(approvalInboxOptions());+ const user = useQuery(currentUserQueryOptions());+ const userId = user.data?.id;+ const chosenId = useChosenBotId(userId);+ const [sheet, setSheet] = useState<MuseSheetKind | null>(null);++ /*+ * The Bot this screen is about, when it is about one: the Bot of a one-to-one conversation, the Bot+ * a new conversation is addressed to, or the Bot whose own page is open.+ */+ const onScreenBot =+ conversation.data && conversation.data.agentIds.length === 1+ ? conversation.data.agentIds[0]+ : pathname === "/channel/new" && typeof addressed === "string"+ ? addressed+ : params.agentId;+ const bot = centreBot(agents.data, chosenId, onScreenBot);++ // Talking to a Bot puts it at the centre, and it stays there after the conversation closes.+ useEffect(() => {+ if (+ userId &&+ onScreenBot &&+ agents.data?.some((agent) => agent.id === onScreenBot)+ ) {+ chooseBot(userId, onScreenBot);+ }+ }, [userId, onScreenBot, agents.data]);++ // A sheet belongs to the screen it was opened on.+ // biome-ignore lint/correctness/useExhaustiveDependencies: closes on navigation, by design.+ useEffect(() => {+ setSheet(null);+ }, [pathname]);++ const tab = tabFor(pathname);+ // A conversation's computer or Bot settings, open beside the transcript.+ const sidePanelOpen = search.watch === true || search.settings === true;+ const column = inColumn(pathname, sidePanelOpen);+ const waiting = waitingOnYou(inbox.data).count;+ const status = statusLine({+ attention: attention.data?.find((entry) => entry.agentId === bot?.id),+ channels: channels.data,+ agentId: bot?.id,+ });++ return (+ <MuseContext.Provider value={{ bot, userId, openSheet: setSheet }}>+ <div+ className="openmuse-frame flex h-svh flex-col overflow-hidden bg-background text-foreground"+ data-openmuse-tab={tab ?? "none"}+ >+ <SelfHostBanner />+ <div className="mx-auto w-full max-w-[760px] shrink-0">+ <header className="relative mx-5 h-[122px] shrink-0 pt-0.5 min-[900px]:h-[146px] min-[900px]:pt-3.5">+ <div className="absolute top-4 left-0">+ <RoundButton+ icon={IconMenu2}+ label="Open conversations and menu"+ onClick={() => setSheet("menu")}+ >+ {/* OpenBot's own "a Bot needs you" mark, worn as OpenMuse's dot. */}+ <span className="openmuse-menu-badge">+ <BotsNavBadge />+ </span>+ </RoundButton>+ </div>+ <div className="pointer-events-none flex flex-col items-center">+ <button+ aria-label={+ bot ? `${bot.name}, ${status}. Switch Bot` : "Choose a Bot"+ }+ className="group pointer-events-auto flex max-w-[70%] flex-col items-center gap-px rounded-2xl outline-none transition-opacity active:opacity-65 focus-visible:ring-3 focus-visible:ring-ring/50 motion-reduce:transition-none"+ onClick={() => setSheet("bots")}+ type="button"+ >+ {/*+ * The Bot's own OpenBot avatar, the one its page and the Bots roster draw. With no Bot+ * yet, the deployment's own mark stands in.+ */}+ <span className="mt-1 mb-1 flex size-11 items-center justify-center min-[900px]:size-[52px] [&>[role=img]]:size-full! [&_svg]:size-full">+ {bot ? (+ <AbstractAvatar+ name={bot.name}+ seed={bot.avatarSeed}+ size={52}+ />+ ) : (+ <AgentOrb size="100%" />+ )}+ </span>+ <span className="flex max-w-full items-center gap-1 font-semibold text-[16px] text-foreground tracking-[-0.4px]">+ <span className="truncate">{bot?.name ?? PRODUCT}</span>+ <IconChevronDown+ aria-hidden="true"+ className="size-3 shrink-0 text-muted-foreground opacity-60 transition-opacity group-hover:opacity-100 motion-reduce:transition-none"+ stroke={2.2}+ />+ </span>+ <span+ className="mb-1.5 max-w-full truncate text-[11px] text-muted-foreground"+ data-testid="openmuse-status"+ >+ {bot ? status : agents.isPending ? "" : "No Bots yet"}+ </span>+ </button>+ </div>+ <div className="absolute top-4 right-0">+ <RoundButton+ icon={IconBell}+ label={`Needs you, ${waiting} waiting`}+ onClick={() => setSheet("notifications")}+ >+ {waiting > 0 ? (+ <span+ aria-hidden="true"+ className="pointer-events-none absolute top-[7px] right-[9px] size-1.5 rounded-full bg-[var(--openmuse-accent)]"+ />+ ) : null}+ </RoundButton>+ </div>+ </header>+ </div>+ {/*+ * A tab's own screen sits in OpenMuse's 760px column. Any other OpenBot page, and a conversation+ * with its side panel open, takes OpenBot's own width on a wide screen; the bars stay centred.+ */}+ <main+ className={cn(+ "openmuse-stage mx-auto flex min-h-0 w-full max-w-[760px] flex-1 flex-col overflow-hidden",+ !column && "min-[1100px]:max-w-none",+ )}+ data-openmuse-width={column ? "column" : "page"}+ >+ {children}+ </main>+ <div className="mx-auto w-full max-w-[760px] shrink-0">+ <nav+ aria-label={PRODUCT}+ className="flex shrink-0 justify-center px-[22px] pt-2.5 pb-[max(7px,env(safe-area-inset-bottom))] min-[900px]:pb-[22px]"+ >+ <div className="flex w-full max-w-[370px] rounded-[40px] border border-[var(--openmuse-pill-border)] bg-[var(--openmuse-pill)] p-[5px] shadow-[0_2px_18px_0_var(--openmuse-pill-shadow)]">+ {TABS.map((item) => {+ const active = item.id === tab;+ const className = cn(+ "flex h-[47px] flex-1 items-center justify-center rounded-[28px] text-foreground outline-none transition-colors focus-visible:ring-3 focus-visible:ring-ring/50 motion-reduce:transition-none",+ active+ ? "bg-[var(--openmuse-tab-active)]"+ : "hover:bg-[var(--openmuse-tab-hover)]",+ );+ return item.id === "chat" ? (+ <MainChatLink+ agentId={bot?.id}+ aria-current={active ? "page" : undefined}+ aria-label={item.label}+ className={className}+ key={item.id}+ >+ <item.icon className="size-[23px]" stroke={1.8} />+ </MainChatLink>+ ) : (+ <TabLink+ active={active}+ className={className}+ key={item.id}+ label={item.label}+ tab={item.id}+ >+ <item.icon className="size-[23px]" stroke={1.8} />+ </TabLink>+ );+ })}+ </div>+ </nav>+ </div>+ </div>+ {sheet === "menu" ? <MenuSheet onClose={() => setSheet(null)} /> : null}+ {sheet === "notifications" ? (+ <NotificationsSheet onClose={() => setSheet(null)} />+ ) : null}+ {sheet === "bots" ? <BotsSheet onClose={() => setSheet(null)} /> : null}+ </MuseContext.Provider>+ );+}++/** Activity, Ideas and Goals are this skin's own screens; Apps is OpenBot's Connections. */+function TabLink({+ tab,+ label,+ active,+ className,+ children,+}: {+ tab: Exclude<MuseTab, "chat">;+ label: string;+ active: boolean;+ className: string;+ children: ReactNode;+}) {+ const shared = {+ "aria-current": active ? ("page" as const) : undefined,+ "aria-label": label,+ className,+ };+ return tab === "apps" ? (+ <Link {...shared} to="/connections">+ {children}+ </Link>+ ) : (+ <Link {...shared} params={{ screen: tab }} to="/s/$screen">+ {children}+ </Link>+ );+}diff --git a/app/src/skins/openmuse/index.ts b/app/src/skins/openmuse/index.tsnew file mode 100644index 00000000..68e170c5--- /dev/null+++ b/app/src/skins/openmuse/index.ts@@ -0,0 +1,24 @@+import type { Skin } from "../types";+import { OpenMuseFrame } from "./frame";+import { ActivityScreen } from "./screens/activity";+import { GoalsScreen } from "./screens/goals";+import { IdeasScreen } from "./screens/ideas";++/**+ * OpenMuse's look: one Bot at the centre of a single phone-shaped column and five tabs in a floating+ * pill. Its identity is the deployment's: the brand.yaml name and each Bot's own OpenBot avatar.+ * Chat is OpenBot's own conversation, and Apps is OpenBot's own Connections page. Activity, Ideas+ * and Goals put OpenBot's own sections for the centre Bot under OpenMuse's titles.+ */+export const openmuse: Skin = {+ id: "openmuse",+ name: "OpenMuse",+ description:+ "One Bot at the centre of a phone-shaped column, with five tabs.",+ Frame: OpenMuseFrame,+ screens: {+ activity: ActivityScreen,+ ideas: IdeasScreen,+ goals: GoalsScreen,+ },+};diff --git a/app/src/skins/openmuse/links.tsx b/app/src/skins/openmuse/links.tsxnew file mode 100644index 00000000..71e7807a--- /dev/null+++ b/app/src/skins/openmuse/links.tsx@@ -0,0 +1,49 @@+import { useInfiniteQuery } from "@tanstack/react-query";+import { Link } from "@tanstack/react-router";+import type * as React from "react";+import { channelListQueryOptions } from "@/lib/channels/queries";+import { mainChannel } from "./model";++type AnchorProps = Omit<React.ComponentProps<"a">, "href">;++/**+ * A link to a Bot's main chat: its one-to-one conversation when it has one, otherwise a new+ * conversation already addressed to it. Both are OpenBot's own chat routes.+ */+export function MainChatLink({+ agentId,+ ...props+}: AnchorProps & { agentId: string | undefined }) {+ const channels = useInfiniteQuery(channelListQueryOptions());+ const main = mainChannel(agentId, channels.data);+ if (main) {+ return (+ <Link+ {...props}+ params={{ channelId: main.id }}+ to="/channel/$channelId"+ />+ );+ }+ return (+ <Link+ {...props}+ search={agentId ? { agent: agentId } : {}}+ to="/channel/new"+ />+ );+}++/** A new conversation with this Bot: OpenMuse's "new side chat". */+export function NewChatLink({+ agentId,+ ...props+}: AnchorProps & { agentId: string | undefined }) {+ return (+ <Link+ {...props}+ search={agentId ? { agent: agentId } : {}}+ to="/channel/new"+ />+ );+}diff --git a/app/src/skins/openmuse/menu-sheet.tsx b/app/src/skins/openmuse/menu-sheet.tsxnew file mode 100644index 00000000..9f8b767a--- /dev/null+++ b/app/src/skins/openmuse/menu-sheet.tsx@@ -0,0 +1,294 @@+import {+ IconHome,+ IconLogout,+ IconMessageCircle,+ IconPin,+ IconPinFilled,+ IconPinnedOff,+ IconPlus,+ IconSearch,+ IconTrash,+ IconUsersGroup,+} from "@tabler/icons-react";+import { useInfiniteQuery, useMutation, useQuery } from "@tanstack/react-query";+import { Link, useNavigate, useParams } from "@tanstack/react-router";+import { useRef, useState } from "react";+import {+ isUnread,+ matchingChannels,+ pinnedFirst,+} from "@/components/app-sidebar/app-sidebar";+import { ChannelPagination } from "@/components/app-sidebar/channel-pagination";+import { ChannelAvatar } from "@/components/channels/avatar";+import { DeleteConversationDialog } from "@/components/channels/delete-conversation-dialog";+import { Item, ItemContent, ItemTitle } from "@/components/ui/item";+import { agentListQueryOptions } from "@/lib/agents/queries";+import { signOutMutationOptions } from "@/lib/auth/mutations";+import { currentUserQueryOptions } from "@/lib/auth/queries";+import { setChannelPinnedMutationOptions } from "@/lib/channels/mutations";+import {+ type ChannelSummary,+ channelListQueryOptions,+} from "@/lib/channels/queries";+import { appConfig } from "@/lib/generated/application-config";+import { useNavigationItems } from "@/lib/navigation";+import { relativeTime } from "@/lib/relative-time";+import { cn } from "@/lib/utils";+import { queryClient } from "@/query-client";+import { useMuse } from "./context";+import { MainChatLink, NewChatLink } from "./links";+import {+ Divider,+ ErrorNotice,+ LinkRow,+ MuseButton,+ MuseLinkButton,+ MuseSheet,+ museText,+} from "./ui";++/**+ * OpenMuse's menu: the main chat, a new chat, every conversation OpenBot keeps, and a way to every+ * other OpenBot surface. Nothing here is OpenMuse's own data; each row opens an OpenBot route.+ */+export function MenuSheet({ onClose }: { onClose: () => void }) {+ const { bot } = useMuse();+ const user = useQuery(currentUserQueryOptions());+ const channels = useInfiniteQuery(channelListQueryOptions());+ const navigate = useNavigate();+ const signOut = useMutation(signOutMutationOptions(queryClient));+ const navigation = useNavigationItems();+ const [search, setSearch] = useState("");+ const body = useRef<HTMLDivElement>(null);+ const searching = search.trim().length > 0;+ const shown = pinnedFirst(matchingChannels(channels.data, search));+ const botName = bot?.name ?? "your Bot";++ return (+ <MuseSheet+ bodyRef={body}+ onClose={onClose}+ subtitle={user.data?.name || user.data?.email}+ title={appConfig.brand.productName}+ >+ <div className="flex flex-col gap-3.5">+ <LinkRow+ detail={`Your ongoing conversation with ${botName}`}+ icon={IconMessageCircle}+ render={<MainChatLink agentId={bot?.id} onClick={onClose} />}+ title="Main chat"+ />+ <MuseLinkButton+ icon={IconPlus}+ primary+ render={<NewChatLink agentId={bot?.id} onClick={onClose} />}+ >+ New chat+ </MuseLinkButton>+ <div className="mt-3 flex items-center justify-between">+ <h2 className={museText.heading}>Conversations</h2>+ <MuseLinkButton+ icon={IconUsersGroup}+ render={<Link onClick={onClose} to="/channel/new" />}+ small+ >+ New group+ </MuseLinkButton>+ </div>+ <label className="relative block">+ <IconSearch+ aria-hidden="true"+ className="-translate-y-1/2 pointer-events-none absolute top-1/2 left-4 size-4 text-muted-foreground"+ />+ <input+ aria-label="Search conversations"+ className="min-h-[45px] w-full rounded-[19px] border border-border bg-card py-3 pr-4 pl-10 text-[16px] text-foreground outline-none placeholder:text-muted-foreground focus-visible:border-[var(--openmuse-focus)]"+ onChange={(event) => setSearch(event.target.value)}+ placeholder="Search conversations"+ value={search}+ />+ </label>+ {channels.isPending ? null : channels.error ? (+ <ErrorNotice error="Couldn't load your conversations." />+ ) : shown.length === 0 ? (+ <p className={museText.muted}>+ {searching+ ? `No conversation has “${search.trim()}” in its name or latest message.`+ : `Start a conversation with ${botName} and it shows up here.`}+ </p>+ ) : (+ <div>+ {shown.map((channel) => (+ <ConversationRow+ channel={channel}+ key={channel.id}+ onOpen={onClose}+ />+ ))}+ </div>+ )}+ <ChannelPagination+ query={channels}+ scrollRoot={body}+ searching={searching}+ />+ <p className={museText.small}>+ A conversation stays with the Bots in it. Pin one to keep it at the+ top.+ </p>+ <Divider className="my-1.5" />+ <div>+ <LinkRow+ icon={IconHome}+ render={<Link onClick={onClose} to="/" />}+ title="Home"+ />+ {/* OpenBot's own destinations, from the one list its sidebar draws. */}+ {navigation.map((item) => (+ <LinkRow+ icon={item.icon}+ key={item.id}+ render={<Link onClick={onClose} to={item.to} />}+ tint={item.section === "account" ? "plain" : "sky"}+ title={item.label}+ />+ ))}+ </div>+ <MuseButton+ className="self-start"+ danger+ disabled={signOut.isPending}+ icon={IconLogout}+ onClick={async () => {+ await signOut.mutateAsync();+ await navigate({ to: "/sign" });+ }}+ small+ >+ Sign out+ </MuseButton>+ <ErrorNotice error={signOut.error?.message} />+ </div>+ </MuseSheet>+ );+}++/**+ * One conversation, laid out as this look lists a side chat: its Bots' faces and title, then its actions as pills.+ * Pin and delete are the same two OpenBot offers on its sidebar row.+ */+function ConversationRow({+ channel,+ onOpen,+}: {+ channel: ChannelSummary;+ onOpen: () => void;+}) {+ const agents = useQuery(agentListQueryOptions());+ const navigate = useNavigate();+ const openId = useParams({+ strict: false,+ select: (params) => (params as { channelId?: string }).channelId,+ });+ const setPinned = useMutation(setChannelPinnedMutationOptions(queryClient));+ const [confirming, setConfirming] = useState(false);+ const group = channel.agentIds.length > 1;+ const unread = isUnread(channel, openId);+ const busy = channel.busy || (channel.work?.length ?? 0) > 0;+ const title =+ channel.summary?.trim() ||+ channel.lastMessage?.trim() ||+ "New conversation";+ const who = group+ ? channel.agentIds+ .map((id) => agents.data?.find((agent) => agent.id === id)?.name)+ .filter(Boolean)+ .join(", ") || channel.name+ : channel.name;+ const when = channel.lastMessageAt ? relativeTime(channel.lastMessageAt) : "";++ return (+ <div className="flex flex-col gap-2.5 border-border border-b py-3">+ <Item+ className={cn(+ "flex-nowrap items-start gap-2.5 border-0 p-0 [a]:hover:bg-transparent",+ channel.id === openId && "[&_[data-slot=item-title]]:underline",+ )}+ render={+ <Link+ onClick={onOpen}+ params={{ channelId: channel.id }}+ to={group ? "/group/$channelId" : "/channel/$channelId"}+ />+ }+ >+ {/* The same faces OpenBot's own conversation list draws: the Bot, or the group's Bots. */}+ <span className="mt-0.5 shrink-0">+ <ChannelAvatar+ participantIds={channel.agentIds}+ size={24}+ typing={busy}+ />+ </span>+ <ItemContent className="min-w-0 gap-0.5">+ <ItemTitle+ className={cn(+ museText.body,+ "line-clamp-1 block",+ unread && "font-semibold",+ )}+ >+ {title}+ </ItemTitle>+ <span className={cn(museText.small, "flex items-center gap-1.5")}>+ <span className="truncate">+ {who}+ {when ? ` · ${when}` : ""}+ </span>+ {busy ? (+ <span className="shrink-0 text-[var(--openmuse-accent)]">+ · working+ </span>+ ) : null}+ </span>+ </ItemContent>+ {unread ? (+ <span+ className="mt-2 size-2 shrink-0 rounded-full bg-[var(--openmuse-accent)]"+ role="img"+ aria-label="Unread"+ />+ ) : null}+ {channel.pinned ? (+ <IconPinFilled+ aria-label="Pinned"+ className="mt-1 size-3.5 shrink-0 text-muted-foreground"+ />+ ) : null}+ </Item>+ <div className="flex gap-2">+ <MuseButton+ disabled={setPinned.isPending}+ icon={channel.pinned ? IconPinnedOff : IconPin}+ onClick={() =>+ setPinned.mutate({ channelId: channel.id, pinned: !channel.pinned })+ }+ small+ >+ {channel.pinned ? "Unpin" : "Pin"}+ </MuseButton>+ <MuseButton icon={IconTrash} onClick={() => setConfirming(true)} small>+ Delete+ </MuseButton>+ </div>+ <ErrorNotice error={setPinned.error?.message} />+ <DeleteConversationDialog+ channelId={channel.id}+ leave={channel.id === openId ? () => navigate({ to: "/" }) : undefined}+ name={channel.name}+ onOpenChange={setConfirming}+ open={confirming}+ />+ </div>+ );+}diff --git a/app/src/skins/openmuse/model.ts b/app/src/skins/openmuse/model.tsnew file mode 100644index 00000000..74e477c8--- /dev/null+++ b/app/src/skins/openmuse/model.ts@@ -0,0 +1,132 @@+import { defaultAgentProfile } from "@/lib/agents/default-agent";+import type { AgentProfile } from "@/lib/agents/queries";+import type { ApprovalInboxData } from "@/lib/approvals";+import type { BotAttention } from "@/lib/bot-lifecycle/queries";+import type { ChannelSummary } from "@/lib/channels/queries";++/*+ * The rules OpenMuse's frame runs on, kept apart from the components so each one is a plain function+ * of OpenBot's own data. None of them decides anything the server already decided: they only choose+ * which of OpenBot's records to put where.+ */++export type MuseTab = "chat" | "activity" | "ideas" | "goals" | "apps";++/**+ * The Bot at the centre of the frame.+ *+ * OpenMuse is one agent. OpenBot has many, so the centre follows, in order: the Bot of the+ * conversation on screen, the Bot the person last chose, and OpenBot's own default Bot — the same+ * `defaultAgentProfile` the home screen and `/bot` fall back to.+ */+export function centreBot(+ agents: readonly AgentProfile[] | undefined,+ chosenId: string | null,+ conversationBotId: string | undefined,+): AgentProfile | undefined {+ if (!agents?.length) return undefined;+ return (+ agents.find((agent) => agent.id === conversationBotId) ??+ agents.find((agent) => agent.id === chosenId) ??+ defaultAgentProfile(agents)+ );+}++/**+ * A Bot's main chat: its one-to-one conversation the roster already lists first.+ *+ * The roster arrives pinned first and newest first, so the first one-to-one channel with this Bot is+ * the one the person is most likely to mean. A group is never a Bot's main chat.+ */+export function mainChannel(+ agentId: string | undefined,+ channels: readonly ChannelSummary[] | undefined,+): ChannelSummary | undefined {+ if (!agentId) return undefined;+ return channels?.find(+ (channel) =>+ channel.active !== false &&+ channel.agentIds.length === 1 &&+ channel.agentIds[0] === agentId,+ );+}++/**+ * The tab whose own screen this path is, or null on any other OpenBot page. Chat is the conversation+ * routes; Apps is OpenBot's Connections, the apps a Bot uses as you. A Bot's page, Routines,+ * Capabilities and the rest light no tab, because they are not that tab's screen.+ */+export function tabFor(pathname: string): MuseTab | null {+ if (pathname === "/s/activity") return "activity";+ if (pathname === "/s/ideas") return "ideas";+ if (pathname === "/s/goals") return "goals";+ if (pathname === "/connections" || pathname.startsWith("/connections/")) {+ return "apps";+ }+ if (+ pathname === "/" ||+ pathname === "/channel" ||+ pathname.startsWith("/channel/") ||+ pathname.startsWith("/group/")+ ) {+ return "chat";+ }+ return null;+}++/**+ * Whether the page stays in OpenMuse's 760px column on a wide screen. A tab's own screen does. Every+ * other OpenBot page, and a conversation with its Bot's computer or settings open beside it, gets+ * OpenBot's own width, so its wide layouts and side panels have the room they were built for.+ */+export function inColumn(pathname: string, sidePanelOpen: boolean): boolean {+ return tabFor(pathname) !== null && !sidePanelOpen;+}++const plural = (count: number, word: string) =>+ `${count} ${word}${count === 1 ? "" : "s"}`;++/**+ * The line under the Bot's name: what it is doing right now, in OpenMuse's own words.+ *+ * Something waiting on the person outranks work in progress, because it is the one thing on this+ * line they can act on. Work comes from the roster the channel socket keeps live, so the line+ * changes while a turn runs without anybody refreshing.+ */+export function statusLine(input: {+ attention: BotAttention | undefined;+ channels: readonly ChannelSummary[] | undefined;+ agentId: string | undefined;+}): string {+ const { attention, channels, agentId } = input;+ if (attention?.approvals) {+ return `Ready to review · ${plural(attention.approvals, "approval")}`;+ }+ if (attention?.questions) {+ return `Needs your input · ${plural(attention.questions, "question")}`;+ }+ if (attention?.handoffs) return "Waiting on a hand-off";+ const working = agentId+ ? channels?.find(+ (channel) =>+ channel.agentIds.includes(agentId) &&+ (channel.busy || (channel.work?.length ?? 0) > 0),+ )+ : undefined;+ if (working) {+ const routine = working.work?.find((work) => work.kind === "routine");+ if (routine && !working.busy) return "Running a routine…";+ return `Working on ${working.summary?.trim() || working.name}…`;+ }+ if (attention?.paused) return "Paused";+ return "Ready when you are";+}++/** Approvals and questions the person has not answered yet, across every Bot. */+export function waitingOnYou(inbox: ApprovalInboxData | undefined) {+ const requests = (inbox?.requests ?? []).filter(+ (request) => request.status === "pending",+ );+ const questions = inbox?.questions ?? [];+ return { requests, questions, count: requests.length + questions.length };+}diff --git a/app/src/skins/openmuse/notifications-sheet.tsx b/app/src/skins/openmuse/notifications-sheet.tsxnew file mode 100644index 00000000..e63d9e12--- /dev/null+++ b/app/src/skins/openmuse/notifications-sheet.tsx@@ -0,0 +1,43 @@+import { IconBell, IconHandStop } from "@tabler/icons-react";+import { useQuery } from "@tanstack/react-query";+import { Link } from "@tanstack/react-router";+import { WaitingForYou } from "@/components/approvals/waiting";+import { approvalInboxOptions } from "@/lib/approvals";+import { waitingOnYou } from "./model";+import { LinkRow, MuseEmpty, MuseSheet } from "./ui";++/**+ * The bell: what every Bot is waiting on the person for. The list is OpenBot's own `WaitingForYou`,+ * so every question, approval, choice and detail is exactly the one OpenBot's Bot pages show.+ */+export function NotificationsSheet({ onClose }: { onClose: () => void }) {+ const inbox = useQuery(approvalInboxOptions());+ const nothing =+ inbox.data !== undefined && waitingOnYou(inbox.data).count === 0;+ return (+ <MuseSheet+ onClose={onClose}+ subtitle="Approvals and questions your Bots are waiting on."+ title="Needs you"+ >+ <div className="flex flex-col gap-3.5">+ {nothing ? (+ <MuseEmpty+ detail="When a Bot needs your OK or an answer, it shows up here."+ icon={IconBell}+ title="You're all caught up"+ />+ ) : (+ <WaitingForYou />+ )}+ <LinkRow+ detail="What your Bots may do without asking"+ icon={IconHandStop}+ render={<Link onClick={onClose} to="/settings/approvals" />}+ tint="lavender"+ title="Approval rules"+ />+ </div>+ </MuseSheet>+ );+}diff --git a/app/src/skins/openmuse/screens/activity.tsx b/app/src/skins/openmuse/screens/activity.tsxnew file mode 100644index 00000000..43b4c2bc--- /dev/null+++ b/app/src/skins/openmuse/screens/activity.tsx@@ -0,0 +1,35 @@+import { IconListCheck } from "@tabler/icons-react";+import { BotNeedsYou } from "@/components/approvals/waiting";+import { BotActivitySections } from "@/components/bot-profile/activity";+import { useMuse } from "../context";+import { MuseEmpty, MuseScreen } from "../ui";++/**+ * Activity: what the centre Bot is waiting on you for, then what it is doing, has scheduled and has+ * finished. Both are OpenBot's own sections from the Bot's page, under OpenMuse's title.+ */+export function ActivityScreen() {+ const { bot } = useMuse();+ return (+ <MuseScreen title="Activity">+ {bot ? (+ <div className="[&>section:first-child]:mt-0">+ <BotNeedsYou agentId={bot.id} />+ <BotActivitySections agentId={bot.id} />+ </div>+ ) : (+ <NoBot />+ )}+ </MuseScreen>+ );+}++export function NoBot() {+ return (+ <MuseEmpty+ detail="Create one with New Bot on the Bots page."+ icon={IconListCheck}+ title="No Bots yet"+ />+ );+}diff --git a/app/src/skins/openmuse/screens/goals.tsx b/app/src/skins/openmuse/screens/goals.tsxnew file mode 100644index 00000000..24308f68--- /dev/null+++ b/app/src/skins/openmuse/screens/goals.tsx@@ -0,0 +1,44 @@+import { BotResponsibilities } from "@/components/responsibilities/responsibilities";+import { RoutinesList } from "@/components/routines/routines-list";+import { cn } from "@/lib/utils";+import { useMuse } from "../context";+import { Divider, MuseScreen, museText, StatusDot } from "../ui";+import { NoBot } from "./activity";++/**+ * Goals: what the centre Bot keeps doing for the person. OpenMuse's "Tracking" is OpenBot's routines,+ * and its "Goals" are OpenBot's responsibilities, which OpenBot itself titles Goals on a Bot's page.+ * Both lists are OpenBot's own, with every switch, Run now, history and Delete they offer.+ */+export function GoalsScreen() {+ const { bot } = useMuse();+ if (!bot) {+ return (+ <MuseScreen title="Goals">+ <NoBot />+ </MuseScreen>+ );+ }+ return (+ <MuseScreen title="Goals">+ <section>+ <div className="flex items-center gap-2.5">+ <StatusDot tone="green" />+ <h2+ className={cn(+ museText.heading,+ "text-[var(--openmuse-green-text)]",+ )}+ >+ Routines+ </h2>+ </div>+ <RoutinesList agentId={bot.id} embedded />+ </section>+ <Divider className="mt-8" />+ <div className="[&>section]:mt-6">+ <BotResponsibilities agentId={bot.id} />+ </div>+ </MuseScreen>+ );+}diff --git a/app/src/skins/openmuse/screens/ideas.tsx b/app/src/skins/openmuse/screens/ideas.tsxnew file mode 100644index 00000000..09f88b5a--- /dev/null+++ b/app/src/skins/openmuse/screens/ideas.tsx@@ -0,0 +1,46 @@+import { IconBulb } from "@tabler/icons-react";+import { useQuery } from "@tanstack/react-query";+import {+ ProactiveResearchSettings,+ SuggestionsInbox,+} from "@/components/suggestions/proactive-panel";+import { proactiveSuggestionsQueryOptions } from "@/lib/proactive";+import { useMuse } from "../context";+import { MuseEmpty, MuseScreen } from "../ui";+import { NoBot } from "./activity";++/**+ * Ideas: the next steps the centre Bot's background research suggested, and the research itself.+ * Both are OpenBot's own sections, so starting, dismissing and running research behave as on the+ * Bot's page.+ */+export function IdeasScreen() {+ const { bot } = useMuse();+ const suggestions = useQuery(proactiveSuggestionsQueryOptions());+ if (!bot) {+ return (+ <MuseScreen title="Ideas">+ <NoBot />+ </MuseScreen>+ );+ }+ const none =+ suggestions.data !== undefined &&+ !suggestions.data.some((suggestion) => suggestion.agentId === bot.id);+ return (+ <MuseScreen title="Ideas">+ <div className="[&>section:first-child]:mt-0">+ {none ? (+ <MuseEmpty+ detail={`${bot.name} suggests next steps here once background research is on.`}+ icon={IconBulb}+ title="No suggestions yet"+ />+ ) : (+ <SuggestionsInbox agentId={bot.id} />+ )}+ <ProactiveResearchSettings agentId={bot.id} />+ </div>+ </MuseScreen>+ );+}diff --git a/app/src/skins/openmuse/skin.css b/app/src/skins/openmuse/skin.cssnew file mode 100644index 00000000..81720ecf--- /dev/null+++ b/app/src/skins/openmuse/skin.css@@ -0,0 +1,338 @@+/*+ * OpenMuse. Light is OpenMuse's own palette from its `ui.tsx`: a near-white canvas, white cards, a+ * pale sky blue for the primary action and the person's own words, and soft pastel tiles. OpenMuse+ * ships no dark theme, so dark is drawn in its spirit: the same airy shapes at night, a deep slate+ * canvas with a blue cast, cards one step up, and the sky blue deepened into a night blue so the+ * person's bubble and the primary pill still read as the one warm accent.+ *+ * Every token is set for both. A skin's `:root[data-skin]` outranks OpenBot's `.dark`, so a token set+ * only for light would leak into dark.+ */++:root[data-skin="openmuse"] {+ color-scheme: light;+ --background: #fcfcfc;+ --foreground: #11191c;+ --card: #ffffff;+ --card-foreground: #11191c;+ --popover: #ffffff;+ --popover-foreground: #11191c;+ --primary: #c8e7ff;+ --primary-foreground: #11191c;+ --secondary: #f1f2f3;+ --secondary-foreground: #11191c;+ --muted: #f0f1f2;+ --muted-foreground: #697176;+ --accent: #edf7fd;+ --accent-foreground: #11191c;+ --destructive: #aa4a45;+ --success: #189a58;+ --border: #eeeef0;+ --input: #e6e8ea;+ --ring: #7fbde9;+ --chart-1: #1473c8;+ --chart-2: #6aaee0;+ --chart-3: #24a46b;+ --chart-4: #6866a6;+ --chart-5: #e59a2b;+ --radius: 1rem;+ --sidebar: #f6f7f8;+ --sidebar-foreground: #11191c;+ --sidebar-primary: #1473c8;+ --sidebar-primary-foreground: #ffffff;+ --sidebar-accent: #edeef0;+ --sidebar-accent-foreground: #11191c;+ --sidebar-border: #eeeef0;+ --sidebar-ring: #7fbde9;++ --openmuse-font:+ -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Roboto,+ Helvetica, Arial, sans-serif;+ --font-sans: var(--openmuse-font);+ --openmuse-accent: #1473c8;+ --openmuse-blue: #c8e7ff;+ --openmuse-sky: #edf7fd;+ --openmuse-green: #e3f3e8;+ --openmuse-lavender: #f0eefa;+ --openmuse-orange: #fdf0df;+ --openmuse-chip: #f3f4f5;+ --openmuse-danger-tint: #fbefed;+ --openmuse-pressed: #e9eaec;+ --openmuse-primary-hover: #b5ddfb;+ --openmuse-task: #f0f1f2;+ --openmuse-tab-active: #f0f1f2;+ --openmuse-tab-hover: #f7f8f8;+ --openmuse-pill: #ffffff;+ --openmuse-pill-border: #f8f8f8;+ --openmuse-pill-shadow: rgba(19, 38, 49, 0.07);+ --openmuse-scrim: rgba(35, 48, 44, 0.25);+ --openmuse-handle: #d8dbde;+ --openmuse-group: #f3f4f5;+ --openmuse-group-line: #e5e7e9;+ --openmuse-group-soft: #f4f5f6;+ --openmuse-quiet: #a3a6a8;+ --openmuse-quiet-text: #666a6d;+ --openmuse-green-dot: #24a46b;+ --openmuse-green-ring: #d9f1e2;+ --openmuse-green-text: #189a58;+ --openmuse-blue-dot: #3d9bde;+ --openmuse-blue-ring: #d7e9fa;+ --openmuse-amber: #e59a2b;+ --openmuse-focus: #c7e4f9;+ --openmuse-user-bubble: #c8e7ff;+ --openmuse-bot-bubble: #eeeef0;+ --openmuse-composer: #ffffff;+ --openmuse-composer-border: #eef0f2;+ --openmuse-composer-shadow: rgba(24, 56, 75, 0.06);+ --openmuse-send-idle: #f3f5f6;+}++:root[data-skin="openmuse"].dark {+ color-scheme: dark;+ --background: #0e1316;+ --foreground: #e8edef;+ --card: #161c20;+ --card-foreground: #e8edef;+ --popover: #161c20;+ --popover-foreground: #e8edef;+ --primary: #1f4766;+ --primary-foreground: #dcefff;+ --secondary: #1d2428;+ --secondary-foreground: #e8edef;+ --muted: #1b2226;+ --muted-foreground: #8d989e;+ --accent: #142530;+ --accent-foreground: #e8edef;+ --destructive: #e07a73;+ --success: #4cc38a;+ --border: #232b30;+ --input: #2a3338;+ --ring: #3f7fae;+ --chart-1: #6fb6f0;+ --chart-2: #3d9bde;+ --chart-3: #4cc38a;+ --chart-4: #a19fe0;+ --chart-5: #f0b45a;+ --radius: 1rem;+ --sidebar: #12181b;+ --sidebar-foreground: #e8edef;+ --sidebar-primary: #6fb6f0;+ --sidebar-primary-foreground: #0e1316;+ --sidebar-accent: #1d2428;+ --sidebar-accent-foreground: #e8edef;+ --sidebar-border: #232b30;+ --sidebar-ring: #3f7fae;++ --openmuse-font:+ -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Roboto,+ Helvetica, Arial, sans-serif;+ --font-sans: var(--openmuse-font);+ --openmuse-accent: #6fb6f0;+ --openmuse-blue: #2a5576;+ --openmuse-sky: #13242e;+ --openmuse-green: #142a1f;+ --openmuse-lavender: #1f1d33;+ --openmuse-orange: #2d2215;+ --openmuse-chip: #1f272b;+ --openmuse-danger-tint: #2e1716;+ --openmuse-pressed: #232b30;+ --openmuse-primary-hover: #275678;+ --openmuse-task: #182025;+ --openmuse-tab-active: #232c31;+ --openmuse-tab-hover: #1b2226;+ --openmuse-pill: #161c20;+ --openmuse-pill-border: #222a2f;+ --openmuse-pill-shadow: rgba(0, 0, 0, 0.45);+ --openmuse-scrim: rgba(4, 8, 10, 0.6);+ --openmuse-handle: #3a444a;+ --openmuse-group: #161c20;+ --openmuse-group-line: #232b30;+ --openmuse-group-soft: #161c20;+ --openmuse-quiet: #5f6a70;+ --openmuse-quiet-text: #a3adb2;+ --openmuse-green-dot: #4cc38a;+ --openmuse-green-ring: #173827;+ --openmuse-green-text: #5fd39b;+ --openmuse-blue-dot: #5aaee8;+ --openmuse-blue-ring: #17344a;+ --openmuse-amber: #f0b45a;+ --openmuse-focus: #2f6a95;+ --openmuse-user-bubble: #1f4766;+ --openmuse-bot-bubble: #1b2226;+ --openmuse-composer: #161c20;+ --openmuse-composer-border: #242d32;+ --openmuse-composer-shadow: rgba(0, 0, 0, 0.35);+ --openmuse-send-idle: #1f272b;+}++/*+ * OpenMuse is set in the device's own system font. `--font-sans` above is the token OpenBot's+ * headings read; the page itself takes it here, because OpenBot names Inter on `html` directly.+ */+:root[data-skin="openmuse"] {+ font-family: var(--font-sans);+}++/*+ * OpenBot's own pages, worn the OpenMuse way. Every rule below reaches OpenBot's components only+ * through the `data-slot` hooks they publish for this, so restyling a component inside OpenBot cannot+ * silently break the skin.+ */++/* OpenMuse's buttons are pills. */+:root[data-skin="openmuse"] [data-slot="button"] {+ border-radius: 9999px;+}++/* Page titles at OpenMuse's 25px, semibold and tight. */+:root[data-skin="openmuse"] .openmuse-stage [data-slot="page-title"] {+ font-size: 25px;+ font-weight: 600;+ letter-spacing: -0.7px;+}++/* OpenBot's "a Bot needs you" badge, drawn as OpenMuse's small blue dot on the menu button. */+:root[data-skin="openmuse"] .openmuse-menu-badge [role="img"] {+ position: absolute;+ top: 7px;+ right: 9px;+ width: 6px;+ height: 6px;+ min-width: 0;+ margin: 0;+ padding: 0;+ border-radius: 9999px;+ font-size: 0;+ line-height: 0;+ background: var(--openmuse-accent);+ color: transparent;+}++/* Chat sits in OpenMuse's padded column: 17px on a phone, 42px on a desktop. */+:root[data-skin="openmuse"]+ .openmuse-frame[data-openmuse-tab="chat"]+ .openmuse-stage {+ padding-inline: 17px;+}++@media (min-width: 900px) {+ :root[data-skin="openmuse"]+ .openmuse-frame[data-openmuse-tab="chat"]+ .openmuse-stage {+ padding-inline: 42px;+ }+}++:root[data-skin="openmuse"]+ .openmuse-stage+ [data-slot="message-scroller-content"] {+ padding-inline: 0;+ gap: 13px;+}++/* A conversation's own header row carries no rule beneath it; the frame above already separates. */+:root[data-skin="openmuse"] .openmuse-stage [data-slot="conversation-header"] {+ border-bottom-color: transparent;+ padding-inline: 0;+}++/* With the computer or settings beside it on a wide screen, the conversation takes OpenBot's own layout. */+@media (min-width: 1100px) {+ :root[data-skin="openmuse"]+ .openmuse-frame[data-openmuse-tab="chat"]+ .openmuse-stage[data-openmuse-width="page"] {+ padding-inline: 0;+ }++ :root[data-skin="openmuse"]+ .openmuse-stage[data-openmuse-width="page"]+ [data-slot="conversation-header"] {+ padding-inline: 12px;+ }+}++/* The person's words: OpenMuse's pale-blue bubble with its tucked corner. */+:root[data-skin="openmuse"]+ .openmuse-stage+ [data-slot="bubble"][data-align="end"]+ > [data-slot="bubble-content"] {+ background: var(--openmuse-user-bubble);+ color: var(--foreground);+ border-radius: 22px 22px 7px 22px;+ padding: 13px 16px;+ font-size: 16px;+ line-height: 24px;+}++/* The Bot's words: OpenMuse's soft grey bubble, tucked on the other side. */+:root[data-skin="openmuse"]+ .openmuse-stage+ [data-slot="bubble"][data-variant="ghost"][data-align="start"]+ > [data-slot="bubble-content"] {+ background: var(--openmuse-bot-bubble);+ border-radius: 22px 22px 22px 7px;+ padding: 13px 16px;+ font-size: 15px;+ line-height: 23px;+}++/* The composer: OpenMuse's white pill with a soft shadow, a "+" on the left and a round send. */+:root[data-skin="openmuse"] .openmuse-stage [data-slot="composer"] {+ min-height: 62px;+ padding: 8px;+ border: 1px solid var(--openmuse-composer-border);+ border-radius: 32px;+ background: var(--openmuse-composer);+ box-shadow: 0 4px 20px var(--openmuse-composer-shadow);+}++:root[data-skin="openmuse"]+ .openmuse-stage+ [data-slot="composer"]:focus-within {+ border-color: var(--openmuse-focus);+ box-shadow: 0 4px 20px var(--openmuse-composer-shadow);+}++:root[data-skin="openmuse"] .openmuse-stage [data-slot="composer-input"] > * {+ font-size: 17px;+ line-height: 24px;+}++:root[data-skin="openmuse"] .openmuse-stage [data-slot="composer-attach"],+:root[data-skin="openmuse"] .openmuse-stage [data-slot="composer-send"],+:root[data-skin="openmuse"] .openmuse-stage [data-slot="composer-stop"] {+ width: 44px;+ height: 44px;+ border-radius: 9999px;+ align-self: flex-end;+}++:root[data-skin="openmuse"] .openmuse-stage [data-slot="composer-attach"] svg {+ width: 24px;+ height: 24px;+ stroke-width: 1.5;+}++:root[data-skin="openmuse"] .openmuse-stage [data-slot="composer-send"],+:root[data-skin="openmuse"] .openmuse-stage [data-slot="composer-stop"] {+ background: var(--primary);+ color: var(--primary-foreground);+}++:root[data-skin="openmuse"]+ .openmuse-stage+ [data-slot="composer-send"]:disabled {+ background: var(--openmuse-send-idle);+ color: var(--openmuse-quiet);+ opacity: 1;+}++:root[data-skin="openmuse"] .openmuse-stage [data-slot="composer-send"] svg {+ width: 22px;+ height: 22px;+}++/* A row that opens something reads from its start, as every other row does. */+:root[data-skin="openmuse"] .openmuse-stage button[data-slot="item"] {+ text-align: start;+}diff --git a/app/src/skins/openmuse/ui.tsx b/app/src/skins/openmuse/ui.tsxnew file mode 100644index 00000000..a32e672d--- /dev/null+++ b/app/src/skins/openmuse/ui.tsx@@ -0,0 +1,364 @@+import { IconChevronRight, type IconProps, IconX } from "@tabler/icons-react";+import * as React from "react";+import { Button, buttonVariants } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogTitle,+} from "@/components/ui/dialog";+import {+ Item,+ ItemActions,+ ItemContent,+ ItemDescription,+ ItemMedia,+ ItemTitle,+} from "@/components/ui/item";+import { cn } from "@/lib/utils";++/*+ * OpenMuse's primitives, rebuilt on OpenBot's own. Each one is an OpenBot component — Button, Item,+ * Dialog — wearing OpenMuse's measurements: 23px cards, pill buttons, 42px icon tiles, a 44px round+ * icon button, and the 15/14/11px type steps from its stylesheet. Colours come from the skin's tokens,+ * so dark mode follows without a branch here.+ */++export type MuseIcon = React.ComponentType<IconProps>;++export const museText = {+ body: "text-[15px] leading-[23px] text-foreground",+ muted: "text-[14px] leading-[21px] text-muted-foreground",+ small: "text-[11px] leading-[17px] text-muted-foreground",+ heading: "text-[16px] font-semibold tracking-[-0.25px] text-foreground",+ title: "text-[23px] font-semibold tracking-[-0.7px] text-foreground",+} as const;++type MuseButtonLook = { primary?: boolean; small?: boolean; danger?: boolean };++/** OpenMuse's pill: pale blue when it is the one thing to do, soft grey otherwise. */+export function museButtonClass({+ primary = false,+ small = false,+ danger = false,+}: MuseButtonLook = {}) {+ return cn(+ buttonVariants({ variant: "secondary" }),+ "h-auto min-h-[42px] gap-2 rounded-full border-0 px-[17px] py-2.5 font-semibold text-[14px] shadow-none active:translate-y-0 active:scale-[0.98] motion-reduce:transition-none motion-reduce:active:scale-100 [&_svg]:size-[15px]",+ primary+ ? "bg-primary text-primary-foreground hover:bg-[var(--openmuse-primary-hover)]"+ : "bg-secondary text-secondary-foreground hover:bg-[var(--openmuse-pressed)]",+ danger && "text-destructive",+ small && "min-h-[38px] px-[13px] py-[7px]",+ );+}++export function MuseButton({+ children,+ className,+ icon: Icon,+ primary,+ small,+ danger,+ ...props+}: React.ComponentProps<typeof Button> &+ MuseButtonLook & {+ icon?: MuseIcon;+ }) {+ return (+ <Button+ className={cn(museButtonClass({ primary, small, danger }), className)}+ variant="secondary"+ {...props}+ >+ {Icon ? <Icon stroke={1.9} /> : null}+ {children}+ </Button>+ );+}++/**+ * A pill that goes somewhere. Base UI's Button gives an anchor the button role, so a destination is+ * an anchor of its own wearing the same pill, and keeps its link role.+ */+export function MuseLinkButton({+ children,+ className,+ icon: Icon,+ primary,+ small,+ danger,+ render,+}: MuseButtonLook & {+ children: React.ReactNode;+ className?: string;+ icon?: MuseIcon;+ render: React.ReactElement<{+ className?: string;+ children?: React.ReactNode;+ }>;+}) {+ return React.cloneElement(render, {+ className: cn(museButtonClass({ primary, small, danger }), className),+ children: (+ <>+ {Icon ? <Icon aria-hidden="true" stroke={1.9} /> : null}+ {children}+ </>+ ),+ });+}++/** The round white button in the top bar and on every sheet. */+export function RoundButton({+ icon: Icon,+ label,+ className,+ children,+ ...props+}: React.ComponentProps<"button"> & { icon: MuseIcon; label: string }) {+ return (+ <button+ aria-label={label}+ className={cn(+ "relative flex size-11 shrink-0 items-center justify-center rounded-full bg-card text-foreground outline-none transition-colors hover:bg-[var(--openmuse-pressed)] focus-visible:ring-3 focus-visible:ring-ring/50 motion-reduce:transition-none",+ className,+ )}+ type="button"+ {...props}+ >+ <Icon className="size-5" stroke={1.8} />+ {children}+ </button>+ );+}++const TILE_TINTS = {+ sky: "bg-[var(--openmuse-sky)]",+ green: "bg-[var(--openmuse-green)]",+ lavender: "bg-[var(--openmuse-lavender)]",+ orange: "bg-[var(--openmuse-orange)]",+ plain: "bg-secondary",+} as const;++export type TileTint = keyof typeof TILE_TINTS;++/** OpenMuse's rounded square that holds an icon. */+export function IconTile({+ icon: Icon,+ tint = "sky",+ size = 42,+ accent = false,+ className,+}: {+ icon: MuseIcon;+ tint?: TileTint;+ size?: 34 | 42 | 55;+ accent?: boolean;+ className?: string;+}) {+ return (+ <span+ aria-hidden="true"+ className={cn(+ "flex shrink-0 items-center justify-center",+ size === 55 ? "size-[55px] rounded-[18px]" : "rounded-[13px]",+ size === 42 && "size-[42px]",+ size === 34 && "size-[34px]",+ TILE_TINTS[tint],+ accent ? "text-[var(--openmuse-accent)]" : "text-foreground",+ className,+ )}+ >+ <Icon+ className={+ size === 55 ? "size-6" : size === 34 ? "size-[18px]" : "size-[19px]"+ }+ stroke={1.8}+ />+ </span>+ );+}++/**+ * A row that leads somewhere: tile, title, one line of detail, chevron. `render` is the element it+ * is drawn as — a router `Link` for a page, a `button` for a sheet — exactly as `Item` takes it.+ */+export function LinkRow({+ icon,+ title,+ detail,+ tint = "sky",+ render,+ trailing,+}: {+ icon: MuseIcon;+ title: React.ReactNode;+ detail?: React.ReactNode;+ tint?: TileTint;+ render: React.ComponentProps<typeof Item>["render"];+ trailing?: React.ReactNode;+}) {+ return (+ <Item+ className="flex-nowrap gap-3.5 rounded-[10px] border-0 px-0 py-[13px] hover:bg-transparent active:bg-[var(--openmuse-pressed)] [a]:hover:bg-transparent"+ render={render}+ >+ <ItemMedia className="translate-y-0! self-center!">+ <IconTile icon={icon} tint={tint} />+ </ItemMedia>+ <ItemContent className="min-w-0 gap-[3px]">+ <ItemTitle className="font-medium text-[15px] leading-[23px]">+ {title}+ </ItemTitle>+ {detail ? (+ <ItemDescription+ className={cn(museText.small, "line-clamp-1 text-[11px]")}+ >+ {detail}+ </ItemDescription>+ ) : null}+ </ItemContent>+ <ItemActions className="gap-2">+ {trailing}+ <IconChevronRight+ aria-hidden="true"+ className="size-[15px] text-muted-foreground"+ />+ </ItemActions>+ </Item>+ );+}++export function MuseEmpty({+ icon,+ title,+ detail,+ children,+}: {+ icon: MuseIcon;+ title: string;+ detail: React.ReactNode;+ children?: React.ReactNode;+}) {+ return (+ <div className="flex flex-col items-center gap-[13px] p-10 text-center">+ <IconTile accent icon={icon} size={55} />+ <h3 className={museText.heading}>{title}</h3>+ <p className={cn(museText.muted, "max-w-[360px] text-pretty")}>+ {detail}+ </p>+ {children}+ </div>+ );+}++export function ErrorNotice({ error }: { error?: string | null }) {+ if (!error) return null;+ return (+ <div+ className="my-2.5 rounded-[14px] bg-[var(--openmuse-danger-tint)] p-4 text-[15px] text-destructive leading-[23px]"+ role="alert"+ >+ {error}+ </div>+ );+}++export function Divider({ className }: { className?: string }) {+ return <div className={cn("h-px bg-border", className)} />;+}++/** A coloured status dot, as on OpenMuse's Tracking and Goals headings. */+export function StatusDot({ tone }: { tone: "green" | "blue" }) {+ return (+ <span+ aria-hidden="true"+ className={cn(+ "size-4 shrink-0 rounded-full border-[5px]",+ tone === "green"+ ? "border-[var(--openmuse-green-ring)] bg-[var(--openmuse-green-dot)]"+ : "border-[var(--openmuse-blue-ring)] bg-[var(--openmuse-blue-dot)]",+ )}+ />+ );+}++/**+ * OpenMuse's sheet: a card that rises from the bottom on a phone, with a grab handle, and settles in+ * the middle on anything wider. Built on OpenBot's Dialog, so focus, Escape and the backdrop behave+ * the way every other OpenBot dialog does.+ */+export function MuseSheet({+ title,+ subtitle,+ children,+ onClose,+ bodyRef,+}: {+ title: string;+ subtitle?: React.ReactNode;+ children: React.ReactNode;+ onClose: () => void;+ bodyRef?: React.Ref<HTMLDivElement>;+}) {+ return (+ <Dialog onOpenChange={(open) => !open && onClose()} open>+ <DialogContent+ className={cn(+ "openmuse-sheet gap-0 overflow-hidden border border-border bg-background p-0 text-foreground shadow-none motion-reduce:transition-none",+ // A phone: pinned to the bottom edge, full width, square at the bottom.+ "top-auto bottom-0 left-0 max-h-[94svh] w-full max-w-none translate-x-0 translate-y-0 rounded-[26px] rounded-b-none pb-3",+ // Wider: centred, OpenMuse's 790px card.+ "min-[600px]:top-1/2 min-[600px]:bottom-auto min-[600px]:left-1/2 min-[600px]:w-[calc(100%-40px)] min-[600px]:max-w-[790px] min-[600px]:-translate-x-1/2 min-[600px]:-translate-y-1/2 min-[600px]:rounded-[26px] min-[600px]:pb-0",+ )}+ overlayClassName="bg-[var(--openmuse-scrim)] supports-backdrop-filter:backdrop-blur-none motion-reduce:transition-none"+ showCloseButton={false}+ >+ <span+ aria-hidden="true"+ className="mx-auto mt-2.5 block h-1 w-[34px] shrink-0 rounded-[3px] bg-[var(--openmuse-handle)] min-[600px]:hidden"+ />+ <div className="flex shrink-0 items-center justify-between gap-4 border-border border-b p-5 min-[600px]:p-6">+ <div className="flex min-w-0 flex-1 flex-col gap-1">+ <DialogTitle className={cn(museText.title, "font-semibold")}>+ {title}+ </DialogTitle>+ {subtitle ? (+ <DialogDescription className={museText.muted}>+ {subtitle}+ </DialogDescription>+ ) : null}+ </div>+ <RoundButton icon={IconX} label="Close" onClick={onClose} />+ </div>+ <div+ className="min-h-0 flex-1 overflow-y-auto p-5 min-[600px]:p-6"+ ref={bodyRef}+ >+ {children}+ </div>+ </DialogContent>+ </Dialog>+ );+}++/** The scrolling page every OpenMuse tab is drawn on, with its 25px title. */+export function MuseScreen({+ title,+ children,+}: {+ title: string;+ children: React.ReactNode;+}) {+ return (+ <div className="min-h-0 flex-1 overflow-y-auto">+ <div className="px-[22px] pb-7 min-[900px]:px-[42px]">+ <h1 className="mb-[22px] font-semibold text-[25px] text-foreground tracking-[-0.7px]">+ {title}+ </h1>+ {children}+ </div>+ </div>+ );+}diff --git a/app/src/skins/registry.ts b/app/src/skins/registry.tsnew file mode 100644index 00000000..b6fbb378--- /dev/null+++ b/app/src/skins/registry.ts@@ -0,0 +1,28 @@+import { appConfig } from "@/lib/generated/application-config";+import { opendots } from "./opendots";+import { openduet } from "./openduet";+import { openmuse } from "./openmuse";+import { useSkinId } from "./store";+import type { Skin, SkinId } from "./types";++/*+ * The default is the product as `brand.yaml` names it, so a deployment that renames OpenBot sees+ * its own name here too. The description says nothing a rename could make untrue.+ */+const openbot: Skin = {+ id: "openbot",+ name: appConfig.brand.productName,+ description: "The standard look, with your conversations in a sidebar.",+};++/** Keyed by every id in `SKIN_IDS`, so a skin cannot be listed without being registered. */+export const SKINS: Record<SkinId, Skin> = {+ openbot,+ openduet,+ opendots,+ openmuse,+};++export function useActiveSkin(): Skin {+ return SKINS[useSkinId()];+}diff --git a/app/src/skins/skin-picker.tsx b/app/src/skins/skin-picker.tsxnew file mode 100644index 00000000..1621e0f4--- /dev/null+++ b/app/src/skins/skin-picker.tsx@@ -0,0 +1,89 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import {+ Item,+ ItemActions,+ ItemContent,+ ItemDescription,+ ItemTitle,+} from "@/components/ui/item";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { appConfig } from "@/lib/generated/application-config";+import {+ saveSkinMutationOptions,+ useUserPreferences,+} from "@/lib/settings/message-list";+import { SKINS } from "./registry";+import { useSkinId } from "./store";+import { SKIN_IDS } from "./types";++/**+ * Choose a skin. It is drawn at once and saved on the person's account, so it follows them to every+ * device. Until the account's preferences have loaded there is nothing to save against, so the+ * control waits for them.+ */+export function SkinPicker() {+ const skin = useSkinId();+ const preferences = useUserPreferences();+ const queryClient = useQueryClient();+ const save = useMutation(+ saveSkinMutationOptions(queryClient, preferences.userId),+ );++ return (+ <>+ <Item size="sm">+ <ItemContent>+ <ItemTitle>Skin</ItemTitle>+ <ItemDescription>+ Change how {appConfig.brand.productName} looks for you, on every+ device. Every skin keeps everything {appConfig.brand.productName}{" "}+ does.+ </ItemDescription>+ </ItemContent>+ <ItemActions>+ <Select+ disabled={!preferences.data || save.isPending}+ value={skin}+ onValueChange={(value) => {+ const id = SKIN_IDS.find((known) => known === value);+ if (id && id !== skin) save.mutate(id);+ }}+ >+ <SelectTrigger aria-label="Skin">+ <SelectValue>{SKINS[skin].name}</SelectValue>+ </SelectTrigger>+ {/* Wider than the trigger, so each skin's description has room to wrap. */}+ <SelectContent+ align="end"+ alignItemWithTrigger={false}+ className="w-72"+ >+ {SKIN_IDS.map((id) => (+ <SelectItem className="py-1.5" key={id} value={id}>+ <span className="flex min-w-0 flex-col gap-0.5 whitespace-normal">+ <span>{SKINS[id].name}</span>+ <span className="text-muted-foreground text-xs">+ {SKINS[id].description}+ </span>+ </span>+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </ItemActions>+ </Item>+ {save.isError ? (+ <p className="px-3 pb-3 text-sm text-destructive" role="alert">+ Couldn't save that skin to your account, so {SKINS[skin].name} is+ back. Try again.+ </p>+ ) : null}+ </>+ );+}diff --git a/app/src/skins/skins.css b/app/src/skins/skins.cssnew file mode 100644index 00000000..284ac221--- /dev/null+++ b/app/src/skins/skins.css@@ -0,0 +1,9 @@+/*+ * Each skin scopes its tokens to `:root[data-skin="<id>"]` and `:root[data-skin="<id>"].dark`.+ * That selector outranks OpenBot's own `.dark`, so a token a skin sets for light it must also set+ * for dark, or dark mode would show the skin's light value. `app/tests/skins.test.ts` holds every+ * skin to that.+ */+@import "./openduet/skin.css";+@import "./opendots/skin.css";+@import "./openmuse/skin.css";diff --git a/app/src/skins/store.ts b/app/src/skins/store.tsnew file mode 100644index 00000000..f09ac176--- /dev/null+++ b/app/src/skins/store.ts@@ -0,0 +1,150 @@+import { useSyncExternalStore } from "react";+import { DEFAULT_SKIN, SKIN_IDS, type SkinId } from "./types";++/*+ * The skin is saved on the person's account (`skin` in their preferences), so it follows them to+ * every device they sign in from. This store is the browser's copy of it, and the one thing every+ * frame reads.+ *+ * localStorage holds it only as a pre-paint cache. `index.html` reads the same key before the first+ * paint and sets `data-skin`, so a reload never flashes the default while the preferences load. Once+ * they have loaded, `SkinAccountSync` applies the account's skin over whatever the cache held, so+ * the account always wins. Signing out clears the cache, so the next person on a shared machine+ * starts from the default.+ */+export const SKIN_STORAGE_KEY = "openbot-skin";++export { DEFAULT_SKIN };++export function parseStoredSkin(value: string | null | undefined): SkinId {+ return SKIN_IDS.find((id) => id === value) ?? DEFAULT_SKIN;+}++type SkinEffects = {+ setStoredValue: (key: string, value: string) => void;+ removeStoredValue: (key: string) => void;+ setRootSkin: (id: SkinId | null) => void;+};++/** The default skin clears the attribute rather than naming itself, so no skin rule can match it. */+export function applySkin(+ id: SkinId,+ effects: Pick<SkinEffects, "setStoredValue" | "setRootSkin">,+) {+ effects.setStoredValue(SKIN_STORAGE_KEY, id);+ effects.setRootSkin(id === DEFAULT_SKIN ? null : id);+}++/** Forget the cached skin and draw the default, as a browser nobody has signed in to does. */+export function clearCachedSkin(+ effects: Pick<SkinEffects, "removeStoredValue" | "setRootSkin">,+) {+ effects.removeStoredValue(SKIN_STORAGE_KEY);+ effects.setRootSkin(null);+}++const browserEffects: SkinEffects = {+ // localStorage throws in some privacy modes; the skin still applies for this visit.+ setStoredValue: (key, value) => {+ try {+ window.localStorage.setItem(key, value);+ } catch {}+ },+ removeStoredValue: (key) => {+ try {+ window.localStorage.removeItem(key);+ } catch {}+ },+ setRootSkin: (id) => {+ // Importing the registry outside a browser (a test with no DOM) has no document to mark.+ if (typeof document === "undefined") return;+ if (id) {+ document.documentElement.dataset.skin = id;+ } else {+ delete document.documentElement.dataset.skin;+ }+ },+};++/*+ * `index.html` applies whatever the key holds before the first paint, without knowing which skins+ * this build ships. A stored skin that has since been removed would otherwise stay on `<html>` for+ * the rest of the visit while the app draws the default, so the app settles the attribute on load.+ */+export function reconcileSkin(+ stored: string | null,+ effects: Pick<SkinEffects, "setRootSkin">,+): SkinId {+ const id = parseStoredSkin(stored);+ effects.setRootSkin(id === DEFAULT_SKIN ? null : id);+ return id;+}++function readStoredValue() {+ try {+ return window.localStorage.getItem(SKIN_STORAGE_KEY);+ } catch {+ return null;+ }+}++let current: SkinId = reconcileSkin(readStoredValue(), browserEffects);+const listeners = new Set<() => void>();++function notify() {+ for (const listener of listeners) {+ listener();+ }+}++/** The skin drawn right now, for code outside React (a mutation remembering what to go back to). */+export function getSkinId(): SkinId {+ return current;+}++/**+ * Draw `id` and cache it for the next pre-paint. This changes nothing on the account: the picker+ * saves through `saveSkinMutationOptions`, and the account sync calls this with what was saved.+ */+export function setSkin(id: SkinId) {+ const changed = id !== current;+ current = id;+ applySkin(id, browserEffects);+ if (changed) notify();+}++/** Signing out: forget the cached skin and go back to the default. */+export function clearSkin() {+ const changed = current !== DEFAULT_SKIN;+ current = DEFAULT_SKIN;+ clearCachedSkin(browserEffects);+ if (changed) notify();+}++/*+ * Another tab choosing a skin writes the same key, and the browser tells every other tab with a+ * `storage` event. Following it keeps two open tabs from disagreeing about which frame to draw.+ */+function onStorage(event: StorageEvent) {+ if (event.key !== SKIN_STORAGE_KEY) return;+ current = parseStoredSkin(event.newValue);+ browserEffects.setRootSkin(current === DEFAULT_SKIN ? null : current);+ notify();+}++function subscribe(listener: () => void) {+ listeners.add(listener);+ if (listeners.size === 1) window.addEventListener("storage", onStorage);+ return () => {+ listeners.delete(listener);+ if (listeners.size === 0) window.removeEventListener("storage", onStorage);+ };+}++export function useSkinId() {+ return useSyncExternalStore(+ subscribe,+ () => current,+ () => DEFAULT_SKIN,+ );+}diff --git a/app/src/skins/types.ts b/app/src/skins/types.tsnew file mode 100644index 00000000..9d736f10--- /dev/null+++ b/app/src/skins/types.ts@@ -0,0 +1,31 @@+import type { SkinId } from "@openbot/shared/user-preferences";+import type { ComponentType, ReactNode } from "react";++/*+ * The ids live in `shared/` because the choice is saved on the person's account and the server+ * checks it. They are re-exported here so a skin reads them from beside its own type.+ */+export {+ DEFAULT_SKIN,+ SKIN_IDS,+ type SkinId,+} from "@openbot/shared/user-preferences";++export type Skin = {+ id: SkinId;+ /** The product name this skin presents as, shown in the picker and inside its own frame. */+ name: string;+ /** One line for the picker. */+ description: string;+ /**+ * Replaces OpenBot's sidebar frame around every page under `/_authed/_app`. It must render+ * `children` (the page) and must give the person a way to reach Settings, so a skin can always+ * be switched back. Absent, the page keeps OpenBot's own frame.+ */+ Frame?: ComponentType<{ children: ReactNode }>;+ /**+ * Screens only this skin has, served at `/s/<key>`. They draw OpenBot's existing data; a skin+ * adds no endpoint. A key the active skin does not have goes home.+ */+ screens?: Record<string, ComponentType>;+};diff --git a/app/src/styles.css b/app/src/styles.cssindex 12f77214..6843f606 100644--- a/app/src/styles.css+++ b/app/src/styles.css@@ -4,6 +4,7 @@/* Composer chips/dropdown. Reads the shadcn tokens declared below, so it themes itself. */@import "prompt-area/tailwind.css";@import "@fontsource-variable/inter";+@import "./skins/skins.css";/** Streamdown draws a Bot's prose, and Tailwind only ships classes it can see used. Its markup livesdiff --git a/app/tests/app-navigation.test.tsx b/app/tests/app-navigation.test.tsxnew file mode 100644index 00000000..b894ade3--- /dev/null+++ b/app/tests/app-navigation.test.tsx@@ -0,0 +1,195 @@+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,+ createRouter,+ RouterProvider,+} from "@tanstack/react-router";+import { cleanup, render, waitFor, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { AppSidebar } from "@/components/app-sidebar/app-sidebar";+import { SidebarProvider } from "@/components/ui/sidebar";+import { agentKeys } from "@/lib/agents/queries";+import { authKeys } from "@/lib/auth/queries";+import { botLifecycleKeys } from "@/lib/bot-lifecycle/queries";+import { channelKeys } from "@/lib/channels/queries";+import { NAVIGATION, navigationFor } from "@/lib/navigation";+import { userPreferencesQueryOptions } from "@/lib/settings/message-list";+import { settleReactWork } from "./settle-react-work";++/*+ * OpenBot's destinations live in one list (`lib/navigation.ts`) that the sidebar and every skin draw+ * from. This holds the sidebar to that list exactly: the same entries, in the same order, at the+ * same addresses, with Admin only for admins. A destination added to the list and not drawn, or+ * drawn here and not added to the list, fails.+ */++class OfflineWebSocket extends EventTarget {+ static readonly CONNECTING = 0;+ static readonly OPEN = 1;+ static readonly CLOSING = 2;+ static readonly CLOSED = 3;+ readyState = 0;+ onclose = null;+ onerror = null;+ onmessage = null;+ onopen = null;+ close() {}+ send() {}+}++const originalFetch = globalThis.fetch;+const originalWebSocket = globalThis.WebSocket;+const clients: QueryClient[] = [];++beforeAll(() => {+ GlobalRegistrator.register({ url: "http://localhost/" });+ globalThis.WebSocket = OfflineWebSocket as unknown as typeof WebSocket;+});+beforeEach(() => {+ globalThis.fetch = Object.assign(+ async () => Response.json({ error: "not served" }, { status: 404 }),+ { preconnect: originalFetch.preconnect },+ );+});+afterEach(() => {+ cleanup();+ for (const client of clients) client.clear();+ clients.length = 0;+ globalThis.fetch = originalFetch;+});+afterAll(async () => {+ await settleReactWork();+ globalThis.WebSocket = originalWebSocket;+ GlobalRegistrator.unregister();+});++function renderSidebar(role: "admin" | "user") {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false, staleTime: Infinity } },+ });+ clients.push(queryClient);+ queryClient.setQueryData(authKeys.currentUser(), {+ id: "maya",+ name: "Maya Chen",+ email: "[email protected]",+ role,+ onboarding: null,+ });+ queryClient.setQueryData(userPreferencesQueryOptions("maya").queryKey, {+ messageListEmphasis: "thread",+ selfHostBannerDismissed: true,+ skin: "openbot",+ });+ queryClient.setQueryData(agentKeys.list(false), []);+ queryClient.setQueryDefaults(botLifecycleKeys.attention, {+ staleTime: Number.POSITIVE_INFINITY,+ refetchInterval: false,+ });+ // One question waiting, so the Bots entry carries its badge.+ queryClient.setQueryData(botLifecycleKeys.attention, [+ {+ agentId: "expenses",+ name: "Expenses",+ questions: 1,+ approvals: 0,+ handoffs: 0,+ unread: 0,+ paused: false,+ notify: "all",+ },+ ]);+ queryClient.setQueryData(channelKeys.list(), {+ pages: [{ channels: [], nextCursor: null }],+ pageParams: [""],+ });+ const router = createRouter({+ routeTree: createRootRoute({+ component: () => (+ <SidebarProvider>+ <AppSidebar />+ </SidebarProvider>+ ),+ }),+ history: createMemoryHistory({ initialEntries: ["/"] }),+ });+ const view = render(+ <QueryClientProvider client={queryClient}>+ <RouterProvider router={router} />+ </QueryClientProvider>,+ );+ return { view, user: userEvent.setup({ document }) };+}++/** Label and address of every link in `root`, in document order. */+function links(root: HTMLElement) {+ return [...root.querySelectorAll("a[href]")].map((link) => ({+ label: link.textContent?.trim() ?? "",+ to: link.getAttribute("href"),+ }));+}++function expected(role: "admin" | "user", section: "primary" | "account") {+ return navigationFor(role)+ .filter((item) => item.section === section)+ .map((item) => ({ label: item.label, to: item.to }));+}++test.each(["user", "admin"] as const)(+ "the sidebar draws exactly the shared list for a %s",+ async (role) => {+ const { view, user } = renderSidebar(role);+ const footer = await waitFor(() => {+ const element = view.container.querySelector<HTMLElement>(+ '[data-sidebar="footer"]',+ );+ if (!element) throw new Error("No sidebar footer");+ return element;+ });+ expect(+ links(footer).map(({ label, to }) => ({+ label: label.replace(/\d+$/, ""),+ to,+ })),+ ).toEqual(expected(role, "primary"));+ // Bots keeps its count of what waits on the person, and only Bots has one.+ const badge = within(footer).getByRole("img", {+ name: "1 thing needs you",+ });+ expect(badge.closest("a")?.getAttribute("href")).toBe("/bots");++ await user.click(view.getByRole("button", { name: /Maya Chen/ }));+ const menu = await view.findByRole("menu");+ const items = within(menu)+ .getAllByRole("menuitem")+ .map((item) => item.textContent?.trim());+ expect(items).toEqual([+ ...expected(role, "account").map((item) => item.label),+ "Sign out",+ ]);+ expect(links(menu)).toEqual(expected(role, "account"));+ },+);++test("Admin is in the list for admins only", () => {+ const ids = (role: string | undefined) =>+ navigationFor(role).map((item) => item.id);+ expect(ids("admin")).toEqual(NAVIGATION.map((item) => item.id));+ expect(ids("user")).not.toContain("admin");+ expect(ids(undefined)).not.toContain("admin");+ expect(ids("user")).toEqual([+ "bots",+ "capabilities",+ "connections",+ "settings",+ ]);+});diff --git a/app/tests/arcade-index.test.tsx b/app/tests/arcade-index.test.tsxindex 02645b4c..5be7fbf5 100644--- a/app/tests/arcade-index.test.tsx+++ b/app/tests/arcade-index.test.tsx@@ -3,7 +3,7 @@ import type { PluginServer } from "@/lib/plugins/queries";import {brokeredAccountsListedOn,sharedAccountsListedOn,-} from "@/routes/_authed/_app/connections.index";+} from "@/lib/plugins/listed";/*** The Connected accounts index lists brokered rows from either broker. A deployment holds rows fromdiff --git a/app/tests/channel-pagination.test.tsx b/app/tests/channel-pagination.test.tsxindex 0c86fef6..7bebd07e 100644--- a/app/tests/channel-pagination.test.tsx+++ b/app/tests/channel-pagination.test.tsx@@ -167,6 +167,7 @@ function renderSidebar() {queryClient.setQueryData(userPreferencesQueryOptions("user").queryKey, {messageListEmphasis: "thread",selfHostBannerDismissed: false,+ skin: "openbot",});queryClient.setQueryData(authKeys.currentUser(), {id: "user",@@ -220,6 +221,7 @@ test("message emphasis updates mounted rows from the account preferences cache",clients[0]?.setQueryData(userPreferencesQueryOptions("user").queryKey, {messageListEmphasis: "agent",selfHostBannerDismissed: false,+ skin: "openbot",}),);await waitFor(() => expect(agent.className).toContain("text-[0.9rem]"));diff --git a/app/tests/composio-unconfigured-account.test.tsx b/app/tests/composio-unconfigured-account.test.tsxindex 6c45fcb5..bd03a166 100644--- a/app/tests/composio-unconfigured-account.test.tsx+++ b/app/tests/composio-unconfigured-account.test.tsx@@ -24,7 +24,7 @@ import {pluginKeys,} from "@/lib/plugins/queries";import { Route as ConnectedAccountRoute } from "@/routes/_authed/_app/connections.$key";-import { serversListedFor } from "@/routes/_authed/_app/connections.index";+import { serversListedFor } from "@/lib/plugins/listed";import { settleReactWork } from "./settle-react-work";/**diff --git a/app/tests/connected-accounts-list.test.tsx b/app/tests/connected-accounts-list.test.tsxindex 8c9fb5cc..a4b9b312 100644--- a/app/tests/connected-accounts-list.test.tsx+++ b/app/tests/connected-accounts-list.test.tsx@@ -1,6 +1,6 @@import { expect, test } from "bun:test";import type { PluginServer } from "@/lib/plugins/queries";-import { brokeredAccountsListedOn } from "@/routes/_authed/_app/connections.index";+import { brokeredAccountsListedOn } from "@/lib/plugins/listed";/*** Which brokered apps the Connected accounts page lists, decided without drawing anything.diff --git a/app/tests/self-host-banner.test.tsx b/app/tests/self-host-banner.test.tsxindex 50b42636..62cfb15b 100644--- a/app/tests/self-host-banner.test.tsx+++ b/app/tests/self-host-banner.test.tsx@@ -86,6 +86,7 @@ function setup({const preferences: UserPreferences = {messageListEmphasis: "thread",selfHostBannerDismissed: dismissed,+ skin: "openbot",};client.setQueryData(userPreferencesQueryOptions("alice").queryKey,diff --git a/app/tests/shared-connected-accounts.test.tsx b/app/tests/shared-connected-accounts.test.tsxindex a50e1543..f765583a 100644--- a/app/tests/shared-connected-accounts.test.tsx+++ b/app/tests/shared-connected-accounts.test.tsx@@ -16,7 +16,7 @@ import { brokeredFor } from "../src/routes/_authed/_app/connections.$key";import {brokeredAccountsListedOn,sharedAccountsListedOn,-} from "../src/routes/_authed/_app/connections.index";+} from "../src/lib/plugins/listed";beforeAll(() => GlobalRegistrator.register());afterEach(cleanup);diff --git a/app/tests/skin-slots.test.tsx b/app/tests/skin-slots.test.tsxnew file mode 100644index 00000000..2971eb61--- /dev/null+++ b/app/tests/skin-slots.test.tsx@@ -0,0 +1,353 @@+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 {+ type AnyRoute,+ createMemoryHistory,+ createRootRoute,+ createRoute,+ createRouter,+ Outlet,+ RouterProvider,+} from "@tanstack/react-router";+import { cleanup, render, waitFor } from "@testing-library/react";+import { Composer } from "@/components/channels/composer/composer";+import {+ DictationButton,+ DictationSurface,+} from "@/components/channels/composer/dictation-controls";+import { ConversationView } from "@/components/channels/conversation-view";+import { DetailPanel } from "@/components/layout/detail-panel";+import { PageShell } from "@/components/layout/page-shell";+import { SidebarProvider } from "@/components/ui/sidebar";+import { agentKeys } from "@/lib/agents/queries";+import { authKeys } from "@/lib/auth/queries";+import { Route as ChannelRoute } from "@/routes/_authed/_app/channel/$channelId";+import { Route as ChannelNewRoute } from "@/routes/_authed/_app/channel/new";+import { Route as GroupRoute } from "@/routes/_authed/_app/group/$channelId";+import { settleReactWork } from "./settle-react-work";++/*+ * Skins dress OpenBot's own elements through `data-slot` hooks, never through Tailwind classes or+ * copy, so restyling the composer or a header cannot silently undress every skin. These hold each+ * hook to the element it names, drawn by the real component or route. A hook that moves to another+ * element, or goes, fails here.+ *+ * The names are app-level and none is one of the names `components/ui` gives its primitives, which+ * the last test checks.+ */++class WideObserver implements ResizeObserver {+ constructor(private readonly callback: ResizeObserverCallback) {}+ // Room for a pane beside the page, so DetailPanel draws its pane rather than a sheet.+ observe(target: Element) {+ this.callback(+ [+ {+ target,+ contentRect: new DOMRect(0, 0, 1280, 800),+ borderBoxSize: [],+ contentBoxSize: [],+ devicePixelContentBoxSize: [],+ },+ ],+ this,+ );+ }+ unobserve() {}+ disconnect() {}+}++class OfflineWebSocket extends EventTarget {+ readyState = 0;+ onclose = null;+ onerror = null;+ onmessage = null;+ onopen = null;+ close() {}+ send() {}+}++const originalFetch = globalThis.fetch;+const originalObserver = globalThis.ResizeObserver;+const originalWebSocket = globalThis.WebSocket;++beforeAll(() => {+ GlobalRegistrator.register({ url: "http://localhost/" });+ globalThis.ResizeObserver = WideObserver;+ globalThis.WebSocket = OfflineWebSocket as unknown as typeof WebSocket;+});+beforeEach(() => {+ globalThis.fetch = Object.assign(+ async () => Response.json({ error: "not served" }, { status: 404 }),+ { preconnect: originalFetch.preconnect },+ );+});+afterEach(() => {+ cleanup();+ globalThis.fetch = originalFetch;+});+afterAll(async () => {+ await settleReactWork();+ globalThis.ResizeObserver = originalObserver;+ globalThis.WebSocket = originalWebSocket;+ GlobalRegistrator.unregister();+});++function slot(root: ParentNode, name: string): HTMLElement {+ const found = root.querySelectorAll<HTMLElement>(`[data-slot="${name}"]`);+ if (found.length === 0) throw new Error(`No [data-slot="${name}"]`);+ return found[0] as HTMLElement;+}++test("the composer's form, input, attach and send carry their hooks, in both layouts", () => {+ for (const compact of [true, false]) {+ const view = render(+ <Composer channelId="c-1" compact={compact} onSubmit={() => {}} />,+ );+ const composer = slot(view.container, "composer");+ expect(composer.tagName).toBe("FORM");++ const input = slot(composer, "composer-input");+ // The hook is ours, around prompt-area's editor: the editor is inside it and nothing else is.+ expect(+ input.querySelector('[role="textbox"][aria-label="Message"]'),+ ).not.toBeNull();+ expect(input.querySelector("button")).toBeNull();++ const attach = slot(composer, "composer-attach");+ expect(attach.tagName).toBe("BUTTON");+ expect(attach.getAttribute("aria-label")).toBe("Attach a file");++ const send = slot(composer, "composer-send");+ expect(send.tagName).toBe("BUTTON");+ expect(send.getAttribute("type")).toBe("submit");+ expect(send.getAttribute("aria-label")).toBe("Send message");+ cleanup();+ }+});++test("the composer's stop button carries its hook while a Bot is working", () => {+ const view = render(+ <Composer+ channelId="c-1"+ compact+ onStop={() => {}}+ onSubmit={() => {}}+ pending+ />,+ );+ const stop = slot(slot(view.container, "composer"), "composer-stop");+ expect(stop.tagName).toBe("BUTTON");+ expect(stop.getAttribute("aria-label")).toBe("Stop the Bot");+ expect(+ view.container.querySelector('[data-slot="composer-send"]'),+ ).toBeNull();+});++test("a conversation's composer sits in the composer column", () => {+ const view = render(+ <ConversationView channelId="c-1" messages={[]} onSubmit={() => {}} />,+ );+ const column = slot(view.container, "composer-column");+ expect(column.querySelector('form[data-slot="composer"]')).not.toBeNull();+ // The column holds the composer, not the transcript.+ expect(column.querySelector('[data-slot="message-scroller"]')).toBeNull();+});++test("the detail pane, its header and its title carry their hooks", () => {+ const view = render(+ <DetailPanel+ detail={<p>Browser preview</p>}+ onClose={() => {}}+ open+ title="Computer"+ >+ <p>Chat</p>+ </DetailPanel>,+ );+ const pane = slot(view.container, "detail-pane");+ expect(pane.textContent).toContain("Browser preview");+ expect(pane.textContent).not.toContain("Chat");+ const header = slot(pane, "detail-pane-header");+ expect(header.parentElement).toBe(pane);+ const title = slot(header, "detail-pane-title");+ expect(title.textContent).toBe("Computer");+ expect(header.querySelector('[aria-label="Close details"]')).not.toBeNull();+});++test("a page's header and title carry their hooks", async () => {+ const router = createRouter({+ routeTree: createRootRoute({+ component: () => (+ <PageShell description="How it works for you." title="Preferences">+ <p>Rows</p>+ </PageShell>+ ),+ }),+ history: createMemoryHistory({ initialEntries: ["/"] }),+ });+ const view = render(<RouterProvider router={router} />);+ const header = await waitFor(() => slot(view.container, "page-header"));+ expect(header.tagName).toBe("HEADER");+ const title = slot(header, "page-title");+ expect(title.tagName).toBe("H1");+ expect(title.textContent).toBe("Preferences");+ expect(header.textContent).toContain("How it works for you.");+});++/*+ * The conversation routes as the app registers them, under ids that match the file routes', so+ * each route's own `Route.useParams()` and `Route.useSearch()` resolve here as they do in the app.+ * Every request fails, which is enough: the header draws before anything has loaded.+ */+function conversationRoutes(path: string) {+ const root = createRootRoute({+ component: () => (+ <SidebarProvider>+ <Outlet />+ </SidebarProvider>+ ),+ });+ const authed = createRoute({+ id: "_authed",+ getParentRoute: () => root,+ component: Outlet,+ });+ const app = createRoute({+ id: "_app",+ getParentRoute: () => authed,+ component: Outlet,+ });+ const route = (path: string, file: AnyRoute) =>+ createRoute({+ path,+ getParentRoute: () => app,+ component: file.options.component,+ validateSearch: file.options.validateSearch,+ });+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ queryClient.setQueryData(authKeys.currentUser(), {+ id: "maya",+ email: "[email protected]",+ role: "user",+ onboarding: null,+ });+ queryClient.setQueryData(agentKeys.list(false), []);+ const router = createRouter({+ routeTree: root.addChildren([+ authed.addChildren([+ app.addChildren([+ route("channel/new", ChannelNewRoute as AnyRoute),+ route("channel/$channelId", ChannelRoute as AnyRoute),+ route("group/$channelId", GroupRoute as AnyRoute),+ ]),+ ]),+ ]),+ history: createMemoryHistory({ initialEntries: [path] }),+ });+ return render(+ <QueryClientProvider client={queryClient}>+ <RouterProvider router={router as never} />+ </QueryClientProvider>,+ );+}++test.each([+ ["a conversation with one Bot", "/channel/c-1", "Channel"],+ ["a group conversation", "/group/g-1", "Group"],+ ["a new conversation", "/channel/new", "To:"],+])("%s has its conversation header", async (_name, path, heading) => {+ const view = conversationRoutes(path);+ const header = await waitFor(() =>+ slot(view.container, "conversation-header"),+ );+ // One bar, across the top of the conversation, naming it.+ expect(+ view.container.querySelectorAll('[data-slot="conversation-header"]'),+ ).toHaveLength(1);+ expect(header.textContent).toContain(heading);+});++test("no app-level hook reuses a name the ui primitives give themselves", async () => {+ const { readdirSync, readFileSync } = await import("node:fs");+ const dir = new URL("../src/components/ui/", import.meta.url);+ const primitives = new Set<string>();+ for (const file of readdirSync(dir)) {+ const source = readFileSync(new URL(file, dir), "utf8");+ for (const match of source.matchAll(/data-slot="([\w-]+)"/g)) {+ primitives.add(match[1] as string);+ }+ }+ expect(primitives.size).toBeGreaterThan(50);+ const hooks = [+ "composer",+ "composer-input",+ "composer-attach",+ "composer-send",+ "composer-stop",+ "composer-dictate",+ "composer-dictate-cancel",+ "composer-dictate-stop",+ "composer-column",+ "conversation-header",+ "detail-pane",+ "detail-pane-header",+ "detail-pane-title",+ "page-header",+ "page-title",+ ];+ expect(hooks.filter((hook) => primitives.has(hook))).toEqual([]);+});++test("the dictation buttons carry their hooks while idle and while recording", () => {+ const session = {+ start: () => undefined,+ stop: () => undefined,+ cancel: () => undefined,+ retry: () => undefined,+ };+ const idle = render(+ <DictationButton+ dictation={+ { available: true, supported: true, busy: false, session } as never+ }+ disabled={false}+ />,+ );+ expect(+ idle.container.querySelector('[data-slot="composer-dictate"]'),+ ).not.toBeNull();+ cleanup();+ const recording = render(+ <DictationSurface+ canSend+ dictation={+ {+ available: true,+ supported: true,+ busy: true,+ state: { phase: "recording", seconds: 3, canRetry: false },+ session,+ } as never+ }+ >+ <span />+ </DictationSurface>,+ );+ expect(+ recording.container.querySelector('[data-slot="composer-dictate-cancel"]'),+ ).not.toBeNull();+ expect(+ recording.container.querySelector('[data-slot="composer-dictate-stop"]'),+ ).not.toBeNull();+});diff --git a/app/tests/skins-account.test.tsx b/app/tests/skins-account.test.tsxnew file mode 100644index 00000000..242bcb6e--- /dev/null+++ b/app/tests/skins-account.test.tsx@@ -0,0 +1,378 @@+import {+ afterAll,+ afterEach,+ beforeAll,+ beforeEach,+ expect,+ test,+} from "bun:test";+import { GlobalRegistrator } from "@happy-dom/global-registrator";+import type { UserPreferences } from "@openbot/shared/user-preferences";+import { QueryClientProvider } from "@tanstack/react-query";+import {+ createMemoryHistory,+ createRootRoute,+ createRoute,+ createRouter,+ Outlet,+ RouterProvider,+} from "@tanstack/react-router";+import { act, cleanup, render, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { signOutMutationOptions } from "@/lib/auth/mutations";+import { authKeys } from "@/lib/auth/queries";+import { appConfig } from "@/lib/generated/application-config";+import { userPreferencesQueryOptions } from "@/lib/settings/message-list";+import { queryClient } from "@/query-client";+import { Route as AppRoute } from "@/routes/_authed/_app";+import { Route as HomeRoute } from "@/routes/_authed/_app/index";+import { Route as ScreenRoute } from "@/routes/_authed/_app/s/$screen";+import { SkinAccountSync } from "@/skins/account-sync";+import { SKINS } from "@/skins/registry";+import { SkinPicker } from "@/skins/skin-picker";+import {+ clearSkin,+ getSkinId,+ SKIN_STORAGE_KEY,+ setSkin,+ useSkinId,+} from "@/skins/store";+import { settleReactWork } from "./settle-react-work";++/*+ * The skin is saved on the person's account. These drive it the way a person does: the picker on+ * Settings, a reload whose cached skin is not the account's, signing out on a shared machine, and+ * the account's skin changing under a screen only the old skin had. The API is a fake that answers+ * in the shapes OpenBot's endpoints send; the store, the sync, the picker and the routes are real.+ */++class OfflineWebSocket extends EventTarget {+ static readonly CONNECTING = 0;+ static readonly OPEN = 1;+ static readonly CLOSING = 2;+ static readonly CLOSED = 3;+ readyState = 0;+ onclose = null;+ onerror = null;+ onmessage = null;+ onopen = null;+ close() {}+ send() {}+}++type Sent = { method: string; path: string; body: unknown };++const alice = {+ id: "alice",+ name: "Alice Park",+ email: "[email protected]",+ role: "user" as const,+ onboarding: null,+};++function preferences(skin: UserPreferences["skin"]): UserPreferences {+ return {+ messageListEmphasis: "thread",+ selfHostBannerDismissed: true,+ skin,+ };+}++const originalFetch = globalThis.fetch;+const originalWebSocket = globalThis.WebSocket;+let sent: Sent[];+/** Answers keyed by `METHOD path`; anything else is a 404, as an unknown route is. */+let answers: Map<string, () => Promise<Response>>;++beforeAll(() => {+ GlobalRegistrator.register({ url: "http://localhost/" });+ globalThis.WebSocket = OfflineWebSocket as unknown as typeof WebSocket;+});+beforeEach(() => {+ sent = [];+ answers = new Map();+ globalThis.fetch = Object.assign(+ async (input: RequestInfo | URL, init?: RequestInit) => {+ const path = String(input).split("?")[0] ?? "";+ const method = init?.method ?? "GET";+ if (method !== "GET") {+ sent.push({+ method,+ path,+ body: init?.body ? JSON.parse(String(init.body)) : null,+ });+ }+ const answer = answers.get(`${method} ${path}`);+ if (answer) return answer();+ return Response.json({ error: "not served" }, { status: 404 });+ },+ { preconnect: originalFetch.preconnect },+ );+});+afterEach(async () => {+ cleanup();+ queryClient.clear();+ clearSkin();+ globalThis.fetch = originalFetch;+});+afterAll(async () => {+ await settleReactWork();+ globalThis.WebSocket = originalWebSocket;+ GlobalRegistrator.unregister();+});++function serve(key: string, body: unknown, status = 200) {+ answers.set(key, async () => Response.json(body, { status }));+}++function signedIn() {+ queryClient.setQueryData(authKeys.currentUser(), alice);+}++function cachedSkin() {+ return window.localStorage.getItem(SKIN_STORAGE_KEY);+}++function SkinProbe() {+ return <output aria-label="Drawn skin">{useSkinId()}</output>;+}++function renderSettings() {+ const view = render(+ <QueryClientProvider client={queryClient}>+ <SkinAccountSync />+ <SkinProbe />+ <SkinPicker />+ </QueryClientProvider>,+ );+ const user = userEvent.setup({ document });+ return { view, user };+}++test("picking a skin draws it at once and saves it on the account", async () => {+ signedIn();+ serve("GET /api/settings/preferences", {+ preferences: preferences("openbot"),+ });+ const save = Promise.withResolvers<Response>();+ answers.set("PATCH /api/settings/preferences", () => save.promise);+ const { view, user } = renderSettings();++ const picker = view.getByRole("combobox", { name: "Skin" });+ await waitFor(() => expect(picker.getAttribute("data-disabled")).toBeNull());+ // The default skin goes by the product's own name, whatever brand.yaml calls it.+ expect(picker.textContent).toContain(appConfig.brand.productName);++ await user.click(picker);+ const option = await view.findByRole("option", { name: /^OpenDots/ });+ // Each choice says what it is.+ expect(option.textContent).toContain(SKINS.opendots.description);+ await user.click(option);++ // Drawn before the server has answered.+ await waitFor(() =>+ expect(view.getByLabelText("Drawn skin").textContent).toBe("opendots"),+ );+ expect(document.documentElement.dataset.skin).toBe("opendots");+ expect(cachedSkin()).toBe("opendots");+ expect(sent).toEqual([+ {+ method: "PATCH",+ path: "/api/settings/preferences",+ body: { skin: "opendots" },+ },+ ]);++ await act(async () => {+ save.resolve(Response.json({ preferences: preferences("opendots") }));+ });+ await waitFor(() =>+ expect(+ queryClient.getQueryData<UserPreferences>(+ userPreferencesQueryOptions("alice").queryKey,+ )?.skin,+ ).toBe("opendots"),+ );+ expect(getSkinId()).toBe("opendots");+ expect(view.queryByRole("alert")).toBeNull();+});++test("a skin the account could not save is put back, and the picker says so", async () => {+ signedIn();+ setSkin("openduet");+ serve("GET /api/settings/preferences", {+ preferences: preferences("openduet"),+ });+ const save = Promise.withResolvers<Response>();+ answers.set("PATCH /api/settings/preferences", () => save.promise);+ const { view, user } = renderSettings();++ const picker = view.getByRole("combobox", { name: "Skin" });+ await waitFor(() => expect(picker.getAttribute("data-disabled")).toBeNull());+ await user.click(picker);+ await user.click(await view.findByRole("option", { name: /^OpenMuse/ }));+ await waitFor(() => expect(getSkinId()).toBe("openmuse"));++ await act(async () => {+ save.resolve(Response.json({ error: "Storage down" }, { status: 503 }));+ });+ expect((await view.findByRole("alert")).textContent).toContain(+ "Couldn't save that skin to your account, so OpenDuet is back.",+ );+ expect(view.getByLabelText("Drawn skin").textContent).toBe("openduet");+ expect(document.documentElement.dataset.skin).toBe("openduet");+ expect(cachedSkin()).toBe("openduet");+ expect(+ queryClient.getQueryData<UserPreferences>(+ userPreferencesQueryOptions("alice").queryKey,+ )?.skin,+ ).toBe("openduet");+});++test("the account's skin wins over a different one this browser cached", async () => {+ signedIn();+ // What a reload paints first: the cached skin, before the preferences have answered.+ setSkin("openmuse");+ const read = Promise.withResolvers<Response>();+ answers.set("GET /api/settings/preferences", () => read.promise);+ const { view } = renderSettings();+ expect(view.getByLabelText("Drawn skin").textContent).toBe("openmuse");++ await act(async () => {+ read.resolve(Response.json({ preferences: preferences("opendots") }));+ });+ await waitFor(() =>+ expect(view.getByLabelText("Drawn skin").textContent).toBe("opendots"),+ );+ expect(document.documentElement.dataset.skin).toBe("opendots");+ // And the cache now holds the account's skin, so the next reload paints it straight away.+ expect(cachedSkin()).toBe("opendots");+ // Applying what the account holds saves nothing back to it.+ expect(sent).toEqual([]);+});++test("signing out forgets the cached skin, so the next person starts from the default", async () => {+ signedIn();+ setSkin("openduet");+ expect(cachedSkin()).toBe("openduet");+ serve("POST /api/auth/sign-out", { success: true });++ // The one sign-out every menu uses: OpenBot's sidebar and each skin's own.+ await queryClient+ .getMutationCache()+ .build(queryClient, signOutMutationOptions(queryClient))+ .execute(undefined);++ expect(cachedSkin()).toBeNull();+ expect(document.documentElement.dataset.skin).toBeUndefined();+ expect(getSkinId()).toBe("openbot");+ expect(queryClient.getQueryData(authKeys.currentUser())).toBeUndefined();+});++test("a sign-out the server refused keeps the skin", async () => {+ signedIn();+ setSkin("openduet");+ serve("POST /api/auth/sign-out", { error: "Try again" }, 500);++ await expect(+ queryClient+ .getMutationCache()+ .build(queryClient, signOutMutationOptions(queryClient))+ .execute(undefined),+ ).rejects.toThrow();+ expect(cachedSkin()).toBe("openduet");+ expect(getSkinId()).toBe("openduet");+});++/*+ * `_authed/_app` and `/s/$screen` exactly as the app registers them: the active skin's Frame around+ * the page, and its own screen at `/s/<key>`. The route ids match the file routes', so the screen+ * route's own `Route.useParams()` resolves here as it does in the app.+ */+function renderApp(path: string) {+ const root = createRootRoute({+ component: () => (+ <>+ <SkinAccountSync />+ <Outlet />+ </>+ ),+ });+ const authed = createRoute({+ id: "_authed",+ getParentRoute: () => root,+ component: Outlet,+ });+ const app = createRoute({+ id: "_app",+ getParentRoute: () => authed,+ component: AppRoute.options.component,+ });+ const home = createRoute({+ path: "/",+ getParentRoute: () => app,+ component: HomeRoute.options.component,+ });+ const screen = createRoute({+ path: "s/$screen",+ getParentRoute: () => app,+ component: ScreenRoute.options.component,+ });+ const router = createRouter({+ routeTree: root.addChildren([+ authed.addChildren([app.addChildren([home, screen])]),+ ]),+ history: createMemoryHistory({ initialEntries: [path] }),+ });+ const view = render(+ <QueryClientProvider client={queryClient}>+ <RouterProvider router={router as never} />+ </QueryClientProvider>,+ );+ return { view, router };+}++/** `/` mounts the rich-text composer; see `agent-roster-error.test.tsx` on why it needs headroom. */+const HOME = { timeout: 5000 };++test("a skin switched while on a screen only the old skin has lands on home, drawn", async () => {+ const from = SKINS.openduet;+ const to = SKINS.opendots;+ const key = Object.keys(from.screens ?? {}).find(+ (screen) => !to.screens?.[screen],+ );+ if (!key) throw new Error("OpenDuet has no screen OpenDots lacks");++ signedIn();+ setSkin("openduet");+ queryClient.setQueryData(+ userPreferencesQueryOptions("alice").queryKey,+ preferences("openduet"),+ );+ serve("GET /api/agents", { agents: [] });+ serve("GET /api/channels", { channels: [], nextCursor: null });+ serve("GET /api/bots/attention", { bots: [] });+ const { view, router } = renderApp(`/s/${key}`);+ await waitFor(() =>+ expect(document.querySelector("[data-openduet-frame]")).not.toBeNull(),+ );+ expect(router.state.location.pathname).toBe(`/s/${key}`);++ // The person switched skins on another device; this tab's preferences catch up.+ act(() => {+ queryClient.setQueryData(+ userPreferencesQueryOptions("alice").queryKey,+ preferences("opendots"),+ );+ });++ await waitFor(() => expect(router.state.location.pathname).toBe("/"));+ expect(getSkinId()).toBe("opendots");+ expect(document.querySelector("[data-openduet-frame]")).toBeNull();+ // Home, inside the new skin's frame, with something on it.+ expect(+ // Home draws its composer; its greeting is personal, so it is not what this waits for.+ await view.findByRole("textbox", { name: "Message" }, HOME),+ ).toBeTruthy();+ expect(document.querySelector("[data-opendots-main]")).not.toBeNull();+});diff --git a/app/tests/skins-opendots-a11y.test.ts b/app/tests/skins-opendots-a11y.test.tsnew file mode 100644index 00000000..daa0188e--- /dev/null+++ b/app/tests/skins-opendots-a11y.test.ts@@ -0,0 +1,191 @@+import { describe, expect, test } from "bun:test";+import { readFileSync } from "node:fs";++/**+ * The OpenDots skin's colours and motion, read from its own stylesheet.+ *+ * Every text colour the skin draws must meet WCAG AA (4.5:1) on the surface it sits on, and every+ * icon 3:1 (WCAG 1.4.11), in light and in dark. OpenDots' own greys did not: its "YOUR WORKSPACE"+ * label measured 2.7:1 and its page description 3.0:1. The pairs below are the ones the frame and+ * its screens actually draw, so a token changed later is measured where it is used.+ */++const css = readFileSync(+ new URL("../src/skins/opendots/skin.css", import.meta.url),+ "utf8",+).replace(/\/\*[\s\S]*?\*\//g, "");++function tokens(selector: string): Record<string, string> {+ const start = css.indexOf(`${selector} {`);+ if (start < 0) throw new Error(`No ${selector} block`);+ const body = css.slice(start, css.indexOf("}", start));+ const found: Record<string, string> = {};+ for (const match of body.matchAll(/(--[\w-]+):\s*([^;]+);/g)) {+ found[match[1]] = match[2].trim();+ }+ return found;+}++const themes = {+ light: tokens(':root[data-skin="opendots"]'),+ dark: tokens(':root[data-skin="opendots"].dark'),+};++function channels(hex: string) {+ const value = hex.slice(1);+ return [0, 2, 4].map(+ (at) => Number.parseInt(value.slice(at, at + 2), 16) / 255,+ );+}++function luminance(hex: string) {+ const [r, g, b] = channels(hex).map((c) =>+ c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4,+ );+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;+}++/** The WCAG 2 contrast ratio of two opaque sRGB colours. */+export function contrast(a: string, b: string) {+ const [x, y] = [luminance(a), luminance(b)];+ return (Math.max(x, y) + 0.05) / (Math.min(x, y) + 0.05);+}++const TEXT = 4.5;+const ICON = 3;++/** [foreground token, the surface it sits on, minimum, where it is drawn] */+const PAIRS: Array<[string, string, number, string]> = [+ ["--foreground", "--background", TEXT, "page text"],+ ["--foreground", "--opendots-sidebar", TEXT, "product name"],+ ["--foreground", "--opendots-tab", TEXT, "computer pane tab"],+ ["--muted-foreground", "--background", TEXT, "muted text"],+ ["--muted-foreground", "--card", TEXT, "muted text on a card"],+ ["--muted-foreground", "--muted", TEXT, "muted text on muted"],+ ["--card-foreground", "--card", TEXT, "cards"],+ ["--popover-foreground", "--popover", TEXT, "menus"],+ ["--primary-foreground", "--primary", TEXT, "primary buttons"],+ ["--secondary-foreground", "--secondary", TEXT, "secondary buttons"],+ ["--accent-foreground", "--accent", TEXT, "hovered rows"],+ ["--destructive", "--background", TEXT, "errors"],+ ["--destructive", "--card", TEXT, "errors on a card"],+ ["--success", "--background", TEXT, "success text"],+ ["--sidebar-foreground", "--sidebar", TEXT, "Settings and Admin sidebars"],+ [+ "--sidebar-accent-foreground",+ "--sidebar-accent",+ TEXT,+ "their current row",+ ],+ ["--opendots-nav-ink", "--opendots-sidebar", TEXT, "conversation rows"],+ [+ "--opendots-nav-ink",+ "--opendots-hover",+ TEXT,+ "a hovered conversation row",+ ],+ ["--opendots-active-ink", "--opendots-active", TEXT, "the open conversation"],+ ["--opendots-dot-ink", "--opendots-sidebar", TEXT, "Bot and workspace rows"],+ [+ "--opendots-dot-ink",+ "--opendots-active",+ TEXT,+ "the current workspace row",+ ],+ ["--opendots-new-chat-ink", "--opendots-sidebar", TEXT, "New chat"],+ ["--opendots-label", "--opendots-sidebar", TEXT, "BOTS and RECENT CHATS"],+ ["--opendots-muted", "--opendots-sidebar", TEXT, "the signed-in name"],+ ["--opendots-muted", "--opendots-pane", TEXT, "Computer for"],+ ["--opendots-faint", "--opendots-sidebar", TEXT, "empty sidebar sections"],+ [+ "--opendots-tag-ink",+ "--opendots-sidebar",+ TEXT,+ "Bot name under a conversation",+ ],+ ["--opendots-crumb", "--opendots-topbar", TEXT, "breadcrumb"],+ ["--opendots-crumb-ink", "--opendots-topbar", TEXT, "current breadcrumb"],+ ["--opendots-pause-ink", "--opendots-topbar", TEXT, "Pause"],+ ["--opendots-eyebrow", "--background", TEXT, "YOUR WORKSPACE"],+ ["--opendots-note", "--background", TEXT, "page description"],+ ["--opendots-persona-ink", "--background", TEXT, "a Bot's role on its home"],+ ["--opendots-text-button", "--background", TEXT, "Edit Bot"],+ ["--opendots-avatar-ink", "--opendots-avatar", TEXT, "your initials"],+ ["--opendots-error-ink", "--opendots-sidebar", TEXT, "sidebar errors"],+ [+ "--opendots-user-bubble-ink",+ "--opendots-user-bubble",+ TEXT,+ "your messages",+ ],+ ["--opendots-assistant-ink", "--background", TEXT, "a Bot's messages"],+ ["--opendots-icon", "--opendots-sidebar", ICON, "sidebar icon buttons"],+ ["--opendots-icon", "--opendots-topbar", ICON, "the computer toggle"],+ ["--opendots-icon", "--opendots-pane", ICON, "closing the computer"],+ ["--opendots-rail-icon", "--opendots-rail", ICON, "rail icons"],+ ["--opendots-toggle-ink", "--opendots-topbar", ICON, "the sidebar toggle"],+ ["--opendots-menu-ink", "--opendots-topbar", ICON, "the phone menu button"],+ ["--opendots-teal", "--opendots-sidebar", ICON, "the unread dot"],+];++describe("OpenDots colours meet WCAG AA", () => {+ test("the measure agrees with WCAG's own examples", () => {+ expect(contrast("#000000", "#ffffff")).toBeCloseTo(21, 5);+ expect(contrast("#767676", "#ffffff")).toBeCloseTo(4.54, 2);+ });++ for (const [theme, values] of Object.entries(themes)) {+ test.each(PAIRS)(+ `${theme}: %s on %s reaches %d:1 (%s)`,+ (foreground, surface, minimum) => {+ const color = values[foreground];+ const ground = values[surface];+ expect(color).toMatch(/^#[0-9a-f]{6}$/i);+ expect(ground).toMatch(/^#[0-9a-f]{6}$/i);+ expect(contrast(color, ground)).toBeGreaterThanOrEqual(minimum);+ },+ );+ }+});++describe("OpenDots respects reduced motion", () => {+ const block = css.match(+ /@media \(prefers-reduced-motion: reduce\) \{([\s\S]*?\{[\s\S]*?\})\s*\}/,+ )?.[1];++ test("the frame's chrome and every popup it opens stop moving", () => {+ expect(block).toBeDefined();+ for (const target of [+ "[data-opendots-chrome]",+ "[data-opendots-chrome] *",+ '[data-slot="tooltip-content"]',+ '[data-slot="dropdown-menu-content"]',+ '[data-slot="context-menu-content"]',+ '[data-slot="select-content"]',+ '[data-slot="sheet-content"]',+ '[data-slot="sheet-overlay"]',+ '[data-slot="dialog-content"]',+ '[data-slot="dialog-overlay"]',+ ]) {+ expect(block).toContain(`:root[data-skin="opendots"] ${target}`);+ }+ expect(block).toMatch(/animation:\s*none;/);+ expect(block).toMatch(/transition:\s*none;/);+ });+});++describe("OpenDots reaches OpenBot's pages only through their hooks", () => {+ /*+ * A selector that names one of OpenBot's Tailwind classes (`form.rounded-2xl`, `.sticky.top-0`)+ * breaks without a test failing the day that page is restyled. Pages publish `data-slot` hooks+ * for skins instead; the only class a selector here may name is the theme's own `.dark`.+ */+ test("no selector names a class other than .dark", () => {+ const classes = [...css.matchAll(/[^{}]+\{/g)]+ .map((match) => match[0].slice(0, -1).trim())+ .filter((head) => !head.startsWith("@") && !head.startsWith("--"))+ .flatMap((head) => head.match(/\.[a-zA-Z_][\w-]*/g) ?? [])+ .filter((name) => name !== ".dark");+ expect(classes).toEqual([]);+ });+});diff --git a/app/tests/skins-opendots-frame.test.tsx b/app/tests/skins-opendots-frame.test.tsxnew file mode 100644index 00000000..11e7218d--- /dev/null+++ b/app/tests/skins-opendots-frame.test.tsx@@ -0,0 +1,657 @@+import {+ afterAll,+ afterEach,+ beforeAll,+ beforeEach,+ describe,+ expect,+ test,+} from "bun:test";+import { GlobalRegistrator } from "@happy-dom/global-registrator";+import { QueryClientProvider } from "@tanstack/react-query";+import {+ createMemoryHistory,+ createRootRoute,+ createRoute,+ createRouter,+ Outlet,+ RouterProvider,+} from "@tanstack/react-router";+import { cleanup, render, waitFor, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { AbstractAvatar } from "@/components/agents/abstract-avatar";+import { appConfig } from "@/lib/generated/application-config";+import { NAVIGATION, navigationFor } from "@/lib/navigation";+import { queryClient } from "@/query-client";+import { opendots } from "@/skins/opendots";+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";++/**+ * The OpenDots frame, drawn around a page the way `_authed/_app` draws it, against OpenBot's own+ * agent routes and the payloads OpenBot's endpoints send.+ *+ * What it holds the frame to: every OpenBot surface the default sidebar reaches is reachable from+ * it, Settings above all (it is where a skin is switched back); its Dots are OpenBot's Bots as the+ * agents route lists them; a Dot opens a chat with its Bot; and its computer toggle drives the+ * conversation's own computer pane rather than opening a second one.+ */++class OfflineWebSocket extends EventTarget implements WebSocket {+ static readonly CONNECTING = 0;+ static readonly OPEN = 1;+ static readonly CLOSING = 2;+ static readonly CLOSED = 3;+ readonly CONNECTING = 0;+ readonly OPEN = 1;+ readonly CLOSING = 2;+ readonly CLOSED = 3;+ binaryType: BinaryType = "blob";+ bufferedAmount = 0;+ extensions = "";+ protocol = "";+ readyState = 0;+ onclose: WebSocket["onclose"] = null;+ onerror: WebSocket["onerror"] = null;+ onmessage: WebSocket["onmessage"] = null;+ onopen: WebSocket["onopen"] = null;+ readonly url: string;+ constructor(url: string | URL) {+ super();+ this.url = String(url);+ }+ close() {}+ send() {}+}++type Actor = { id: string; email: string; role: "admin" | "user" };++const person: Actor = { id: "dana", email: "[email protected]", role: "user" };+const admin: Actor = { id: "ola", email: "[email protected]", role: "admin" };++function profile(+ id: string,+ name: string,+ overrides: Partial<AgentProfile> = {},+): AgentProfile {+ return {+ id,+ name,+ title: "Coworker",+ roleDescription: `${name} helps.`,+ // Unlike the id on purpose, so a test can tell which of the two an avatar was drawn from.+ avatarSeed: `seed-${id}`,+ ownerUserId: person.id,+ visibility: "private",+ systemOwned: false,+ hidden: false,+ pinned: false,+ deletedAt: null,+ endpoint: null,+ hasAuth: false,+ hasCallbackToken: false,+ ...overrides,+ };+}++function channel(+ id: string,+ agentIds: string[],+ overrides: Record<string, unknown> = {},+) {+ return {+ id,+ name: id,+ agentIds,+ threadId: id,+ active: true,+ lastMessageAt: "2026-10-20T10:00:00.000Z",+ summary: null,+ lastMessage: null,+ lastMessageAgentId: null,+ createdAt: "2026-10-01T00:00:00.000Z",+ pinned: false,+ lastReadAt: null,+ ...overrides,+ };+}++/** What each request asked for, so a test can say a write reached the server. */+const requests: Array<{ method: string; path: string }> = [];+let actor: Actor = person;+let bots: AgentProfile[] = [];+let channels: ReturnType<typeof channel>[] = [];+let agentsFail = false;+const paused = new Set<string>();++let originalFetch: typeof fetch;+let originalWebSocket: typeof WebSocket;++function agentRoutes() {+ const store = {+ list: async () => (agentsFail ? Promise.reject(new Error("down")) : bots),+ get: async (_actor: unknown, id: string) =>+ bots.find((bot) => bot.id === id) ?? null,+ } as unknown as AgentProfileStore;+ return createAgentRoutes(store, async (context, next) => {+ context.set("actor", actor);+ await next();+ });+}++/** OpenBot's endpoints, answering in the envelopes the browser reads them in. */+async function serve(path: string, init?: RequestInit): Promise<Response> {+ const method = init?.method ?? "GET";+ requests.push({ method, path });+ const url = new URL(path, "http://openbot.test");+ if (+ url.pathname === "/api/agents" ||+ url.pathname.startsWith("/api/agents/")+ ) {+ return agentRoutes().request(+ new Request(+ `http://openbot.test${url.pathname.slice("/api/agents".length)}${url.search}`,+ init,+ ),+ );+ }+ if (url.pathname === "/api/me") {+ return Response.json({+ user: { ...actor, name: "Dana Reyes", onboarding: null },+ });+ }+ if (url.pathname === "/api/channels") {+ return Response.json({ channels, nextCursor: null });+ }+ const one = url.pathname.match(/^\/api\/channels\/([^/]+)$/);+ if (one) {+ const found = channels.find((item) => item.id === one[1]);+ return found+ ? Response.json({ channel: found })+ : Response.json({ error: "Not found" }, { status: 404 });+ }+ if (url.pathname === "/api/routines") {+ return Response.json({+ routines: [],+ sweep: { lastSweptAt: null, working: true },+ });+ }+ if (url.pathname === "/api/memory") {+ return Response.json({ memories: [] });+ }+ if (url.pathname === "/api/bots/attention") {+ return Response.json({ bots: [] });+ }+ const lifecycle = url.pathname.match(+ /^\/api\/bots\/([^/]+)\/(lifecycle|pause|resume)$/,+ );+ if (lifecycle) {+ const id = decodeURIComponent(lifecycle[1]);+ if (lifecycle[2] === "pause") paused.add(id);+ if (lifecycle[2] === "resume") paused.delete(id);+ return Response.json({+ lifecycle: {+ agentId: id,+ paused: paused.has(id),+ pausedAt: null,+ notify: "all",+ },+ });+ }+ return Response.json({ error: "Not part of this test" }, { status: 404 });+}++beforeAll(() => {+ GlobalRegistrator.register({ url: "http://127.0.0.1:3112" });+ originalFetch = globalThis.fetch;+ originalWebSocket = globalThis.WebSocket;+ globalThis.WebSocket = OfflineWebSocket;+ globalThis.fetch = Object.assign(+ (input: RequestInfo | URL, init?: RequestInit) =>+ serve(String(input), init),+ { preconnect: originalFetch.preconnect },+ );+});++beforeEach(() => {+ requests.length = 0;+ actor = person;+ agentsFail = false;+ paused.clear();+ bots = [+ profile("ada", "Ada"),+ profile("brook", "Brook", { pinned: true }),+ profile("cass", "Cass", { ownerUserId: "someone", visibility: "public" }),+ ];+ channels = [+ channel("trip", ["brook"], { summary: "Planning the Lisbon trip" }),+ channel("standup", ["ada", "brook"], { summary: "Monday standup" }),+ ];+});++afterEach(() => {+ cleanup();+ // The app's one client, as the mutations invalidate it; each test starts from an empty cache.+ queryClient.clear();+});++afterAll(async () => {+ await settleReactWork();+ globalThis.fetch = originalFetch;+ globalThis.WebSocket = originalWebSocket;+ GlobalRegistrator.unregister();+});++/**+ * The frame around a stand-in page, at `path`, in a router whose every address is a page. The+ * frame is the registered skin's own, exactly what `_authed/_app` renders.+ */+function draw(path: string) {+ const Frame = opendots.Frame;+ if (!Frame) throw new Error("OpenDots has no frame");+ const root = createRootRoute({+ component: () => (+ <Frame>+ <Outlet />+ </Frame>+ ),+ });+ const page = createRoute({+ getParentRoute: () => root,+ path: "$",+ component: () => <p>OpenBot page</p>,+ });+ const index = createRoute({+ getParentRoute: () => root,+ path: "/",+ component: () => <p>OpenBot home</p>,+ });+ const router = createRouter({+ history: createMemoryHistory({ initialEntries: [path] }),+ routeTree: root.addChildren([index, page]),+ });+ const view = render(+ <QueryClientProvider client={queryClient}>+ <RouterProvider router={router} />+ </QueryClientProvider>,+ );+ const user = userEvent.setup({ document: view.baseElement.ownerDocument });+ return { view, router, user };+}++/** Every address the frame links to, as the browser would follow it. */+function hrefs(container: HTMLElement) {+ return new Set(+ [...container.querySelectorAll("a[href]")].map(+ (anchor) => anchor.getAttribute("href") ?? "",+ ),+ );+}++describe("OpenDots frame", () => {+ test("BOTS lists the Bots OpenBot's agent list returns, in the roster's order", async () => {+ const { view } = draw("/");+ const list = await view.findByRole("navigation", { name: "Your Bots" });+ await waitFor(() =>+ expect(within(list).getAllByTestId("opendots-bot")).toHaveLength(3),+ );+ // Pinned first, then the person's own, then shared with them: the Bots roster's own order.+ expect(+ within(list)+ .getAllByTestId("opendots-bot")+ .map((row) => row.textContent),+ ).toEqual(["Brook", "Ada", "Cass"]);+ expect(requests.some((request) => request.path === "/api/agents")).toBe(+ true,+ );+ });++ test("a Bot's row reopens its latest chat, starts one when there is none, and its settings open the Bot", async () => {+ const { view, router, user } = draw("/");+ const dots = await view.findByRole("navigation", { name: "Your Bots" });+ await within(dots).findByText("Ada");+ await waitFor(() =>+ expect(+ within(dots).getByText("Brook").closest("a")?.getAttribute("href"),+ ).toBe("/channel/trip"),+ );+ // Ada is only in a group, so choosing her starts a conversation with her alone.+ expect(+ within(dots).getByText("Ada").closest("a")?.getAttribute("href"),+ ).toBe("/channel/new?agent=ada");++ await user.click(within(dots).getByText("Ada"));+ await waitFor(() =>+ expect(router.state.location.href).toBe("/channel/new?agent=ada"),+ );+ await waitFor(() =>+ expect(view.getByTestId("opendots-crumb").textContent).toBe("Ada"),+ );++ await user.click(view.getByLabelText("Open Cass's settings"));+ await waitFor(() =>+ expect(router.state.location.pathname).toBe("/bots/cass"),+ );+ });++ test("a new conversation with a chosen Bot is OpenDots' coworker home", async () => {+ const { view } = draw("/channel/new?agent=ada");+ expect(await view.findByRole("heading", { name: "Ada" })).toBeTruthy();+ expect(view.getByText("Ada helps.")).toBeTruthy();+ expect(+ view.getByRole("link", { name: /Edit Bot/ }).getAttribute("href"),+ ).toBe("/bots/ada");+ cleanup();+ // Without a chosen Bot there is no one to introduce.+ const open = draw("/channel/new");+ await open.view.findByText("OpenBot page");+ expect(open.view.queryByRole("link", { name: /Edit Bot/ })).toBeNull();+ });++ test("every OpenBot surface is reachable from the frame", async () => {+ const { view } = draw("/");+ await view.findByText("Planning the Lisbon trip");+ await view.findByText("Cass");+ const links = hrefs(view.container);+ for (const href of [+ "/", // home+ "/channel/new", // new chat+ "/channel/trip", // a conversation with one Bot+ "/group/standup", // a group conversation+ "/bots", // Bots, where approvals, responsibilities and Team Bots now live+ "/bots?new=true", // creating a Bot+ "/bots/ada", // each Bot's own pages+ "/bots/brook",+ "/bots/cass",+ "/s/routines", // routines+ "/s/memories", // memory+ "/capabilities", // skills and memory+ "/connections",+ "/settings", // the skin picker, approvals and reachability+ ]) {+ expect(links).toContain(href);+ }+ // Admin is offered only to the people the server lets in.+ expect(links).not.toContain("/admin");+ expect(view.getByRole("button", { name: "Sign out" })).toBeTruthy();+ });++ test("on a phone the sidebar is a drawer, and every surface is in it", async () => {+ const viewport = (+ window as unknown as {+ happyDOM: {+ setViewport: (size: { width: number; height: number }) => void;+ };+ }+ ).happyDOM;+ viewport.setViewport({ width: 390, height: 844 });+ try {+ const { view, user } = draw("/");+ const menu = await view.findByRole("button", { name: "Open navigation" });+ // The drawer is shut until asked for, so the page has the screen.+ expect(view.queryByRole("navigation", { name: "Your Bots" })).toBeNull();+ await user.click(menu);+ const drawer = await view.findByRole("dialog");+ await within(drawer).findByText("Planning the Lisbon trip");+ const links = hrefs(drawer);+ for (const href of [+ "/channel/new",+ "/channel/trip",+ "/bots",+ "/s/routines",+ "/s/memories",+ "/capabilities",+ "/connections",+ "/settings",+ ]) {+ expect(links).toContain(href);+ }+ expect(+ within(drawer).getByRole("button", { name: "Sign out" }),+ ).toBeTruthy();+ } finally {+ viewport.setViewport({ width: 1024, height: 768 });+ }+ });++ test("the frame's chrome is marked, so reduced motion can still it", async () => {+ const { view } = draw("/");+ await view.findByRole("navigation", { name: "Your Bots" });+ for (const chrome of [+ view.getByRole("navigation", { name: "Workspace navigation" }),+ view.getByRole("complementary", { name: "Sidebar" }),+ view.getByRole("navigation", { name: "Breadcrumb" }).closest("header"),+ ]) {+ expect(chrome?.hasAttribute("data-opendots-chrome")).toBe(true);+ }+ });++ test.each([+ ["a member", person],+ ["an admin", admin],+ ])(+ "the rail and sidebar draw OpenBot's own navigation list for %s",+ async (_who, signedIn) => {+ actor = signedIn;+ const { view } = draw("/");+ const expected = navigationFor(signedIn.role);+ const rail = await view.findByRole("navigation", {+ name: "Workspace navigation",+ });+ await waitFor(() =>+ expect(+ within(rail).queryByRole("link", { name: "Settings" }),+ ).toBeTruthy(),+ );+ if (signedIn.role === "admin") {+ await waitFor(() =>+ expect(+ within(rail).queryByRole("link", { name: "Admin" }),+ ).toBeTruthy(),+ );+ }+ // Every destination OpenBot's sidebar offers this person, under its own label, and no others.+ for (const item of expected) {+ expect(+ within(rail)+ .getByRole("link", { name: item.label })+ .getAttribute("href"),+ ).toBe(item.to);+ }+ const railDestinations = within(rail)+ .getAllByRole("link")+ .map((link) => link.getAttribute("href"))+ .filter((href) => NAVIGATION.some((item) => item.to === href));+ expect(railDestinations).toEqual(expected.map((item) => item.to));+ const sidebar = view.getByRole("complementary", { name: "Sidebar" });+ for (const item of expected) {+ expect(hrefs(sidebar)).toContain(item.to);+ }+ },+ );++ test("an administrator also reaches Admin", async () => {+ actor = admin;+ const { view } = draw("/");+ await waitFor(() => expect(hrefs(view.container)).toContain("/admin"));+ });++ test.each([+ "/",+ "/channel/trip",+ "/group/standup",+ "/bots/ada/setup",+ "/s/routines",+ "/connections",+ ])(+ "Settings is reachable on %s, even when nothing else loads",+ async (path) => {+ agentsFail = true;+ channels = [];+ const { view } = draw(path);+ await view.findByText(/OpenBot (page|home)/);+ const settings = view+ .getAllByRole("link")+ .filter((link) => link.getAttribute("href") === "/settings");+ // In the rail and in the sidebar, so collapsing the sidebar never hides it.+ expect(settings.length).toBe(2);+ expect(+ within(view.getByRole("navigation", { name: "Workspace navigation" }))+ .getByRole("link", { name: "Settings" })+ .getAttribute("href"),+ ).toBe("/settings");+ },+ );++ test("on a conversation, the computer toggle opens the conversation's own computer pane", async () => {+ const { view, router, user } = draw("/channel/trip");+ const toggle = await view.findByRole("button", { name: "Show computer" });+ await user.click(toggle);+ await waitFor(() =>+ expect(router.state.location.search).toMatchObject({ watch: true }),+ );+ // No second screen: the frame's own pane stays shut where the page has one.+ expect(view.queryByTestId("opendots-computer-pane")).toBeNull();+ await user.click(+ await view.findByRole("button", { name: "Hide computer" }),+ );+ await waitFor(() =>+ expect(+ (router.state.location.search as { watch?: boolean }).watch,+ ).toBeUndefined(),+ );+ });++ test("elsewhere, the computer toggle opens OpenBot's computer for the Bot on screen", async () => {+ const { view, user } = draw("/bots/cass");+ await waitFor(() =>+ expect(view.getByTestId("opendots-crumb").textContent).toBe("Cass"),+ );+ await user.click(view.getByRole("button", { name: "Show computer" }));+ const pane = await view.findByTestId("opendots-computer-pane");+ expect(within(pane).getByText("Cass’s computer")).toBeTruthy();+ // OpenBot's own panel, not a copy of it.+ expect(+ within(pane).getByRole("region", { name: "Computer sidebar" }),+ ).toBeTruthy();+ await user.click(+ within(pane).getByRole("button", { name: "Close computer" }),+ );+ expect(view.queryByTestId("opendots-computer-pane")).toBeNull();+ });++ test("the Bot on screen can be paused and resumed from the top bar", async () => {+ const { view, user } = draw("/channel/new?agent=ada");+ await user.click(await view.findByRole("button", { name: "Pause Ada" }));+ expect(+ await view.findByRole("button", { name: "Resume Ada" }),+ ).toBeTruthy();+ expect(requests).toContainEqual({+ method: "POST",+ path: "/api/bots/ada/pause",+ });+ // A page about no one Bot offers no pause, since there would be nothing to say it applies to.+ cleanup();+ const elsewhere = draw("/connections");+ await elsewhere.view.findByText("OpenBot page");+ expect(+ elsewhere.view.queryByRole("button", { name: /^Pause / }),+ ).toBeNull();+ });+});++describe("OpenDots screens", () => {+ test("Routines is OpenBot's routines list under OpenDots' heading", async () => {+ const Screen = opendots.screens?.routines;+ if (!Screen) throw new Error("OpenDots has no routines screen");+ const view = render(+ <QueryClientProvider client={queryClient}>+ <Screen />+ </QueryClientProvider>,+ );+ expect(view.getByRole("heading", { name: "Routines" })).toBeTruthy();+ expect(await view.findByText("No routines yet")).toBeTruthy();+ });++ test("Memories is OpenBot's memory list under OpenDots' heading, with Remember a fact", async () => {+ const Screen = opendots.screens?.memories;+ if (!Screen) throw new Error("OpenDots has no memories screen");+ const view = render(+ <QueryClientProvider client={queryClient}>+ <Screen />+ </QueryClientProvider>,+ );+ expect(view.getByRole("heading", { name: "Memories" })).toBeTruthy();+ expect(await view.findByText("No memories yet")).toBeTruthy();+ expect(view.getByRole("button", { name: /Remember a fact/ })).toBeTruthy();+ });+});++/**+ * The skin is OpenDots' look, never its identity: whatever a person reads as the product is the+ * deployment's own name from `brand.yaml`, and every Bot wears OpenBot's own avatar.+ */+describe("OpenDots skin wears the deployment's brand", () => {+ /** What the drawing of one avatar looks like, without the ids React gives each instance. */+ const drawing = (root: Element | null) =>+ (root?.querySelector("svg")?.outerHTML ?? "").replace(/_r_[\w]+_/g, "");++ test("the frame names the product from brand.yaml and never says OpenDots or Dots", async () => {+ const { view } = draw("/channel/new?agent=ada");+ await view.findByRole("navigation", { name: "Your Bots" });+ await view.findByRole("heading", { name: "Ada" });+ const productName = appConfig.brand.productName;+ expect(view.getByTestId("opendots-wordmark").textContent).toBe(productName);+ expect(+ view.getAllByRole("link", { name: `${productName} home` }).length,+ ).toBe(2);+ const read = [+ view.container.textContent ?? "",+ ...[...view.container.querySelectorAll("[aria-label],[title],[alt]")].map(+ (element) =>+ [+ element.getAttribute("aria-label"),+ element.getAttribute("title"),+ element.getAttribute("alt"),+ ].join(" "),+ ),+ ].join(" ");+ expect(read).not.toContain("OpenDots");+ expect(read).not.toMatch(/\bDots?\b/);+ expect(view.getByText("BOTS")).toBeTruthy();+ expect(view.getByText("Bots", { selector: "span" })).toBeTruthy();+ // No plush, no monogram: nothing of OpenDots' own identity is drawn.+ expect(view.container.querySelector('img[src*="/skins/"]')).toBeNull();+ });++ test("every Bot wears OpenBot's own avatar, drawn from its avatarSeed", async () => {+ const { view } = draw("/channel/new?agent=ada");+ const list = await view.findByRole("navigation", { name: "Your Bots" });+ await waitFor(() =>+ expect(within(list).getAllByTestId("opendots-bot")).toHaveLength(3),+ );+ await view.findByRole("heading", { name: "Ada" });+ const persona = view.container.querySelector("[data-opendots-persona]");+ for (const bot of bots) {+ const reference = render(+ <AbstractAvatar name={bot.name} seed={bot.avatarSeed} size={30} />,+ );+ const row = within(list).getByText(bot.name).closest("a");+ expect(+ row?.querySelector(`[role="img"][aria-label="${bot.name}"]`),+ ).toBeTruthy();+ expect(drawing(row)).toBe(drawing(reference.container));+ // Drawn from the seed, not the id: the id would be a different Bot's face.+ const fromId = render(+ <AbstractAvatar name={bot.name} seed={bot.id} size={30} />,+ );+ expect(drawing(row)).not.toBe(drawing(fromId.container));+ reference.unmount();+ fromId.unmount();+ }+ const ada = render(<AbstractAvatar name="Ada" seed="seed-ada" size={64} />);+ expect(drawing(persona)).toBe(drawing(ada.container));+ });+});diff --git a/app/tests/skins-openduet-composer.test.ts b/app/tests/skins-openduet-composer.test.tsnew file mode 100644index 00000000..7d0aa7da--- /dev/null+++ b/app/tests/skins-openduet-composer.test.ts@@ -0,0 +1,47 @@+import { expect, test } from "bun:test";+import { readdirSync, readFileSync } from "node:fs";++/*+ * Found live: in OpenDuet's 430px column a conversation's composer ran flush to the screen's edges,+ * its focus ring on the edge, where OpenDuet floats it inset. The skin insets the column OpenBot+ * marks with the `composer-column` hook; this holds the two sides of that hook together, so a+ * change to either one fails here rather than silently putting the composer back on the edge.+ */++const read = (path: string) =>+ readFileSync(new URL(path, import.meta.url), "utf8");++test("OpenBot marks a conversation's composer column with its hook", () => {+ const view = read("../src/components/channels/conversation-view.tsx");+ expect(view).toMatch(+ /<div\s+className="[^"]*"\s+data-slot="composer-column"\s*>\s*\{notice\}\s*<Composer/,+ );+});++test("the OpenDuet skin insets that column, by the hook and only inside its frame", () => {+ const css = read("../src/skins/openduet/skin.css").replace(/\s+/g, " ");+ const rule = css.match(+ /\[data-skin="openduet"\] \[data-openduet-frame\] \[data-slot="composer-column"\] \{([^}]*)\}/,+ );+ expect(rule?.[1]).toContain("padding-inline: 12px");+ expect(css).not.toMatch(/\.px-0/);+});++/*+ * Found in review: the skin found OpenBot's controls by their accessible names, so rewording a+ * label for a screen reader silently broke the skin. No selector in the skin, in its stylesheet or+ * its code, may reach OpenBot's markup by an aria-label; it uses the data-slot hooks.+ */+test("no selector in the OpenDuet skin targets an aria-label", () => {+ const folder = new URL("../src/skins/openduet/", import.meta.url);+ const offenders = readdirSync(folder)+ .filter((name) => /\.(css|ts|tsx)$/.test(name))+ .flatMap((name) =>+ [+ ...readFileSync(new URL(name, folder), "utf8").matchAll(+ /\[aria-label[~|^$*]?=/g,+ ),+ ].map(() => name),+ );+ expect(offenders).toEqual([]);+});diff --git a/app/tests/skins-openduet-frame.test.tsx b/app/tests/skins-openduet-frame.test.tsxnew file mode 100644index 00000000..dca77f69--- /dev/null+++ b/app/tests/skins-openduet-frame.test.tsx@@ -0,0 +1,579 @@+import {+ afterAll,+ afterEach,+ beforeAll,+ describe,+ expect,+ test,+} from "bun:test";+import { GlobalRegistrator } from "@happy-dom/global-registrator";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import {+ createMemoryHistory,+ createRootRoute,+ createRoute,+ createRouter,+ Outlet,+ RouterProvider,+} from "@tanstack/react-router";+import {+ cleanup,+ fireEvent,+ render,+ waitFor,+ within,+} from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { PageShell } from "@/components/layout/page-shell";+import { appConfig } from "@/lib/generated/application-config";+import { navigationFor } from "@/lib/navigation";+import { SKINS } from "@/skins/registry";+import { settleReactWork } from "./settle-react-work";++/*+ * OpenDuet's frame replaces OpenBot's sidebar, so everything the sidebar reached has to be reachable+ * from it, and Settings above all, because the skin picker is there. And its Tasks screen draws only+ * OpenBot's own data, decided with OpenBot's own mutations. These render the skin exactly as+ * `_authed/_app` does (the registered skin's Frame around the page, its screen at `/s/tasks`)+ * against a fake of OpenBot's API that answers in the shapes the real endpoints return.+ */++beforeAll(() => GlobalRegistrator.register());+afterEach(cleanup);+afterAll(async () => {+ await settleReactWork();+ GlobalRegistrator.unregister();+});++const originalFetch = global.fetch;+const originalSocket = globalThis.WebSocket;+afterEach(() => {+ global.fetch = originalFetch;+ globalThis.WebSocket = originalSocket;+});++/** The frame keeps OpenBot's live socket open; here it never connects. */+class QuietSocket {+ onopen: unknown = null;+ onclose: unknown = null;+ onmessage: unknown = null;+ onerror: unknown = null;+ close() {}+ send() {}+}++type Sent = { method: string; path: string; body: unknown };++const now = "2026-10-27T10:00:00.000Z";++function channel(id: string, agentIds: string[], summary: string) {+ return {+ id,+ name: agentIds.length > 1 ? "Ops group" : "Inbox Bot",+ agentIds,+ threadId: `t-${id}`,+ active: true,+ lastMessageAt: now,+ summary,+ lastMessage: summary,+ lastMessageAgentId: null,+ createdAt: now,+ pinned: false,+ lastReadAt: now,+ };+}++function api(role: "admin" | "user") {+ const sent: Sent[] = [];+ const bodies: Record<string, unknown> = {+ "/api/me": {+ user: {+ id: "u-1",+ name: "Maya Chen",+ email: "[email protected]",+ role,+ onboarding: null,+ },+ },+ "/api/capabilities": { transcription: true },+ "/api/settings/preferences": {+ preferences: {+ messageListEmphasis: "thread",+ selfHostBannerDismissed: true,+ },+ },+ "/api/channels": {+ channels: [+ channel("c-1", ["b-1"], "Renewal for the studio policy"),+ channel("g-1", ["b-1", "b-2"], "Kiln repair plan"),+ ],+ nextCursor: null,+ },+ "/api/bots/attention": { bots: [] },+ "/api/agents": {+ agents: [+ { id: "b-1", name: "Inbox Bot" },+ { id: "b-2", name: "Ops Bot" },+ ],+ },+ "/api/approvals": {+ enabled: true,+ rules: [],+ teamRules: [],+ requests: [+ {+ id: "r-waiting",+ status: "pending",+ createdAt: now,+ action: {+ botId: "b-1",+ toolRef: "mcp/gmail/send_email",+ effect: "write",+ scope: "[email protected]",+ threadId: "t-c-1",+ args: { to: "[email protected]", body: "Thursday at 10 works." },+ target: null,+ policy: {+ behaviour: "ask",+ source: "rule",+ reason: "Sending mail asks first.",+ },+ },+ },+ {+ id: "r-decided",+ status: "allowed",+ createdAt: now,+ action: {+ botId: "b-1",+ toolRef: "mcp/drive/share",+ effect: "write",+ scope: "Quarterly plan",+ threadId: "t-c-1",+ args: {},+ target: null,+ },+ },+ ],+ questions: [+ {+ id: "q-1",+ botId: "b-2",+ threadId: "t-g-1",+ question: "Which kiln should I book the repair for?",+ createdAt: now,+ },+ ],+ },+ "/api/responsibilities": {+ responsibilities: [+ {+ id: "resp-on",+ agentId: "b-1",+ channelId: "c-1",+ threadId: "t-c-1",+ title: "Keep the support inbox at zero",+ instruction: "Answer what you can, hand me the rest.",+ successCriteria: "",+ status: "active",+ progress: "Answered 4 of 6 this morning",+ lastResult: null,+ subscriptions: [],+ updatedAt: now,+ },+ {+ id: "resp-paused",+ agentId: "b-1",+ channelId: "c-1",+ threadId: "t-c-1",+ title: "Chase overdue invoices",+ instruction: "",+ successCriteria: "",+ status: "paused",+ progress: "",+ lastResult: null,+ subscriptions: [],+ updatedAt: now,+ },+ ],+ },+ "/api/routines": {+ routines: [+ {+ id: "rt-on",+ agentId: "b-2",+ schedule: "Every weekday at 9:00",+ timezone: "UTC",+ instruction: "Post the standup notes",+ channel: { id: "g-1", name: "Ops group", gone: false },+ enabled: true,+ nextRunAt: "2026-10-28T09:00:00.000Z",+ lastRun: null,+ },+ {+ id: "rt-off",+ agentId: "b-2",+ schedule: "Every Monday at 8:00",+ timezone: "UTC",+ instruction: "Summarise last week's orders",+ channel: { id: "g-1", name: "Ops group", gone: false },+ enabled: false,+ nextRunAt: "2026-11-02T08:00:00.000Z",+ lastRun: null,+ },+ ],+ sweep: { lastSweptAt: now, working: true },+ },+ "/api/proactive/suggestions": {+ suggestions: [+ {+ id: "s-1",+ agentId: "b-1",+ title: "Confirm Friday ship date for the 120 mugs",+ detail: "Ana needs it confirmed by end of day.",+ sourceApp: "Gmail",+ sourceLink: null,+ createdAt: now,+ },+ ],+ },+ };+ global.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {+ const path = String(input).split("?")[0] ?? "";+ const method = init?.method ?? "GET";+ if (method !== "GET") {+ sent.push({+ method,+ path,+ body: init?.body ? JSON.parse(String(init.body)) : null,+ });+ return Response.json({ ok: true });+ }+ if (path in bodies) return Response.json(bodies[path]);+ return Response.json({ error: "not served" }, { status: 404 });+ }) as typeof fetch;+ globalThis.WebSocket = QuietSocket as unknown as typeof WebSocket;+ return sent;+}++/** OpenDuet around a page, as `_authed/_app` draws a skin's Frame, starting at `path`. */+function renderApp(path: string) {+ const skin = SKINS.openduet;+ const { Frame, screens } = skin;+ if (!Frame || !screens) throw new Error("OpenDuet has no frame");+ const rootRoute = createRootRoute({+ component: () => (+ <Frame>+ <Outlet />+ </Frame>+ ),+ });+ const page = (routePath: string, body: () => React.ReactNode) =>+ createRoute({+ path: routePath,+ getParentRoute: () => rootRoute,+ component: body,+ });+ const screenRoute = createRoute({+ path: "/s/$screen",+ getParentRoute: () => rootRoute,+ component: function SkinScreen() {+ const { screen } = screenRoute.useParams();+ const Screen = screens[screen];+ return Screen ? <Screen /> : null;+ },+ });+ const router = createRouter({+ routeTree: rootRoute.addChildren([+ page("/", () => <h1>Start a conversation</h1>),+ page("/bots", () => (+ <PageShell+ backButton={{ label: "Home", linkProps: { to: "/" } }}+ description="Your Bots and the ones shared with you."+ title="Bots"+ >+ <p>The roster</p>+ </PageShell>+ )),+ page("/channel/$channelId", () => <p>A conversation</p>),+ screenRoute,+ ]),+ history: createMemoryHistory({ initialEntries: [path] }),+ });+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return render(+ <QueryClientProvider client={client}>+ <RouterProvider router={router as never} />+ </QueryClientProvider>,+ );+}++/** Every address a link on screen goes to, the menu's included (it is portaled to the body). */+function hrefs(): string[] {+ return [...document.querySelectorAll("a[href]")].map(+ (anchor) => anchor.getAttribute("href") ?? "",+ );+}++async function openMenu(view: ReturnType<typeof render>) {+ fireEvent.click(await view.findByRole("button", { name: "Menu" }));+ const menu = await view.findByRole("navigation", { name: "Menu" });+ // Wait for the conversations, then open Manage.+ await within(menu).findByText("Renewal for the studio policy");+ fireEvent.click(within(menu).getByRole("button", { name: /Manage/ }));+ return menu;+}++describe("the frame reaches every OpenBot surface", () => {+ test("Chat, each conversation, and every page OpenBot's sidebar reached are one menu away", async () => {+ api("admin");+ const view = renderApp("/");+ await openMenu(view);+ const links = hrefs();+ for (const place of [+ "/",+ "/channel/c-1",+ "/group/g-1",+ "/channel/new",+ "/s/tasks",+ "/bots",+ "/capabilities",+ "/connections",+ "/admin",+ "/settings",+ ])+ expect(links).toContain(place);+ });++ /*+ * Found in review: the menu kept its own list of destinations beside OpenBot's sidebar. It draws+ * OpenBot's one navigation list now, so a destination added there reaches this menu too.+ */+ test("the menu's destinations are exactly OpenBot's navigation list, for admins and for everyone else", async () => {+ for (const role of ["admin", "user"] as const) {+ api(role);+ const view = renderApp("/");+ const menu = await openMenu(view);+ const manage = within(menu).getByRole("button", { name: /Manage/ });+ const group = document.getElementById(+ manage.getAttribute("aria-controls") ?? "",+ );+ const drawn = [...(group?.querySelectorAll("a") ?? [])].map((link) =>+ link.textContent?.replace(/\d+$/, "").trim(),+ );+ const settings = within(menu).getByRole("link", { name: "Settings" });+ expect([...drawn, settings.textContent?.trim()]).toEqual(+ navigationFor(role).map((item) => item.label),+ );+ view.unmount();+ }+ });++ test("Settings, which holds the skin picker, is on every tab without opening anything; Admin only for administrators", async () => {+ api("user");+ const view = renderApp("/");+ const settings = await view.findByRole("link", { name: "Your settings" });+ expect(settings.getAttribute("href")).toBe("/settings");+ await openMenu(view);+ const links = hrefs();+ expect(links.filter((href) => href === "/settings").length).toBe(2);+ expect(links).not.toContain("/admin");+ });++ /*+ * Found in review: the frame wrote an attribute onto the page's own heading, an element React+ * owns, and a page with its own back link showed two ways back. The chrome now reads the page's+ * `page-title` and its back link, writes nothing to either, and its one back disc goes where the+ * page's own link goes.+ */+ test("a page opened over the app names itself from its own title, writes nothing to it, and has one way back that goes where the page's does", async () => {+ api("user");+ const view = renderApp("/bots");+ const back = await view.findByRole("button", { name: "Back to Home" });+ expect(view.queryByRole("navigation", { name: "Main" })).toBeNull();+ expect(view.queryByRole("button", { name: "Menu" })).toBeNull();+ await waitFor(() =>+ expect(document.querySelector("header p[aria-hidden]")?.textContent).toBe(+ "Bots",+ ),+ );+ const title = document.querySelector('[data-slot="page-title"]');+ expect(title?.getAttributeNames().sort()).toEqual(["class", "data-slot"]);+ /*+ * The skin hides the page's own bar by its place beside the page-header hook+ * (`div:has(+ div > div > [data-slot="page-header"])`, which this DOM cannot evaluate): the+ * div just before the one holding the header's column. It is the bar with the page's back link.+ */+ const header = document.querySelector('[data-slot="page-header"]');+ const bar = header?.parentElement?.parentElement?.previousElementSibling;+ expect(bar?.tagName).toBe("DIV");+ expect(bar?.querySelector("a")?.textContent).toContain("Home");+ fireEvent.click(back);+ await view.findByRole("heading", { name: "Start a conversation" });+ });++ test("Chat and Tasks are phone-shaped, other pages keep OpenBot's width, and an open computer gets OpenBot's pane", async () => {+ api("user");+ const column = () =>+ document+ .querySelector("[data-openduet-column]")+ ?.getAttribute("data-openduet-column");+ for (const [path, expected] of [+ ["/", "phone"],+ ["/s/tasks", "phone"],+ ["/bots", "page"],+ ["/channel/c-1?watch=true", "pane"],+ ] as const) {+ const view = renderApp(path);+ await waitFor(() => expect(column()).toBe(expected));+ view.unmount();+ }+ });++ test("the Tasks tab counts what waits on the person", async () => {+ api("user");+ const view = renderApp("/");+ expect(+ await view.findByRole("link", { name: "Tasks, 2 waiting" }),+ ).toBeTruthy();+ });+});++/*+ * Found in review: Tasks re-implemented OpenBot's approvals, suggestions and routines, and the copies+ * had drifted. It now draws OpenBot's own lists, so these drive those lists through Tasks.+ */+describe("Tasks is OpenBot's own lists under OpenDuet's headings", () => {+ test("Active shows OpenBot's waiting list, responsibilities and routines, and every region has its own name", async () => {+ api("user");+ const view = renderApp("/s/tasks");+ fireEvent.click(await view.findByRole("tab", { name: "Active" }));+ const needs = await view.findByRole("region", { name: "Needs input" });+ expect(within(needs).getByText("Needs input")).toBeTruthy();+ expect(await within(needs).findByText(/Inbox Bot wants to/)).toBeTruthy();+ expect(within(needs).queryByText(/drive\/share/)).toBeNull();+ expect(+ within(needs).getByText(/Which kiln should I book the repair for\?/),+ ).toBeTruthy();+ // OpenBot's list always shows what the action would send.+ expect(within(needs).getByText(/Thursday at 10 works\./)).toBeTruthy();+ expect(+ await view.findByText("Keep the support inbox at zero"),+ ).toBeTruthy();+ const routines = view.getByRole("region", { name: "Routines" });+ expect(+ await within(routines).findByText("Post the standup notes"),+ ).toBeTruthy();+ const names = view+ .getAllByRole("region")+ .map((region) => region.getAttribute("aria-label"));+ expect(new Set(names).size).toBe(names.length);+ });++ test("an approval is decided in OpenBot's own row", async () => {+ const sent = api("user");+ const view = renderApp("/s/tasks");+ fireEvent.click(await view.findByRole("tab", { name: "Active" }));+ const needs = await view.findByRole("region", { name: "Needs input" });+ fireEvent.click(+ await within(needs).findByRole("button", { name: "Allow once" }),+ );+ await waitFor(() =>+ expect(sent).toContainEqual({+ method: "POST",+ path: "/api/approvals/r-waiting/decision",+ body: { decision: "allow_once" },+ }),+ );+ });++ test("a Bot's question is answered in OpenBot's own row", async () => {+ const sent = api("user");+ const view = renderApp("/s/tasks");+ fireEvent.click(await view.findByRole("tab", { name: "Active" }));+ const needs = await view.findByRole("region", { name: "Needs input" });+ await userEvent+ .setup({ document })+ .type(await within(needs).findByLabelText("Your answer"), "Kiln 2");+ const send = within(needs).getByRole("button", { name: "Send answer" });+ await waitFor(() => expect(send.hasAttribute("disabled")).toBe(false));+ fireEvent.click(send);+ await waitFor(() =>+ expect(sent).toContainEqual({+ method: "POST",+ path: "/api/approvals/questions/q-1/respond",+ body: { response: "Kiln 2" },+ }),+ );+ });++ test("Up next starts or dismisses a suggestion with OpenBot's own suggestion list", async () => {+ const sent = api("user");+ const view = renderApp("/s/tasks");+ fireEvent.click(await view.findByRole("tab", { name: "Up next" }));+ expect(+ await view.findByText("Confirm Friday ship date for the 120 mugs"),+ ).toBeTruthy();+ fireEvent.click(view.getByRole("button", { name: "Start as task" }));+ await waitFor(() =>+ expect(sent).toContainEqual({+ method: "POST",+ path: "/api/proactive/suggestions/s-1/start",+ body: null,+ }),+ );+ fireEvent.click(await view.findByRole("button", { name: "Dismiss" }));+ await waitFor(() =>+ expect(sent).toContainEqual({+ method: "POST",+ path: "/api/proactive/suggestions/s-1/dismiss",+ body: null,+ }),+ );+ });+});++/*+ * A skin takes OpenDuet's look and the deployment's identity: the name a person reads is the one in+ * brand.yaml, and the orb is OpenBot's own, never OpenDuet's name or its robot face.+ */+describe("the frame carries the deployment's brand, not OpenDuet's", () => {+ /** Every word a person can read or hear: the text, and the names and titles on controls. */+ function readable(): string {+ const named = [...document.querySelectorAll("[aria-label], [title], [alt]")]+ .flatMap((node) => [+ node.getAttribute("aria-label"),+ node.getAttribute("title"),+ node.getAttribute("alt"),+ ])+ .filter(Boolean);+ return `${document.body.textContent ?? ""}\n${named.join("\n")}`;+ }++ test("the menu and the orb name the deployment's product, and nothing says OpenDuet", async () => {+ api("admin");+ const view = renderApp("/");+ const orb = await view.findByRole("button", {+ name: `Talk to ${appConfig.brand.productName}`,+ });+ await openMenu(view);+ const menu = view.getByRole("dialog");+ expect(within(menu).getByText(appConfig.brand.productName)).toBeTruthy();+ expect(readable()).not.toContain("OpenDuet");+ // OpenBot's own orb, as sign-in and onboarding draw it, and no drawing of OpenDuet's.+ expect(orb.querySelector(".agent-orb")).not.toBeNull();+ expect(orb.querySelector("canvas")).toBeNull();+ });++ test("Tasks names nothing as OpenDuet either", async () => {+ api("user");+ const view = renderApp("/s/tasks");+ fireEvent.click(await view.findByRole("tab", { name: "Active" }));+ await view.findByRole("region", { name: "Needs input" });+ fireEvent.click(view.getByRole("tab", { name: "Up next" }));+ await view.findByRole("button", { name: "Start as task" });+ expect(readable()).not.toContain("OpenDuet");+ });+});diff --git a/app/tests/skins-openduet-model.test.tsx b/app/tests/skins-openduet-model.test.tsxnew file mode 100644index 00000000..c424ff18--- /dev/null+++ b/app/tests/skins-openduet-model.test.tsx@@ -0,0 +1,180 @@+import {+ afterAll,+ afterEach,+ beforeAll,+ describe,+ 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 { WaitingForYou } from "@/components/approvals/waiting";+import type { ApprovalInboxData } from "@/lib/approvals";+import {+ columnFor,+ conversationPath,+ isSkinScreen,+ tabForPath,+} from "@/skins/openduet/places";+import { waitingCount } from "@/skins/openduet/tasks-model";+import { settleReactWork } from "./settle-react-work";++/*+ * The rules OpenDuet's frame runs on. Which paths are tabs decides whether a screen has a tab bar+ * or a back disc; which column a path gets decides whether a page keeps OpenBot's width; and the+ * Tasks badge has to count exactly the rows OpenBot's own Needs input list draws.+ */++beforeAll(() => GlobalRegistrator.register());+afterEach(cleanup);+const originalFetch = global.fetch;+afterEach(() => {+ global.fetch = originalFetch;+});+afterAll(async () => {+ await settleReactWork();+ GlobalRegistrator.unregister();+});++describe("which tab a path is", () => {+ test("every conversation OpenBot draws is Chat", () => {+ for (const path of [+ "/",+ "/channel/new",+ "/channel/c-1",+ "/group/g-1",+ "/group/new",+ "/bot",+ "/channel/c-1/",+ ])+ expect(tabForPath(path)).toBe("chat");+ });++ test("the skin's Tasks screen is Tasks", () => {+ expect(tabForPath("/s/tasks")).toBe("tasks");+ expect(isSkinScreen("/s/tasks")).toBe(true);+ });++ test("every other page opens over the app, with no tab", () => {+ for (const path of [+ "/bots",+ "/bots/b-1",+ "/bots/b-1/responsibilities",+ "/routines",+ "/capabilities/skills",+ "/capabilities/memory",+ "/connections",+ "/channel/c-1/extra",+ ]) {+ expect(tabForPath(path)).toBeNull();+ expect(isSkinScreen(path)).toBe(false);+ }+ });++ test("a conversation with several Bots opens as a group", () => {+ expect(conversationPath({ id: "c", agentIds: ["a"] })).toBe("/channel/c");+ expect(conversationPath({ id: "g", agentIds: ["a", "b"] })).toBe(+ "/group/g",+ );+ });+});++/*+ * Found in review: the 430px column held every page, so a Bot's page, Admin and the computer were+ * squeezed into a phone's width on a wide screen. Only Chat and Tasks are phone-shaped now.+ */+describe("how wide the column is", () => {+ test("Chat and Tasks are a phone's width", () => {+ expect(columnFor("/")).toBe("phone");+ expect(columnFor("/channel/c-1")).toBe("phone");+ expect(columnFor("/s/tasks")).toBe("phone");+ });++ test("a conversation with its computer or its Bot's details open has room for OpenBot's pane", () => {+ expect(columnFor("/channel/c-1", { watch: true })).toBe("pane");+ expect(columnFor("/channel/c-1", { settings: true })).toBe("pane");+ expect(columnFor("/bot", { watch: true })).toBe("pane");+ });++ test("every other page keeps OpenBot's own width", () => {+ for (const path of [+ "/bots",+ "/bots/b-1",+ "/bots/b-1/setup",+ "/routines",+ "/capabilities/skills",+ "/connections",+ ])+ expect(columnFor(path)).toBe("page");+ });+});++const request = (+ id: string,+ status: string,+): ApprovalInboxData["requests"][number] => ({+ id,+ status,+ createdAt: "2026-10-27T10:00:00.000Z",+ action: {+ botId: "b-1",+ toolRef: "computer_run_command",+ effect: "write",+ scope: "workspace",+ threadId: "t-1",+ args: { command: "echo hello" },+ target: null,+ },+});++/*+ * Found in review: Tasks drew approvals with its own copy of OpenBot's list. It now draws OpenBot's+ * `WaitingForYou`, and the only thing the skin still works out is the badge's number. This renders+ * OpenBot's list against the same inbox and holds the two to the same count, so a change to what+ * the list shows fails here rather than leaving a badge that disagrees with the screen.+ */+test("the Tasks badge counts exactly what OpenBot's Needs input list draws", async () => {+ const inbox: ApprovalInboxData = {+ enabled: true,+ requests: [+ request("waiting", "pending"),+ request("allowed", "allowed"),+ request("denied", "denied"),+ ],+ rules: [],+ teamRules: [],+ questions: [+ {+ id: "q-1",+ botId: "b-1",+ threadId: "t-1",+ question: "Which kiln?",+ createdAt: "2026-10-27T10:00:00.000Z",+ },+ ],+ };+ global.fetch = (async (input: RequestInfo | URL) => {+ const path = String(input).split("?")[0];+ if (path === "/api/approvals") return Response.json(inbox);+ if (path === "/api/agents")+ return Response.json({ agents: [{ id: "b-1", name: "Ops Bot" }] });+ return Response.json({ error: "not served" }, { status: 404 });+ }) as typeof fetch;+ const view = render(+ <QueryClientProvider+ client={+ new QueryClient({ defaultOptions: { queries: { retry: false } } })+ }+ >+ <WaitingForYou />+ </QueryClientProvider>,+ );+ await waitFor(() =>+ expect(view.container.querySelectorAll('[data-slot="item"]').length).toBe(+ waitingCount(inbox),+ ),+ );+ expect(waitingCount(inbox)).toBe(2);+ expect(waitingCount(undefined)).toBe(0);+});diff --git a/app/tests/skins-openduet-motion.test.ts b/app/tests/skins-openduet-motion.test.tsnew file mode 100644index 00000000..0513de5f--- /dev/null+++ b/app/tests/skins-openduet-motion.test.ts@@ -0,0 +1,28 @@+import { expect, test } from "bun:test";+import { readdirSync, readFileSync } from "node:fs";++/*+ * Found in review: the skin's controls moved for people who asked their system for less motion.+ * Every class list in the skin that animates (a transition, a press that scales, a spin or pulse)+ * has to say what happens under `motion-reduce:` in the same list, so a new one cannot slip in+ * without it. The orb is OpenBot's `AgentOrb`, which reads the same preference itself.+ */++const folder = new URL("../src/skins/openduet/", import.meta.url);++const MOVES =+ /\b(transition(?:-[a-z]+)?|animate-[a-z-]+|active:scale-[\d.[\]]+)\b/;++test("every animated class list in the OpenDuet skin also says what reduced motion does", () => {+ const offenders: string[] = [];+ for (const file of readdirSync(folder).filter((name) =>+ name.endsWith(".tsx"),+ )) {+ const source = readFileSync(new URL(file, folder), "utf8");+ for (const [literal] of source.matchAll(/"[^"\n]*"/g)) {+ if (MOVES.test(literal) && !literal.includes("motion-reduce:"))+ offenders.push(`${file}: ${literal.slice(0, 80)}`);+ }+ }+ expect(offenders).toEqual([]);+});diff --git a/app/tests/skins-openduet-orb.test.tsx b/app/tests/skins-openduet-orb.test.tsxnew file mode 100644index 00000000..bb781d6a--- /dev/null+++ b/app/tests/skins-openduet-orb.test.tsx@@ -0,0 +1,157 @@+import { afterAll, afterEach, beforeAll, expect, mock, test } from "bun:test";+import { GlobalRegistrator } from "@happy-dom/global-registrator";+import { cleanup, render, waitFor } from "@testing-library/react";+import { Composer } from "@/components/channels/composer/composer";+import {+ DictationButton,+ DictationSurface,+} from "@/components/channels/composer/dictation-controls";+import type { DictationState } from "@/lib/dictation/session";+import {+ EDITOR_SELECTOR,+ pressOrb,+ useComposerPresence,+} from "@/skins/openduet/orb-dictation";+import { settleReactWork } from "./settle-react-work";++/*+ * OpenDuet's mic orb has no dictation of its own: it presses the composer's, by the names OpenBot's+ * dictation controls carry, so the recording, the waveform and the words landing in the draft are+ * all OpenBot's. These render OpenBot's real controls and press the orb over them, so a renamed+ * control fails here rather than leaving an orb that silently does nothing.+ */++beforeAll(() => GlobalRegistrator.register());+afterEach(cleanup);+afterAll(async () => {+ await settleReactWork();+ GlobalRegistrator.unregister();+});++function dictation(phase: DictationState["phase"]) {+ const session = {+ start: mock(async () => {}),+ finish: mock(async () => {}),+ cancel: mock(() => {}),+ retry: mock(async () => {}),+ };+ const state: DictationState = { phase, seconds: 3, canRetry: false };+ return {+ session,+ value: {+ session,+ state,+ available: true,+ supported: true,+ busy: phase !== "idle",+ } as never,+ };+}++test("pressing the orb starts the composer's own dictation", () => {+ const { session, value } = dictation("idle");+ const view = render(+ <DictationSurface canSend dictation={value}>+ <DictationButton dictation={value} disabled={false} />+ </DictationSurface>,+ );+ expect(pressOrb(view.container)).toBe("started");+ expect(session.start).toHaveBeenCalledTimes(1);+});++test("pressing the orb while the composer records stops it and puts the words in the draft", () => {+ const { session, value } = dictation("recording");+ const view = render(+ <DictationSurface canSend dictation={value}>+ <DictationButton dictation={value} disabled={false} />+ </DictationSurface>,+ );+ expect(pressOrb(view.container)).toBe("stopped");+ expect(session.finish).toHaveBeenCalledWith("draft");+ expect(session.start).not.toHaveBeenCalled();+});++test("where the composer cannot dictate, the orb presses nothing", () => {+ const { session, value } = dictation("idle");+ const view = render(<DictationButton dictation={value} disabled />);+ expect(pressOrb(view.container)).toBe("none");+ expect(session.start).not.toHaveBeenCalled();+});++test("with no composer on screen, the orb reports it has nothing to press", () => {+ const view = render(<p>Tasks</p>);+ expect(pressOrb(view.container)).toBe("none");+});++/** What the orb reads from the composer drawn inside it. */+function Presence({ root }: { root: HTMLElement | null }) {+ const presence = useComposerPresence(root);+ return (+ <output+ data-recording={presence.recording}+ data-working={presence.working}+ />+ );+}++/*+ * Found live: the orb rested while a Bot browsed with its computer, because it only read the+ * roster's busy flag, which comes over the socket and missed the person's own run. The composer+ * draws its Stop control for exactly as long as a turn runs, so the orb reads that.+ */+test("the orb reads the Bot as working for as long as the real composer offers to stop it", async () => {+ const host = document.createElement("div");+ document.body.append(host);+ const probe = render(<Presence root={host} />);+ const output = () => probe.container.querySelector("output");+ const composer = render(+ <Composer compact onStop={() => {}} onSubmit={() => {}} pending />,+ { container: host },+ );+ await waitFor(() => expect(output()?.dataset.working).toBe("true"), {+ timeout: 2_000,+ });+ composer.rerender(+ <Composer compact onStop={() => {}} onSubmit={() => {}} pending={false} />,+ );+ await waitFor(() => expect(output()?.dataset.working).toBe("false"));+ host.remove();+});++/*+ * Found live: opening any conversation flashed the orb's "Thinking" for half a second, because the+ * composer shows Stop for a moment while it checks for a turn already running. A Stop that comes+ * and goes that quickly is not the Bot working.+ */+test("a Stop the composer shows only for a moment does not make the orb think", async () => {+ const host = document.createElement("div");+ document.body.append(host);+ const probe = render(<Presence root={host} />);+ const output = () => probe.container.querySelector("output");+ const composer = render(+ <Composer compact onStop={() => {}} onSubmit={() => {}} pending />,+ { container: host },+ );+ await new Promise((resolve) => setTimeout(resolve, 200));+ composer.rerender(+ <Composer compact onStop={() => {}} onSubmit={() => {}} pending={false} />,+ );+ const seen = new Set<string | undefined>();+ for (let i = 0; i < 10; i++) {+ seen.add(output()?.dataset.working);+ await new Promise((resolve) => setTimeout(resolve, 100));+ }+ expect([...seen]).toEqual(["false"]);+ host.remove();+});++/*+ * The orb finds the composer by OpenBot's `composer-input` hook, and puts the caret in its editor+ * where it cannot dictate. This holds that selector to the real composer's editor.+ */+test("the orb finds the real composer's editor by its hook", () => {+ const view = render(<Composer compact onSubmit={() => {}} />);+ const editor = view.container.querySelector(EDITOR_SELECTOR);+ expect(editor).not.toBeNull();+ expect(editor?.getAttribute("aria-label")).toBe("Message");+});diff --git a/app/tests/skins-openmuse.test.tsx b/app/tests/skins-openmuse.test.tsxnew file mode 100644index 00000000..0a770081--- /dev/null+++ b/app/tests/skins-openmuse.test.tsx@@ -0,0 +1,1014 @@+import {+ afterAll,+ afterEach,+ beforeAll,+ describe,+ expect,+ test,+} from "bun:test";+import { GlobalRegistrator } from "@happy-dom/global-registrator";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import {+ createMemoryHistory,+ createRootRoute,+ createRoute,+ createRouter,+ Outlet,+ RouterProvider,+ useRouterState,+} from "@tanstack/react-router";+import {+ cleanup,+ fireEvent,+ render,+ waitFor,+ within,+} from "@testing-library/react";+import type { AgentProfile } from "@/lib/agents/queries";+import type { ApprovalInboxData } from "@/lib/approvals";+import type { BotActivity, BotAttention } from "@/lib/bot-lifecycle/queries";+import type { ChannelSummary } from "@/lib/channels/queries";+import { appConfig } from "@/lib/generated/application-config";+import type { MemoryRecord } from "@/lib/memory";+import { navigationFor } from "@/lib/navigation";+import type { PluginsPage } from "@/lib/plugins/queries";+import type { ProactiveSetting, ProactiveSuggestion } from "@/lib/proactive";+import type { ResponsibilityRecord } from "@/lib/responsibilities";+import type { RoutineRecord } from "@/lib/routines/queries";+import { openmuse } from "@/skins/openmuse";+import {+ chooseBot,+ chosenBotKey,+ forgetChosenBots,+} from "@/skins/openmuse/chosen-bot";+import { OpenMuseFrame } from "@/skins/openmuse/frame";+import {+ centreBot,+ mainChannel,+ statusLine,+ tabFor,+} from "@/skins/openmuse/model";+import { SKINS } from "@/skins/registry";++/*+ * The OpenMuse frame against OpenBot's own API shapes. Every payload below is what the server's+ * route returns, envelope and all, so the frame reads it through the same query factories the rest+ * of the app uses. What is checked is what a person sees and can reach.+ */++/** The deployment's own name, from brand.yaml. The skin never names itself. */+const PRODUCT = appConfig.brand.productName;++beforeAll(() => GlobalRegistrator.register());+afterAll(() => GlobalRegistrator.unregister());++const originalFetch = globalThis.fetch;+const originalSocket = globalThis.WebSocket;++afterEach(() => {+ cleanup();+ globalThis.fetch = originalFetch;+ globalThis.WebSocket = originalSocket;+ window.localStorage.clear();+ forgetChosenBots();+});++const now = new Date().toISOString();+const earlier = new Date(Date.now() - 3_600_000).toISOString();++function agent(+ overrides: Partial<AgentProfile> & { id: string },+): AgentProfile {+ return {+ avatarSeed: overrides.id,+ builtIn: true,+ canManage: true,+ endpoint: null,+ hasAuth: false,+ hasCallbackToken: false,+ hidden: false,+ pinned: false,+ mine: true,+ name: overrides.id,+ roleDescription: "",+ systemOwned: false,+ title: "",+ visibility: "private",+ ...overrides,+ };+}++function channel(+ overrides: Partial<ChannelSummary> & { id: string; agentIds: string[] },+): ChannelSummary {+ return {+ name: "Conversation",+ threadId: `thread-${overrides.id}`,+ active: true,+ lastMessageAt: earlier,+ summary: null,+ lastMessage: null,+ lastMessageAgentId: null,+ createdAt: earlier,+ pinned: false,+ lastReadAt: earlier,+ ...overrides,+ };+}++const scout = agent({ id: "scout", name: "Scout", title: "Research" });+// OpenBot's default Bot: `defaultAgentProfile` prefers the picked harness over list order.+const muse = agent({+ id: "picked-harness",+ name: "Muse",+ title: "Your helper",+});++const channels = [+ channel({+ id: "c-muse",+ agentIds: [muse.id],+ name: "Muse",+ summary: "Planning the week",+ }),+ channel({+ id: "c-scout",+ agentIds: [scout.id],+ name: "Scout",+ summary: "Competitor notes",+ busy: true,+ }),+ channel({+ id: "g-team",+ agentIds: [muse.id, scout.id],+ name: "Team",+ summary: "Launch plan",+ }),+];++const inbox: ApprovalInboxData = {+ enabled: true,+ rules: [],+ teamRules: [],+ questions: [],+ requests: [+ {+ id: "r-pending",+ status: "pending",+ createdAt: now,+ action: {+ botId: muse.id,+ toolRef: "computer_open_url",+ effect: "read",+ scope: "https://example.com",+ threadId: "thread-c-muse",+ args: { url: "https://example.com" },+ target: null,+ },+ },+ {+ id: "r-done",+ status: "consumed",+ createdAt: earlier,+ action: {+ botId: muse.id,+ toolRef: "send_email",+ effect: "write",+ scope: "mail",+ threadId: "thread-c-muse",+ args: {},+ target: null,+ },+ },+ ],+};++const attention: BotAttention[] = [+ {+ agentId: muse.id,+ name: muse.name,+ questions: 0,+ approvals: 1,+ handoffs: 0,+ unread: 0,+ paused: false,+ notify: "all",+ },+ {+ agentId: scout.id,+ name: scout.name,+ questions: 0,+ approvals: 0,+ handoffs: 0,+ unread: 1,+ paused: false,+ notify: "all",+ },+];++const activity: BotActivity = {+ inProgress: [+ {+ id: "a-live",+ kind: "routine",+ title: "Morning briefing",+ detail: "Reading the overnight news",+ status: "running",+ at: now,+ channelId: "c-muse",+ needsYou: false,+ stoppable: false,+ cancellable: false,+ },+ ],+ scheduled: [],+ completed: [+ {+ id: "a-done",+ kind: "handoff",+ title: "Draft the launch post",+ detail: null,+ status: "succeeded",+ at: earlier,+ channelId: null,+ needsYou: false,+ stoppable: false,+ cancellable: false,+ },+ ],+};++const settings: ProactiveSetting[] = [+ {+ id: "p-muse",+ agentId: muse.id,+ channelId: "c-muse",+ focus: "",+ enabled: true,+ intervalMinutes: 240,+ nextRunAt: now,+ lastRunAt: earlier,+ lastStatus: "succeeded",+ lastError: null,+ },+];++const suggestions: ProactiveSuggestion[] = [+ {+ id: "s-muse",+ agentId: muse.id,+ title: "Book a table for Friday dinner",+ detail: "Jamie asked about Friday.\nThe thread is in your inbox.",+ sourceApp: "Gmail",+ sourceLink: "https://mail.example.com/thread/1",+ createdAt: now,+ },+ {+ id: "s-scout",+ agentId: scout.id,+ title: "Compare pricing pages",+ detail: "A competitor changed theirs.",+ sourceApp: null,+ sourceLink: null,+ createdAt: now,+ },+];++const routines: RoutineRecord[] = [+ {+ id: "rt-1",+ agentId: muse.id,+ schedule: "Every weekday at 9:00",+ timezone: "Europe/London",+ instruction: "Send me the headlines",+ channel: { id: "c-muse", name: "Muse", gone: false },+ enabled: true,+ nextRunAt: now,+ lastRun: null,+ },+];++const responsibilities: ResponsibilityRecord[] = [+ {+ id: "g-1",+ agentId: muse.id,+ channelId: "c-muse",+ threadId: "thread-c-muse",+ title: "Keep my inbox at zero",+ instruction: "Triage new mail each morning",+ successCriteria: "Nothing unread by noon",+ status: "active",+ progress: "Down to 4 unread",+ lastResult: null,+ subscriptions: [],+ updatedAt: now,+ },+ {+ id: "g-scout",+ agentId: scout.id,+ channelId: "c-scout",+ threadId: "thread-c-scout",+ title: "Watch the competition",+ instruction: "",+ successCriteria: "",+ status: "active",+ progress: "",+ lastResult: null,+ subscriptions: [],+ updatedAt: now,+ },+];++const memories: MemoryRecord[] = [+ {+ id: "m-1",+ content: "Prefers morning meetings",+ provenance: "You told Muse",+ sourceId: null,+ enabled: true,+ reviewState: "confirmed",+ formedBy: "person",+ formedByAgentId: null,+ sourceApp: null,+ sourceLink: null,+ observedAt: null,+ updatedAt: earlier,+ },+];++const plugins: PluginsPage = {+ catalogue: [+ {+ key: "notion",+ title: "Notion",+ vendor: "Notion",+ summary: "Pages and databases",+ docsUrl: "",+ auth: "user-oauth",+ perInstance: false,+ },+ {+ key: "google-drive",+ title: "Google Drive",+ vendor: "Google",+ summary: "Files",+ docsUrl: "",+ auth: "user-oauth",+ perInstance: false,+ },+ ],+ servers: [+ { id: "notion" },+ { id: "google-drive" },+ ] as unknown as PluginsPage["servers"],+ skills: [],+ botsMayCallBack: false,+ redirectUri: null,+ composioConfigured: false,+ authorizesPerAction: false,+};++type Call = { method: string; path: string; body: unknown };++function serve(options: { role?: "admin" | "user"; userId?: string } = {}) {+ const calls: Call[] = [];+ const routes: Record<string, unknown> = {+ "/api/me": {+ user: {+ id: options.userId ?? "u-1",+ email: "[email protected]",+ name: "Alex Rivera",+ role: options.role ?? "admin",+ onboarding: null,+ },+ },+ "/api/agents": { agents: [scout, muse] },+ "/api/channels": { channels, nextCursor: null },+ "/api/approvals": inbox,+ "/api/bots/attention": { bots: attention },+ [`/api/bots/${muse.id}/activity`]: { activity },+ [`/api/bots/${scout.id}/activity`]: {+ activity: { inProgress: [], scheduled: [], completed: [] },+ },+ "/api/proactive/settings": { settings },+ "/api/proactive/suggestions": { suggestions },+ "/api/routines": {+ routines,+ sweep: { lastSweptAt: now, working: true },+ },+ "/api/responsibilities": { responsibilities },+ "/api/memory": { memories },+ "/api/plugins": plugins,+ "/api/plugins/connections": {+ connections: [{ serverId: "notion", holder: "person" }],+ redirectUri: null,+ },+ "/api/identity/links": { links: [] },+ "/api/identity/providers": { providers: { slack: false, github: false } },+ "/api/capabilities": {},+ "/api/settings/preferences": { preferences: {} },+ };+ globalThis.fetch = Object.assign(+ async (input: RequestInfo | URL, init?: RequestInit) => {+ const path = typeof input === "string" ? input : input.toString();+ const method = init?.method ?? "GET";+ calls.push({+ method,+ path,+ body: init?.body ? JSON.parse(String(init.body)) : undefined,+ });+ if (method !== "GET") return Response.json({ ok: true });+ const detail = path.match(/^\/api\/channels\/([^/?]+)$/);+ if (detail) {+ const found = channels.find((row) => row.id === detail[1]);+ return found+ ? Response.json({ channel: found })+ : Response.json({ error: "Not found" }, { status: 404 });+ }+ if (path in routes) return Response.json(routes[path]);+ return Response.json({ error: "Not here" }, { status: 404 });+ },+ { preconnect: originalFetch.preconnect },+ );+ // A socket that never opens: the roster is then exactly what the API returned.+ globalThis.WebSocket = class {+ close() {}+ } as unknown as typeof WebSocket;+ return calls;+}++/** The page under the frame. OpenBot's own pages are stood in for by their path. */+function Page() {+ const pathname = useRouterState({+ select: (state) => state.location.pathname,+ });+ return <p data-testid="page">OpenBot page {pathname}</p>;+}++function renderAt(path: string) {+ const root = createRootRoute({ component: Outlet });+ const app = createRoute({+ getParentRoute: () => root,+ id: "app",+ component: () => (+ <OpenMuseFrame>+ <Outlet />+ </OpenMuseFrame>+ ),+ });+ const skinScreen = createRoute({+ getParentRoute: () => app,+ path: "/s/$screen",+ component: function SkinScreen() {+ // The same lookup `/s/$screen` makes for the active skin.+ const { screen: key } = skinScreen.useParams();+ const Screen = openmuse.screens?.[key];+ return Screen ? <Screen /> : <Page />;+ },+ });+ const channelRoute = createRoute({+ getParentRoute: () => app,+ path: "/channel/$channelId",+ component: Page,+ });+ const anything = createRoute({+ getParentRoute: () => app,+ path: "$",+ component: Page,+ });+ const home = createRoute({+ getParentRoute: () => app,+ path: "/",+ component: Page,+ });+ const router = createRouter({+ routeTree: root.addChildren([+ app.addChildren([home, skinScreen, channelRoute, anything]),+ ]),+ history: createMemoryHistory({ initialEntries: [path] }),+ });+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ render(+ <QueryClientProvider client={queryClient}>+ <RouterProvider router={router} />+ </QueryClientProvider>,+ );+ return router;+}++/*+ * Testing Library's `screen` binds to the document that existed when it was imported, which is+ * before `beforeAll` registers happy-dom; this binds to the document of the moment instead.+ */+const page = () => within(document.body);++const hrefOf = (name: string | RegExp) =>+ page().getByRole("link", { name }).getAttribute("href");++async function openMenu() {+ fireEvent.click(+ await page().findByRole("button", { name: "Open conversations and menu" }),+ );+ return page().findByRole("dialog");+}++describe("OpenMuse is a registered skin with its own frame", () => {+ test("the registry hands OpenBot the frame and the three skin screens", () => {+ expect(SKINS.openmuse.Frame).toBe(OpenMuseFrame);+ // Apps is OpenBot's own Connections page, so the skin adds three screens, not four.+ expect(Object.keys(SKINS.openmuse.screens ?? {}).sort()).toEqual([+ "activity",+ "goals",+ "ideas",+ ]);+ });+});++describe("the frame", () => {+ test("centres OpenBot's default Bot, with what it is waiting on", async () => {+ serve();+ renderAt("/connections");+ const centre = await page().findByRole("button", {+ name: /^Muse, Ready to review · 1 approval\. Switch Bot$/,+ });+ expect(centre.textContent).toContain("Muse");+ expect(page().getByTestId("openmuse-status").textContent).toBe(+ "Ready to review · 1 approval",+ );+ // The bell carries the one pending approval.+ expect(+ page().getByRole("button", { name: "Needs you, 1 waiting" }),+ ).toBeTruthy();+ });++ test("a one-to-one conversation puts its own Bot at the centre", async () => {+ serve();+ renderAt("/channel/c-scout");+ await page().findByRole("button", { name: /^Scout, .*Switch Bot$/ });+ // Scout has a turn running in its channel; the line says so.+ await waitFor(() =>+ expect(page().getByTestId("openmuse-status").textContent).toBe(+ "Working on Competitor notes…",+ ),+ );+ expect(page().getByTestId("page").textContent).toBe(+ "OpenBot page /channel/c-scout",+ );+ });++ test("the five tabs lead to OpenBot's chat and the skin's own screens", async () => {+ serve();+ renderAt("/s/goals");+ const nav = await page().findByRole("navigation", { name: PRODUCT });+ const tabs = within(nav);+ // Chat is the centre Bot's main chat: its one-to-one conversation.+ await waitFor(() =>+ expect(+ tabs.getByRole("link", { name: "Chat" }).getAttribute("href"),+ ).toBe("/channel/c-muse"),+ );+ expect(+ tabs.getByRole("link", { name: "Activity" }).getAttribute("href"),+ ).toBe("/s/activity");+ expect(tabs.getByRole("link", { name: "Ideas" }).getAttribute("href")).toBe(+ "/s/ideas",+ );+ expect(+ tabs.getByRole("link", { name: "Goals" }).getAttribute("aria-current"),+ ).toBe("page");+ expect(tabs.getByRole("link", { name: "Apps" }).getAttribute("href")).toBe(+ "/connections",+ );+ });++ test.each([+ ["/s/activity", "Activity"],+ ["/s/ideas", "Ideas"],+ ["/s/goals", "Goals"],+ ["/connections", "Apps"],+ ["/channel/c-muse", "Chat"],+ ["/routines", null],+ ["/settings/approvals", null],+ ["/bots/scout/setup", null],+ ["/capabilities/memory", null],+ ])("on %s the current tab is %s", async (path, current) => {+ serve();+ renderAt(path);+ const nav = await page().findByRole("navigation", { name: PRODUCT });+ await within(nav).findByRole("link", { name: "Chat" });+ const marked = within(nav)+ .getAllByRole("link")+ .filter((link) => link.getAttribute("aria-current") === "page")+ .map((link) => link.getAttribute("aria-label"));+ expect(marked).toEqual(current ? [current] : []);+ });++ test.each([+ ["/s/goals", "column"],+ ["/connections", "column"],+ ["/channel/c-muse", "column"],+ // The Bot's computer open beside the conversation needs OpenBot's own width.+ ["/channel/c-muse?watch=true", "page"],+ ["/channel/c-muse?settings=true", "page"],+ ["/bots/scout/setup", "page"],+ ["/routines", "page"],+ ])("%s is drawn at the %s width", async (path, width) => {+ serve();+ renderAt(path);+ await page().findByRole("navigation", { name: PRODUCT });+ expect(+ document+ .querySelector(".openmuse-stage")+ ?.getAttribute("data-openmuse-width"),+ ).toBe(width);+ });++ test("the chosen Bot is remembered per person, not per machine", async () => {+ serve({ userId: "u-1" });+ renderAt("/s/activity");+ fireEvent.click(await page().findByRole("button", { name: /Switch Bot$/ }));+ fireEvent.click(+ within(await page().findByRole("dialog")).getByRole("button", {+ name: /Scout/,+ }),+ );+ await page().findByRole("button", { name: /^Scout, / });+ expect(window.localStorage.getItem(chosenBotKey("u-1"))).toBe(scout.id);+ cleanup();+ // The next person on this browser starts from OpenBot's default Bot.+ forgetChosenBots();+ serve({ userId: "u-2" });+ renderAt("/s/activity");+ await page().findByRole("button", { name: /^Muse, / });+ expect(window.localStorage.getItem(chosenBotKey("u-2"))).toBeNull();+ });++ test("Chat opens a new conversation with a Bot that has none yet", async () => {+ serve();+ chooseBot("u-1", scout.id);+ const roster = channels.filter((row) => row.id !== "c-scout");+ globalThis.fetch = (() => {+ const real = globalThis.fetch;+ return Object.assign(+ (input: RequestInfo | URL, init?: RequestInit) =>+ String(input) === "/api/channels"+ ? Promise.resolve(+ Response.json({ channels: roster, nextCursor: null }),+ )+ : real(input, init),+ { preconnect: originalFetch.preconnect },+ );+ })();+ renderAt("/s/ideas");+ const nav = await page().findByRole("navigation", { name: PRODUCT });+ await page().findByRole("button", { name: /^Scout, / });+ await waitFor(() =>+ expect(+ within(nav).getByRole("link", { name: "Chat" }).getAttribute("href"),+ ).toBe("/channel/new?agent=scout"),+ );+ });+});++describe("the frame wears the deployment's brand, not OpenMuse's", () => {+ /** Everything a person can read or hear: the text, and every name, label and alt text. */+ function readable() {+ const attributes = [...document.body.querySelectorAll("*")].flatMap(+ (element) =>+ ["aria-label", "alt", "title", "placeholder"]+ .map((name) => element.getAttribute(name))+ .filter((value): value is string => Boolean(value)),+ );+ return [document.body.textContent ?? "", ...attributes].join("\n");+ }++ function capybaras() {+ return [...document.body.querySelectorAll("img")].filter((image) =>+ /capybara|mascot/i.test(+ `${image.getAttribute("src")} ${image.getAttribute("alt")}`,+ ),+ );+ }++ test.each([+ "/",+ "/channel/c-muse",+ "/s/activity",+ "/s/ideas",+ "/s/goals",+ "/connections",+ ])(+ "%s shows the deployment's name, never OpenMuse, and no capybara",+ async (path) => {+ serve();+ renderAt(path);+ // The tab bar is named for the deployment, and so is the menu.+ await page().findByRole("navigation", { name: PRODUCT });+ const menu = within(await openMenu());+ expect(menu.getByRole("heading", { name: PRODUCT })).toBeTruthy();+ await menu.findByText("Planning the week");+ expect(readable()).toContain(PRODUCT);+ expect(readable()).not.toMatch(/openmuse/i);+ expect(capybaras()).toEqual([]);+ },+ );++ test("the centre Bot is drawn with its own OpenBot avatar", async () => {+ serve();+ renderAt("/connections");+ const centre = await page().findByRole("button", { name: /Switch Bot$/ });+ // AbstractAvatar names the drawing after the Bot, as on its OpenBot page.+ expect(within(centre).getByRole("img", { name: "Muse" })).toBeTruthy();+ expect(capybaras()).toEqual([]);+ });++ test("with no Bot yet, the deployment's name and mark stand at the centre", async () => {+ serve();+ const real = globalThis.fetch;+ globalThis.fetch = Object.assign(+ (input: RequestInfo | URL, init?: RequestInit) =>+ String(input) === "/api/agents"+ ? Promise.resolve(Response.json({ agents: [] }))+ : real(input, init),+ { preconnect: originalFetch.preconnect },+ );+ renderAt("/s/activity");+ const centre = await page().findByRole("button", { name: "Choose a Bot" });+ await waitFor(() => expect(centre.textContent).toContain(PRODUCT));+ expect(readable()).not.toMatch(/openmuse/i);+ expect(capybaras()).toEqual([]);+ });+});++describe("every OpenBot surface stays reachable", () => {+ // A row's name is its title and then its one line of detail, so each is matched from its start.+ const surfaces: [RegExp, string][] = [+ [/^Main chat/, "/channel/c-muse"],+ [/^New chat$/, "/channel/new?agent=picked-harness"],+ [/^New group$/, "/channel/new"],+ [/^Home$/, "/"],+ // OpenBot's own destinations, from the shared navigation list its sidebar draws.+ [/^Bots$/, "/bots"],+ [/^Capabilities$/, "/capabilities"],+ [/^Connections$/, "/connections"],+ [/^Admin$/, "/admin"],+ [/^Settings$/, "/settings"],+ ];++ test("the menu reaches every surface, every conversation and every group", async () => {+ serve({ role: "admin" });+ renderAt("/s/activity");+ const menu = within(await openMenu());+ await menu.findByText("Planning the week");+ for (const [name, href] of surfaces) {+ expect([+ String(name),+ menu.getByRole("link", { name }).getAttribute("href"),+ ]).toEqual([String(name), href]);+ }+ expect(+ menu+ .getByRole("link", { name: /Planning the week/ })+ .getAttribute("href"),+ ).toBe("/channel/c-muse");+ expect(+ menu.getByRole("link", { name: /Competitor notes/ }).getAttribute("href"),+ ).toBe("/channel/c-scout");+ expect(+ menu.getByRole("link", { name: /Launch plan/ }).getAttribute("href"),+ ).toBe("/group/g-team");+ });++ test.each(["admin", "user"] as const)(+ "the menu draws OpenBot's whole navigation list for a %s",+ async (role) => {+ serve({ role });+ renderAt("/s/goals");+ const menu = within(await openMenu());+ await menu.findByRole("link", { name: /^Settings$/ });+ for (const item of navigationFor(role)) {+ expect(+ menu+ .getByRole("link", { name: new RegExp(`^${item.label}$`) })+ .getAttribute("href"),+ ).toBe(item.to);+ }+ },+ );++ test("Admin is offered only to administrators", async () => {+ serve({ role: "user" });+ renderAt("/s/activity");+ const menu = within(await openMenu());+ await menu.findByRole("link", { name: /^Settings$/ });+ expect(menu.queryByRole("link", { name: /^Admin$/ })).toBeNull();+ });++ test.each([+ "/",+ "/channel/c-muse",+ "/s/activity",+ "/s/ideas",+ "/s/goals",+ "/connections",+ "/bots/scout/setup",+ ])("Settings is one tap behind the menu on %s", async (path) => {+ serve();+ const router = renderAt(path);+ const menu = within(await openMenu());+ const settings = await menu.findByRole("link", { name: /^Settings$/ });+ expect(settings.getAttribute("href")).toBe("/settings");+ fireEvent.click(settings);+ await waitFor(() =>+ expect(router.state.location.pathname).toBe("/settings"),+ );+ });++ test("the Bot switcher reaches each Bot's page, the roster and a new Bot", async () => {+ serve();+ renderAt("/connections");+ fireEvent.click(await page().findByRole("button", { name: /Switch Bot$/ }));+ const sheet = within(await page().findByRole("dialog"));+ expect(hrefOf(/^Muse's page/)).toBe("/bots/picked-harness");+ expect(+ sheet.getByRole("link", { name: /^All Bots/ }).getAttribute("href"),+ ).toBe("/bots");+ expect(+ sheet.getByRole("link", { name: /^New Bot/ }).getAttribute("href"),+ ).toBe("/bots?new=true");+ // A Bot that is waiting on the person says so; one with only unread messages does not.+ expect(sheet.getByText("Needs you · 1 approval")).toBeTruthy();+ expect(sheet.getByText("1 unread")).toBeTruthy();+ expect(sheet.queryByText(/Needs you · 1 unread/)).toBeNull();+ // Choosing Scout moves it to the centre.+ fireEvent.click(sheet.getByRole("button", { name: /Scout/ }));+ await page().findByRole("button", { name: /^Scout, / });+ });+});++describe("each tab is OpenBot's own sections for the centre Bot", () => {+ test("Activity shows what the Bot waits on you for, and its work", async () => {+ serve();+ renderAt("/s/activity");+ // OpenBot's Needs you section, with OpenBot's own approval and its details always shown.+ expect(await page().findByText("Muse wants to open url")).toBeTruthy();+ expect(page().getByText(/"url": "https:\/\/example.com"/)).toBeTruthy();+ // OpenBot's activity sections for the Bot.+ expect(await page().findByText("Morning briefing")).toBeTruthy();+ expect(page().getByText("Draft the launch post")).toBeTruthy();+ expect(page().getByRole("heading", { name: "In progress" })).toBeTruthy();+ expect(page().getByRole("heading", { name: "Completed" })).toBeTruthy();+ });++ test("Ideas shows only the centre Bot's suggestions and starts one through OpenBot", async () => {+ const calls = serve();+ renderAt("/s/ideas");+ expect(+ await page().findByText("Book a table for Friday dinner"),+ ).toBeTruthy();+ expect(page().queryByText("Compare pricing pages")).toBeNull();+ // OpenBot's own background-research section for the Bot sits under the suggestions.+ expect(+ page().getByRole("heading", { name: "Background research" }),+ ).toBeTruthy();+ fireEvent.click(page().getByRole("button", { name: "Start as task" }));+ await waitFor(() =>+ expect(+ calls.some(+ (call) =>+ call.method === "POST" &&+ call.path === "/api/proactive/suggestions/s-muse/start",+ ),+ ).toBe(true),+ );+ });++ test("Goals shows the centre Bot's routines and responsibilities", async () => {+ serve();+ renderAt("/s/goals");+ expect(await page().findByText("Send me the headlines")).toBeTruthy();+ expect(await page().findByText("Keep my inbox at zero")).toBeTruthy();+ expect(page().queryByText("Watch the competition")).toBeNull();+ });++ test("a routine is paused from Goals through OpenBot's own switch", async () => {+ const calls = serve();+ renderAt("/s/goals");+ fireEvent.click(+ await page().findByRole("switch", {+ name: "Enable the routine scheduled Every weekday at 9:00",+ }),+ );+ await waitFor(() =>+ expect(calls).toContainEqual({+ method: "PUT",+ path: "/api/routines/rt-1/enabled",+ body: { enabled: false },+ }),+ );+ });++ test("the bell lists what is waiting and decides through OpenBot's approvals", async () => {+ const calls = serve();+ renderAt("/s/goals");+ fireEvent.click(+ await page().findByRole("button", { name: "Needs you, 1 waiting" }),+ );+ const sheet = within(await page().findByRole("dialog"));+ expect(await sheet.findByText("Muse wants to open url")).toBeTruthy();+ // What it will send is always on screen, as in OpenBot.+ expect(sheet.getByText(/"url": "https:\/\/example.com"/)).toBeTruthy();+ expect(sheet.queryByText(/send email/)).toBeNull();+ fireEvent.click(sheet.getByRole("button", { name: "Allow once" }));+ await waitFor(() =>+ expect(calls).toContainEqual({+ method: "POST",+ path: "/api/approvals/r-pending/decision",+ body: { decision: "allow_once" },+ }),+ );+ });+});++describe("the rules the frame runs on", () => {+ test("the centre follows the conversation, then the choice, then OpenBot's default", () => {+ const agents = [scout, muse];+ expect(centreBot(agents, null, undefined)?.id).toBe(muse.id);+ expect(centreBot(agents, scout.id, undefined)?.id).toBe(scout.id);+ expect(centreBot(agents, muse.id, scout.id)?.id).toBe(scout.id);+ expect(centreBot(agents, "deleted-bot", undefined)?.id).toBe(muse.id);+ expect(centreBot([], null, undefined)).toBeUndefined();+ });++ test("a group is never a Bot's main chat", () => {+ expect(mainChannel(muse.id, channels)?.id).toBe("c-muse");+ expect(mainChannel("nobody", channels)).toBeUndefined();+ expect(+ mainChannel(+ muse.id,+ channels.filter((row) => row.id !== "c-muse"),+ ),+ ).toBeUndefined();+ });++ test("only a tab's own screen lights that tab", () => {+ expect(tabFor("/")).toBe("chat");+ expect(tabFor("/channel/new")).toBe("chat");+ expect(tabFor("/group/g-team")).toBe("chat");+ expect(tabFor("/s/activity")).toBe("activity");+ expect(tabFor("/s/ideas")).toBe("ideas");+ expect(tabFor("/s/goals")).toBe("goals");+ expect(tabFor("/connections")).toBe("apps");+ expect(tabFor("/connections/notion")).toBe("apps");+ expect(tabFor("/routines")).toBeNull();+ expect(tabFor("/settings/approvals")).toBeNull();+ expect(tabFor("/bots/scout/setup")).toBeNull();+ expect(tabFor("/capabilities/skills")).toBeNull();+ expect(tabFor("/s/apps")).toBeNull();+ });++ test("something waiting on the person outranks work in progress", () => {+ const busy = [+ channel({ id: "x", agentIds: ["b"], busy: true, summary: "Report" }),+ ];+ const base = {+ agentId: "b",+ name: "B",+ questions: 0,+ approvals: 0,+ handoffs: 0,+ unread: 0,+ paused: false,+ notify: "all" as const,+ };+ expect(+ statusLine({ attention: undefined, channels: busy, agentId: "b" }),+ ).toBe("Working on Report…");+ expect(+ statusLine({+ attention: { ...base, questions: 2 },+ channels: busy,+ agentId: "b",+ }),+ ).toBe("Needs your input · 2 questions");+ expect(+ statusLine({+ attention: { ...base, approvals: 1 },+ channels: busy,+ agentId: "b",+ }),+ ).toBe("Ready to review · 1 approval");+ expect(+ statusLine({+ attention: { ...base, paused: true },+ channels: [],+ agentId: "b",+ }),+ ).toBe("Paused");+ expect(statusLine({ attention: base, channels: [], agentId: "b" })).toBe(+ "Ready when you are",+ );+ });+});diff --git a/app/tests/skins.test.ts b/app/tests/skins.test.tsnew file mode 100644index 00000000..79936d25--- /dev/null+++ b/app/tests/skins.test.ts@@ -0,0 +1,144 @@+import { describe, expect, test } from "bun:test";+import { readFileSync } from "node:fs";+import { SKINS } from "../src/skins/registry";+import {+ applySkin,+ DEFAULT_SKIN,+ parseStoredSkin,+ reconcileSkin,+ SKIN_STORAGE_KEY,+} from "../src/skins/store";+import { SKIN_IDS } from "../src/skins/types";++const read = (path: string) =>+ readFileSync(new URL(path, import.meta.url), "utf8");++const skinned = SKIN_IDS.filter((id) => id !== DEFAULT_SKIN);++describe("skin preference", () => {+ test("a stored skin is used only when OpenBot ships it", () => {+ for (const id of SKIN_IDS) expect(parseStoredSkin(id)).toBe(id);+ expect(parseStoredSkin(null)).toBe(DEFAULT_SKIN);+ expect(parseStoredSkin("")).toBe(DEFAULT_SKIN);+ expect(parseStoredSkin("retired-skin")).toBe(DEFAULT_SKIN);+ });++ test("choosing a skin stores it and names it on the document", () => {+ const writes: Array<[string, string]> = [];+ const roots: Array<string | null> = [];+ const effects = {+ setStoredValue: (key: string, value: string) => writes.push([key, value]),+ setRootSkin: (id: string | null) => roots.push(id),+ };++ applySkin("opendots", effects);+ applySkin(DEFAULT_SKIN, effects);++ expect(writes).toEqual([+ [SKIN_STORAGE_KEY, "opendots"],+ [SKIN_STORAGE_KEY, DEFAULT_SKIN],+ ]);+ // The default clears the attribute, so no skin's rules can match OpenBot's own look.+ expect(roots).toEqual(["opendots", null]);+ });++ test("a skin this build no longer ships is cleared from the document on load", () => {+ const roots: Array<string | null> = [];+ const setRootSkin = (id: string | null) => roots.push(id);++ expect(reconcileSkin("retired-skin", { setRootSkin })).toBe(DEFAULT_SKIN);+ expect(reconcileSkin("openmuse", { setRootSkin })).toBe("openmuse");+ expect(roots).toEqual([null, "openmuse"]);+ });++ test("every skin is registered under its own id", () => {+ for (const id of SKIN_IDS) expect(SKINS[id].id).toBe(id);+ });+});++describe("pre-paint skin boot", () => {+ const html = read("../index.html");++ test("the boot script reads the same storage key the app writes", () => {+ expect(html).toContain(SKIN_STORAGE_KEY);+ expect(html).toContain("dataset.skin");+ });+});++/*+ * Top-level rules of a stylesheet, with the selectors of rules nested in `@media` or `@supports`+ * flattened in, and the at-rules that hold no selectors (`@keyframes`, `@font-face`, `@theme`,+ * `@property`) left out.+ */+function selectors(css: string): string[] {+ const text = css.replace(/\/\*[\s\S]*?\*\//g, "");+ const found: string[] = [];+ let depth = 0;+ let start = 0;+ for (let i = 0; i < text.length; i++) {+ if (text[i] === "{") {+ if (depth === 0) {+ const head = text.slice(start, i).trim();+ const close = matching(text, i);+ if (/^@(media|supports|layer)\b/.test(head)) {+ found.push(...selectors(text.slice(i + 1, close)));+ } else if (!head.startsWith("@")) {+ found.push(head);+ }+ i = close;+ start = close + 1;+ continue;+ }+ depth++;+ } else if (text[i] === ";" && depth === 0) {+ start = i + 1;+ }+ }+ return found;+}++function matching(text: string, open: number) {+ let depth = 0;+ for (let i = open; i < text.length; i++) {+ if (text[i] === "{") depth++;+ if (text[i] === "}" && --depth === 0) return i;+ }+ throw new Error("Unbalanced braces");+}++function declaredTokens(css: string, selector: string) {+ const text = css.replace(/\/\*[\s\S]*?\*\//g, "");+ const tokens = new Set<string>();+ for (const block of text.matchAll(/([^{}]+)\{([^{}]*)\}/g)) {+ const heads = block[1].split(",").map((head) => head.trim());+ if (!heads.includes(selector)) continue;+ for (const token of block[2].matchAll(/(--[\w-]+)\s*:/g)) {+ tokens.add(token[1]);+ }+ }+ return tokens;+}++describe("skin stylesheets", () => {+ const index = read("../src/skins/skins.css");++ test.each(skinned)("%s is loaded", (id) => {+ expect(index).toContain(`./${id}/skin.css`);+ });++ test.each(skinned)("%s styles nothing while another skin is active", (id) => {+ const css = read(`../src/skins/${id}/skin.css`);+ for (const selector of selectors(css)) {+ for (const part of selector.split(",")) {+ expect(part).toContain(`[data-skin="${id}"]`);+ }+ }+ });++ test.each(skinned)("%s sets every light token for dark too", (id) => {+ const css = read(`../src/skins/${id}/skin.css`);+ const light = declaredTokens(css, `:root[data-skin="${id}"]`);+ const dark = declaredTokens(css, `:root[data-skin="${id}"].dark`);+ expect([...light].filter((token) => !dark.has(token))).toEqual([]);+ });+});diff --git a/app/tests/user-preferences.test.tsx b/app/tests/user-preferences.test.tsxindex 6b0ddf79..a2075f7e 100644--- a/app/tests/user-preferences.test.tsx+++ b/app/tests/user-preferences.test.tsx@@ -99,6 +99,7 @@ test("successful writes update only the current account cache; failures preserveclient.setQueryData(bobKey, {messageListEmphasis: "agent",selfHostBannerDismissed: false,+ skin: "opendots",});const mutation = client.getMutationCache()@@ -108,6 +109,7 @@ test("successful writes update only the current account cache; failures preservepreferences: {messageListEmphasis: "thread",selfHostBannerDismissed: false,+ skin: "openbot",},});await mutation.execute({ messageListEmphasis: "thread" });@@ -124,6 +126,7 @@ test("successful writes update only the current account cache; failures preserveexpect(client.getQueryData<UserPreferences>(bobKey)).toEqual({messageListEmphasis: "agent",selfHostBannerDismissed: false,+ skin: "opendots",});response = async () =>Response.json({ error: "Could not save" }, { status: 500 });@@ -134,5 +137,9 @@ test("successful writes update only the current account cache; failures preserveclient.getQueryData<UserPreferences>(userPreferencesQueryOptions("alice").queryKey,),- ).toEqual({ messageListEmphasis: "thread", selfHostBannerDismissed: false });+ ).toEqual({+ messageListEmphasis: "thread",+ selfHostBannerDismissed: false,+ skin: "openbot",+ });});diff --git a/server/src/user-preferences-routes.ts b/server/src/user-preferences-routes.tsindex 39792c31..0f6cddd8 100644--- a/server/src/user-preferences-routes.ts+++ b/server/src/user-preferences-routes.ts@@ -1,4 +1,5 @@import { Hono, type MiddlewareHandler } from "hono";+import { SKIN_IDS } from "@openbot/shared/user-preferences";import { z } from "zod";import type { AppVariables } from "./auth/guards";import type { UserPreferencesStore } from "./user-preferences";@@ -12,6 +13,7 @@ const preferencesPatch = z.strictObject({messageListEmphasis: z.enum(["agent", "thread"]).optional(),selfHostBannerDismissed: z.boolean().optional(),+ skin: z.enum(SKIN_IDS).optional(),}).refine((patch) => Object.keys(patch).length > 0);@@ -43,8 +45,7 @@ export function userPreferencesRoutes(if (!parsed.success) {return context.json({- error:- "Choose agent or thread for message list emphasis, or true or false for the self-host banner.",+ error: `Choose agent or thread for message list emphasis, true or false for the self-host banner, or one of these skins: ${SKIN_IDS.join(", ")}.`,},400,);diff --git a/server/src/user-preferences.ts b/server/src/user-preferences.tsindex 4fd186d5..d1ad4dda 100644--- a/server/src/user-preferences.ts+++ b/server/src/user-preferences.ts@@ -1,11 +1,23 @@import { eq, sql } from "drizzle-orm";import {DEFAULT_USER_PREFERENCES,+ isSkinId,type UserPreferences,} from "@openbot/shared/user-preferences";import type { Database } from "./db/client";import { users } from "./db/schema";+/*+ * What is stored, over the defaults. A skin a later build no longer ships stays in the row, so going+ * back to a build that has it brings it back, but this build answers with its default.+ */+function withDefaults(stored: Partial<UserPreferences>): UserPreferences {+ const preferences = { ...DEFAULT_USER_PREFERENCES, ...stored };+ return isSkinId(preferences.skin)+ ? preferences+ : { ...preferences, skin: DEFAULT_USER_PREFERENCES.skin };+}+export type UserPreferencesStore = {read: (userId: string) => Promise<UserPreferences>;patch: (@@ -25,7 +37,7 @@ export function createUserPreferencesStore(.where(eq(users.id, userId)).limit(1);if (!user) throw new Error("User preferences could not be found.");- return { ...DEFAULT_USER_PREFERENCES, ...user.preferences };+ return withDefaults(user.preferences);},async patch(userId, preferences) {const [user] = await database@@ -38,7 +50,7 @@ export function createUserPreferencesStore(.where(eq(users.id, userId)).returning({ preferences: users.preferences });if (!user) throw new Error("User preferences could not be saved.");- return { ...DEFAULT_USER_PREFERENCES, ...user.preferences };+ return withDefaults(user.preferences);},};}diff --git a/server/tests/sole-definition.test.ts b/server/tests/sole-definition.test.tsindex 47605bab..32517038 100644--- a/server/tests/sole-definition.test.ts+++ b/server/tests/sole-definition.test.ts@@ -163,10 +163,10 @@ const KNOWN_DUPLICATES: Record<> = {"brokered-provenance": {finding: "round-1 DRY sweep (`brokeredProvenance` defined 2x) + G-series",- why: "One predicate for the app and one for the server, plus the same two-arm literal open-coded as `isBrokered` on the connected-accounts page; collapsing them is a cross-package move the fix cycle owns.",+ why: "One predicate for the app and one for the server, plus the same two-arm literal open-coded as `isBrokered` in the Connections page's helpers (`lib/plugins/listed.ts`); collapsing them is a cross-package move the fix cycle owns.",sites: [+ "app/src/lib/plugins/listed.ts","app/src/lib/plugins/provider-vocabulary.ts",- "app/src/routes/_authed/_app/connections.index.tsx","server/src/plugins/access.ts",],},diff --git a/server/tests/user-preferences-routes.test.ts b/server/tests/user-preferences-routes.test.tsindex 3ddd3803..897d0a4c 100644--- a/server/tests/user-preferences-routes.test.ts+++ b/server/tests/user-preferences-routes.test.ts@@ -53,6 +53,7 @@ test("preferences default to thread and persist separately for each authenticatepreferences: {messageListEmphasis: "thread",selfHostBannerDismissed: false,+ skin: "openbot",},});const saved = await alice.request(@@ -64,12 +65,14 @@ test("preferences default to thread and persist separately for each authenticatepreferences: {messageListEmphasis: "agent",selfHostBannerDismissed: false,+ skin: "openbot",},});expect(await (await appFor("bob").request(path)).json()).toEqual({preferences: {messageListEmphasis: "thread",selfHostBannerDismissed: false,+ skin: "openbot",},});});@@ -80,6 +83,9 @@ test.each([{ selfHostBannerDismissed: "yes" },{ messageListEmphasis: "invalid" },{ messageListEmphasis: "agent", userId: "bob" },+ { skin: "retired-skin" },+ { skin: "" },+ { skin: null },])("rejects invalid or extra preference fields: %j", async (body) => {const { appFor, state } = fixture();expect((await appFor("alice").request(path, patch(body))).status).toBe(400);@@ -114,12 +120,56 @@ test("saves the self-host banner dismissal without touching message list emphasipreferences: {messageListEmphasis: "agent",selfHostBannerDismissed: true,+ skin: "openbot",},});expect(await (await appFor("bob").request(path)).json()).toEqual({preferences: {messageListEmphasis: "thread",selfHostBannerDismissed: false,+ skin: "openbot",},});});++test("saves the skin on the account without touching the other preferences", async () => {+ const { appFor } = fixture();+ const alice = appFor("alice");+ await alice.request(path, patch({ messageListEmphasis: "agent" }));+ const saved = await alice.request(path, patch({ skin: "opendots" }));+ expect(saved.status).toBe(200);+ expect(await saved.json()).toEqual({+ preferences: {+ messageListEmphasis: "agent",+ selfHostBannerDismissed: false,+ skin: "opendots",+ },+ });+ // Another browser signed in as Alice reads the same skin; Bob keeps the default.+ expect(await (await appFor("alice").request(path)).json()).toEqual({+ preferences: {+ messageListEmphasis: "agent",+ selfHostBannerDismissed: false,+ skin: "opendots",+ },+ });+ expect(+ (+ (await (await appFor("bob").request(path)).json()) as {+ preferences: UserPreferences;+ }+ ).preferences.skin,+ ).toBe("openbot");+});++test("a skin OpenBot does not ship is refused with the skins it does", async () => {+ const { appFor } = fixture();+ const refused = await appFor("alice").request(+ path,+ patch({ skin: "retired-skin" }),+ );+ expect(refused.status).toBe(400);+ expect(((await refused.json()) as { error: string }).error).toContain(+ "openbot, openduet, opendots, openmuse",+ );+});diff --git a/server/tests/user-preferences.integration.test.ts b/server/tests/user-preferences.integration.test.tsindex 94db1b7a..84cda5d8 100644--- a/server/tests/user-preferences.integration.test.ts+++ b/server/tests/user-preferences.integration.test.ts@@ -29,18 +29,22 @@ test("database defaults and writes survive a new store and remain scoped to theexpect(await store.read(alice)).toEqual({messageListEmphasis: "thread",selfHostBannerDismissed: false,+ skin: "openbot",});expect(await store.patch(alice, { messageListEmphasis: "agent" })).toEqual({messageListEmphasis: "agent",selfHostBannerDismissed: false,+ skin: "openbot",});expect(await createUserPreferencesStore(database).read(alice)).toEqual({messageListEmphasis: "agent",selfHostBannerDismissed: false,+ skin: "openbot",});expect(await store.read(bob)).toEqual({messageListEmphasis: "thread",selfHostBannerDismissed: false,+ skin: "openbot",});});@@ -68,3 +72,24 @@ test("missing users do not appear successfully saved", async () => {store.patch(id, { messageListEmphasis: "agent" }),).rejects.toThrow("could not be saved");});++test("the skin is saved on the account and survives a new store", async () => {+ const id = await person();+ expect(await store.patch(id, { skin: "openmuse" })).toEqual({+ messageListEmphasis: "thread",+ selfHostBannerDismissed: false,+ skin: "openmuse",+ });+ expect((await createUserPreferencesStore(database).read(id)).skin).toBe(+ "openmuse",+ );+});++test("a stored skin this build does not ship reads as the default", async () => {+ const id = await person();+ await database+ .update(users)+ .set({ preferences: sql`'{"skin":"retired-skin"}'::jsonb` })+ .where(eq(users.id, id));+ expect((await store.read(id)).skin).toBe("openbot");+});diff --git a/shared/user-preferences.ts b/shared/user-preferences.tsindex fcf9fcdf..a9ff80f6 100644--- a/shared/user-preferences.ts+++ b/shared/user-preferences.ts@@ -1,14 +1,39 @@export type MessageListEmphasis = "agent" | "thread";+/**+ * Every skin OpenBot ships. `openbot` is the default and is OpenBot exactly as it is without a+ * skin: no frame of its own, no tokens of its own.+ *+ * Here rather than in the app because the choice is saved on the person's account, so the server+ * has to know which values it may store.+ */+export const SKIN_IDS = [+ "openbot",+ "openduet",+ "opendots",+ "openmuse",+] as const;++export type SkinId = (typeof SKIN_IDS)[number];++export const DEFAULT_SKIN: SkinId = "openbot";++export function isSkinId(value: unknown): value is SkinId {+ return SKIN_IDS.some((id) => id === value);+}+export type UserPreferences = {/** Set by profile saves so choosing a name finishes the first-run prompt. */profileNameSet?: boolean;messageListEmphasis: MessageListEmphasis;/** Whether this person closed the banner offering help self-hosting OpenBot. */selfHostBannerDismissed: boolean;+ /** How OpenBot looks for this person, on every device they sign in from. */+ skin: SkinId;};export const DEFAULT_USER_PREFERENCES: UserPreferences = {messageListEmphasis: "thread",selfHostBannerDismissed: false,+ skin: DEFAULT_SKIN,};