Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(home): Settings catalog, a skill library for new hires, the orb restyle
trohitg24306671e520
diff --git a/CLAUDE.md b/CLAUDE.mdindex 7afccd4f..3a4fa515 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -2492,7 +2492,7 @@ Updated `client_left` and presence handlers use `has_real_android_devices()` ins| **Usage/Compaction** | `get_api_usage_summary`, `get_compaction_stats`, `configure_compaction`, `get_provider_usage_summary` || **Agent Teams** | `create_team`, `get_team`, `get_team_status`, `dissolve_team`, `add_team_task`, `claim_team_task`, `complete_team_task`, `get_team_tasks`, `send_team_message`, `get_team_messages` || **Model Registry** | `get_model_constraints`, `refresh_model_registry` |-| **Employees (Normal mode)** | `list_employees`, `get_employee`, `generate_employee_setup`, `cancel_employee_setup`, `hire_employee`, `start_employee` (see [normal_mode.md](./docs-internal/normal_mode.md)) |+| **Employees (Normal mode)** | `list_employees`, `get_employee`, `get_employee_usage`, `generate_employee_setup`, `cancel_employee_setup`, `hire_employee`, `start_employee` (see [normal_mode.md](./docs-internal/normal_mode.md)) || **Approvals** | `list_approvals`, `decide_approval` (the `approvalGate` node's drafts) |#### Broadcast Messages (Server -> All Clients)diff --git a/client/src/components/parameterPanel/MasterSkillEditor.tsx b/client/src/components/parameterPanel/MasterSkillEditor.tsxindex 7c61cbd5..dc5e7669 100644--- a/client/src/components/parameterPanel/MasterSkillEditor.tsx+++ b/client/src/components/parameterPanel/MasterSkillEditor.tsx@@ -51,15 +51,19 @@ import { NodeIcon } from '../../assets/icons';import { theme } from '../../styles/theme';import { cn } from '@/lib/utils';import { useFolderSkills } from '../../hooks/useFolderSkills';+import { USER_SKILLS_QUERY_KEY, useUserSkillsQuery, type UserSkill } from '../../hooks/useUserSkills';import { useNodeAllowlist } from '../../hooks/useNodeAllowlist';// Skill configuration stored in node parameters-// Key is skillName (folder name like 'whatsapp-skill')+// Key is skillName (folder name like 'whatsapp-skill'). Entries can carry+// more keys (a hired employee's Skills node adds `description`), so every+// edit below spreads the existing entry instead of rebuilding it.interface SkillConfig {enabled: boolean;instructions: string;isCustomized: boolean;required?: boolean;+ description?: string;}interface MasterSkillConfig {@@ -76,18 +80,6 @@ interface AvailableSkill {isUserSkill?: boolean; // True if this is a user-created skill from database}-// User skill from database-interface UserSkill {- name: string;- display_name: string;- description: string;- instructions: string;- icon: string;- color: string;- category: string;- is_active: boolean;-}-// Pending skill data for create/editinterface PendingSkillData {name: string;@@ -153,20 +145,10 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({const initializedSkillRef = useRef<string | null>(null);const queryClient = useQueryClient();- const userSkillsQuery = useQuery<UserSkill[], Error>({- queryKey: ['userSkills'],- queryFn: async () => {- const response = await sendRequest<{ skills: UserSkill[]; count: number }>(- 'get_user_skills',- { active_only: false },- );- return response?.skills ?? [];- },- staleTime: 60_000,- });+ const userSkillsQuery = useUserSkillsQuery();const userSkills = userSkillsQuery.data ?? EMPTY_USER_SKILLS;const invalidateUserSkills = useCallback(- () => queryClient.invalidateQueries({ queryKey: ['userSkills'] }),+ () => queryClient.invalidateQueries({ queryKey: USER_SKILLS_QUERY_KEY }),[queryClient],);@@ -230,8 +212,11 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({skills.push(...folderSkills);}- // Add user-created skills+ // Add user-created skills. A built-in added to the owner's library from+ // Home is a copy under the same name: the folder's row already shows it.+ const folderNames = new Set(skills.map((skill) => skill.skillName));userSkills.forEach(us => {+ if (folderNames.has(us.name)) return;skills.push({type: 'userSkill',skillName: us.name,@@ -400,12 +385,13 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({const defaultContent = await fetchSkillContent(skillName);onConfigChange({...skillsConfig,- [skillName]: { enabled: true, instructions: defaultContent, isCustomized: false }+ [skillName]: { ...currentConfig, enabled: true, instructions: defaultContent, isCustomized: false }});} else {onConfigChange({...skillsConfig,[skillName]: {+ ...currentConfig,enabled,instructions: currentConfig?.instructions || '',isCustomized: currentConfig?.isCustomized || false@@ -422,6 +408,7 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({onConfigChange({...skillsConfig,[skillName]: {+ ...currentConfig,enabled: currentConfig?.enabled || false,instructions,isCustomized@@ -436,7 +423,7 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({onConfigChange({...skillsConfig,- [skillName]: { enabled: currentConfig?.enabled || false, instructions: defaultContent, isCustomized: false }+ [skillName]: { ...currentConfig, enabled: currentConfig?.enabled || false, instructions: defaultContent, isCustomized: false }});}, [skillsConfig, onConfigChange, fetchSkillContent, queryClient]);@@ -504,6 +491,8 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({setSavingSkill(true);try {const handler = isCreatingNew ? 'create_user_skill' : 'update_user_skill';+ // No `is_active`: a new skill starts on, and an edit keeps whether the+ // owner has it on for new hires (Home's Settings > Skills).const payload = {name: skillName,display_name: pendingSkillData.display_name,@@ -512,7 +501,6 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({icon: pendingSkillData.icon,color: pendingSkillData.color,category: skillFolder || 'custom',- is_active: true};const result = await sendRequest<{ skill?: UserSkill; success?: boolean; error?: string }>(handler, payload);diff --git a/client/src/components/parameterPanel/MiddleSection.tsx b/client/src/components/parameterPanel/MiddleSection.tsxindex 7fda7f3b..c49aa28f 100644--- a/client/src/components/parameterPanel/MiddleSection.tsx+++ b/client/src/components/parameterPanel/MiddleSection.tsx@@ -41,7 +41,7 @@ import { useAppStore } from '../../store/useAppStore';import { useNodeStatus, useWebSocket, CompactionStats } from '../../contexts/WebSocketContext';import { useUserSettingsQuery } from '../../hooks/useUserSettingsQuery';import { nodeParamsQueryKey, type NodeParametersResponse } from '../../hooks/useNodeParamsQuery';-import { folderSkillsQueryKey, type AvailableSkill } from '../../hooks/useFolderSkills';+import { fetchFolderSkills, folderSkillsQueryKey, type AvailableSkill } from '../../hooks/useFolderSkills';import { queryKeys, STALE_TIME } from '../../lib/queryConfig';import { INodeTypeDescription, INodeProperties } from '../../types/INodeProperties';import { NodeIcon } from '../../assets/icons';@@ -367,28 +367,12 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({return Array.from(folders);}, [masterSkillEdgeSources, masterSkillParams]);+ // The same fetcher as useFolderSkills: one query function per cache key,+ // so the editor and this list never disagree on a folder's shape.const folderSkillsQueries = useQueries({queries: masterSkillFolders.map((folder) => ({queryKey: folderSkillsQueryKey(folder),- queryFn: async (): Promise<AvailableSkill[]> => {- const response = await sendRequest<{- success: boolean;- skills?: Array<{- name: string;- description: string;- metadata?: Record<string, any>;- }>;- }>('scan_skill_folder', { folder });- if (!response?.success || !response.skills) return [];- return response.skills.map((s) => ({- type: s.name,- skillName: s.name,- displayName: s.name,- icon: s.metadata?.icon ?? '',- color: s.metadata?.color ?? 'var(--node-agent)',- description: s.description ?? '',- }));- },+ queryFn: (): Promise<AvailableSkill[]> => fetchFolderSkills(sendRequest, folder),staleTime: STALE_TIME.MEDIUM,enabled: !!folder,})),diff --git a/client/src/features/home/__tests__/catalogLayout.test.tsx b/client/src/features/home/__tests__/catalogLayout.test.tsxnew file mode 100644index 00000000..71379de2--- /dev/null+++ b/client/src/features/home/__tests__/catalogLayout.test.tsx@@ -0,0 +1,128 @@+/**+ * The shared catalog page: Discover shows eight until "Show all"; the+ * category filter reveals its chips and clears when closed; Yours shows the+ * page's own list with a switch only when the page can toggle and remove+ * only when it can remove; an empty Yours points to Discover; a card that+ * turns added while on screen calls back once.+ */++import { describe, expect, it, vi } from 'vitest';+import { fireEvent, render, screen } from '@testing-library/react';+import { ThemeProvider } from '@/contexts/ThemeContext';+import type { CatalogItem } from '../settings/catalog';+import { CatalogLayout, type CatalogLayoutProps } from '../settings/CatalogLayout';++function item(id: string, patch: Partial<CatalogItem> = {}): CatalogItem {+ return { id, name: `Item ${id}`, tile: {}, state: 'available', ...patch };+}++const EMPTY = { title: 'Nothing yours yet', detail: 'Add one from Discover.' };++function renderLayout(props: Partial<CatalogLayoutProps> = {}) {+ const base: CatalogLayoutProps = {+ title: 'Things',+ searchPlaceholder: 'Search things',+ yours: { items: [], sectionTitle: 'Your things', empty: EMPTY },+ discover: { items: [], sectionTitle: 'Top things' },+ verbs: { add: 'Add', remove: 'Remove' },+ onAdd: vi.fn(),+ ...props,+ };+ const view = (next: Partial<CatalogLayoutProps> = {}) => (+ <ThemeProvider>+ <CatalogLayout {...base} {...next} />+ </ThemeProvider>+ );+ const utils = render(view());+ return { ...utils, rerenderWith: (next: Partial<CatalogLayoutProps>) => utils.rerender(view(next)) };+}++const cards = () => document.querySelectorAll('[data-catalog-item]');+const showYours = () => fireEvent.click(screen.getByRole('radio', { name: /Yours/ }));++describe('CatalogLayout', () => {+ it('shows eight in Discover until Show all', () => {+ renderLayout({ discover: { items: Array.from({ length: 10 }, (_, i) => item(String(i))), sectionTitle: 'Top things' } });+ expect(cards()).toHaveLength(8);+ fireEvent.click(screen.getByRole('button', { name: /Show all/ }));+ expect(cards()).toHaveLength(10);+ expect(screen.getByRole('button', { name: /Show less/ })).toBeInTheDocument();+ });++ it('reveals the category chips, and closing the filter clears the category', () => {+ renderLayout({+ categories: [+ { key: 'a', label: 'Alpha' },+ { key: 'b', label: 'Beta' },+ ],+ discover: { items: [item('1', { category: 'a' }), item('2', { category: 'b' })], sectionTitle: 'Top things' },+ });+ expect(screen.queryByRole('radio', { name: 'Beta' })).not.toBeInTheDocument();+ const filter = screen.getByRole('button', { name: 'Filter by category' });+ fireEvent.click(filter);+ fireEvent.click(screen.getByRole('radio', { name: 'Beta' }));+ expect(cards()).toHaveLength(1);+ fireEvent.click(filter);+ expect(screen.queryByRole('radio', { name: 'Beta' })).not.toBeInTheDocument();+ expect(cards()).toHaveLength(2);+ });++ it('has no filter without categories, and starts filtered when opened on one', () => {+ const { unmount } = renderLayout();+ expect(screen.queryByRole('button', { name: 'Filter by category' })).not.toBeInTheDocument();+ unmount();+ renderLayout({+ categories: [{ key: 'a', label: 'Alpha' }],+ initialCategory: 'a',+ discover: { items: [item('1', { category: 'a' }), item('2')], sectionTitle: 'Top things' },+ });+ expect(screen.getByRole('radio', { name: 'Alpha' })).toHaveAttribute('aria-checked', 'true');+ expect(cards()).toHaveLength(1);+ });++ it('shows a switch in Yours only when the page can toggle, and remove only when it can remove', () => {+ const onToggle = vi.fn();+ const added = item('1', { state: 'added', enabled: true });+ const lists = { yours: { items: [added], sectionTitle: 'Your things', empty: EMPTY }, discover: { items: [added], sectionTitle: 'Top things' } };+ const { rerenderWith } = renderLayout({ ...lists, onToggle });+ expect(screen.getByRole('img', { name: 'Item 1 added' })).toBeInTheDocument();+ showYours();+ fireEvent.click(screen.getByRole('switch', { name: 'Item 1' }));+ expect(onToggle).toHaveBeenCalledWith(added, false);+ expect(screen.queryByRole('button', { name: 'Remove Item 1' })).not.toBeInTheDocument();++ const onRemove = vi.fn();+ rerenderWith({ ...lists, onRemove, onToggle: undefined });+ expect(screen.queryByRole('switch')).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Remove Item 1' }));+ expect(onRemove).toHaveBeenCalledWith(added);+ });++ it('points an empty Yours to Discover', () => {+ renderLayout({ discover: { items: [item('1')], sectionTitle: 'Top things' } });+ showYours();+ expect(screen.getByText('Nothing yours yet')).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Discover' }));+ expect(screen.getByRole('radio', { name: 'Discover' })).toHaveAttribute('aria-checked', 'true');+ expect(cards()).toHaveLength(1);+ });++ it('calls back once when an item on screen turns added, never on first render', () => {+ const onItemAdded = vi.fn();+ const { rerenderWith } = renderLayout({+ discover: { items: [item('1', { state: 'added' }), item('2')], sectionTitle: 'Top things' },+ onItemAdded,+ });+ expect(onItemAdded).not.toHaveBeenCalled();+ rerenderWith({ discover: { items: [item('1', { state: 'added' }), item('2', { state: 'added' })], sectionTitle: 'Top things' }, onItemAdded });+ expect(onItemAdded).toHaveBeenCalledTimes(1);+ expect(onItemAdded).toHaveBeenCalledWith(expect.objectContaining({ id: '2' }));+ });++ it('opens and closes the primary action form', () => {+ renderLayout({ primaryAction: { label: 'Create', form: (close) => <button onClick={close}>Done here</button> } });+ fireEvent.click(screen.getByRole('button', { name: 'Create' }));+ fireEvent.click(screen.getByRole('button', { name: 'Done here' }));+ expect(screen.queryByRole('button', { name: 'Done here' })).not.toBeInTheDocument();+ });+});diff --git a/client/src/features/home/__tests__/connectorsTab.test.tsx b/client/src/features/home/__tests__/connectorsTab.test.tsxindex e07a43b7..9652872b 100644--- a/client/src/features/home/__tests__/connectorsTab.test.tsx+++ b/client/src/features/home/__tests__/connectorsTab.test.tsx@@ -2,7 +2,8 @@* Settings > Connectors: Disconnect removes what the provider's own panel* would (an API key, a sign-in), and hands QR and email accounts to their* panel; a card glows and confirms only when a provider flips to connected- * while the tab is open.+ * while the page is open; the page opens on the category it was asked for,+ * and search also matches who makes the app.*/import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -24,8 +25,7 @@ vi.mock('../data/connectors', async (importOriginal) => {useConnectors: () => ({providers,categories: [{ key: 'ai', label: 'AI' }, { key: 'messages', label: 'Messages' }],- connectedCount: providers.filter(actual.isConnected).length,- connectedApps: [],+ connectedApps: providers.filter(actual.isConnected).filter((p) => p.consumer_category !== 'ai'),hasAi: true,isLoading: false,}),@@ -37,10 +37,10 @@ vi.mock('../ui/pillToast', () => ({ pillToast: vi.fn() }));import { ThemeProvider } from '@/contexts/ThemeContext';import { ConnectorsTab } from '../settings/ConnectorsTab';-function ui(onConnect = vi.fn()) {+function ui(onConnect = vi.fn(), initialCategory?: string) {return (<ThemeProvider>- <ConnectorsTab onConnect={onConnect} />+ <ConnectorsTab onConnect={onConnect} initialCategory={initialCategory} /></ThemeProvider>);}@@ -58,7 +58,7 @@ function provider(patch: Partial<ServerProviderConfig> & { id: string; kind: Ser}async function disconnect(name: string) {- const card = screen.getByText(name).closest('[data-connector]') as HTMLElement;+ const card = screen.getByText(name).closest('[data-catalog-item]') as HTMLElement;fireEvent.click(card.querySelector('button')!);fireEvent.click(await screen.findByRole('button', { name: 'Disconnect' }));}@@ -122,4 +122,24 @@ describe('ConnectorsTab', () => {expect(screen.getByText('Google')).toBeInTheDocument();expect(screen.queryByText('OpenAI')).not.toBeInTheDocument();});++ it('opens on the category it was asked for, with the filter showing', () => {+ render(ui(vi.fn(), 'messages'));+ expect(screen.getByText('Messages').closest('button')).toHaveAttribute('data-state', 'on');+ expect(screen.getByText('WhatsApp')).toBeInTheDocument();+ expect(screen.queryByText('OpenAI')).not.toBeInTheDocument();+ });++ it('searches who makes the app', () => {+ providers = [+ provider({ id: 'gemini', name: 'Gemini', kind: 'apiKey', publisher: 'Google', verified: true }),+ provider({ id: 'openai', name: 'OpenAI', kind: 'apiKey', publisher: 'OpenAI' }),+ ];+ render(ui());+ fireEvent.change(screen.getByRole('textbox', { name: 'Search connectors' }), { target: { value: 'google' } });+ expect(screen.getByText('Gemini')).toBeInTheDocument();+ expect(screen.getByText('by Google')).toBeInTheDocument();+ expect(screen.getByRole('img', { name: 'Verified' })).toBeInTheDocument();+ expect(screen.queryByText('OpenAI')).not.toBeInTheDocument();+ });});diff --git a/client/src/features/home/__tests__/homeSettings.test.tsx b/client/src/features/home/__tests__/homeSettings.test.tsxnew file mode 100644index 00000000..86913cdf--- /dev/null+++ b/client/src/features/home/__tests__/homeSettings.test.tsx@@ -0,0 +1,80 @@+/**+ * Settings: the nav search keeps the pages whose label or keywords match+ * and drops a group left empty; changing page clears the category a page+ * was opened on; Billing shows this month's tasks and the team size, and a+ * dash when the count can't be read.+ */++import { beforeEach, describe, expect, it, vi } from 'vitest';+import { fireEvent, render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';++const sendRequest = vi.fn();++vi.mock('@/contexts/WebSocketContext', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/contexts/WebSocketContext')>()),+ useWebSocketActions: () => ({ sendRequest, isReady: true, addEventListener: () => () => {} }),+}));+vi.mock('../settings/ProfileTab', () => ({ ProfileTab: () => <p>Profile page</p> }));+vi.mock('../settings/ConnectorsTab', () => ({+ ConnectorsTab: ({ initialCategory }: { initialCategory?: string }) => <p>Connectors page ({initialCategory})</p>,+}));+vi.mock('../data/employees', () => ({ useEmployeesQuery: () => ({ data: [{}, {}, {}], isPending: false }) }));++import { ThemeProvider } from '@/contexts/ThemeContext';+import { HomeSettings } from '../settings/HomeSettings';+import { useHomeStore } from '../state/homeStore';++function renderSettings() {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ render(+ <ThemeProvider>+ <QueryClientProvider client={client}>+ <HomeSettings onConnect={vi.fn()} />+ </QueryClientProvider>+ </ThemeProvider>,+ );+}++beforeEach(() => {+ sendRequest.mockReset().mockResolvedValue({ success: true, tasks_this_month: 12 });+ useHomeStore.setState({ settingsOpen: false, settingsTab: 'profile', settingsCategory: 'all' });+});++describe('HomeSettings', () => {+ it('keeps the pages the nav search matches and drops an empty group', () => {+ useHomeStore.getState().openSettings();+ renderSettings();+ fireEvent.change(screen.getByRole('textbox', { name: 'Search settings' }), { target: { value: 'invoices' } });+ expect(screen.getByRole('tab', { name: 'Billing' })).toBeInTheDocument();+ expect(screen.queryByRole('tab', { name: 'Profile' })).not.toBeInTheDocument();+ expect(screen.queryByRole('tab', { name: 'Connectors' })).not.toBeInTheDocument();+ expect(screen.queryByText('Customize')).not.toBeInTheDocument();+ });++ it('clears the category a page was opened on when the page changes', async () => {+ useHomeStore.getState().openSettings('connectors', 'ai');+ renderSettings();+ expect(screen.getByText('Connectors page (ai)')).toBeInTheDocument();+ await userEvent.click(screen.getByRole('tab', { name: 'Profile' }));+ expect(useHomeStore.getState().settingsCategory).toBe('all');+ await userEvent.click(screen.getByRole('tab', { name: 'Connectors' }));+ expect(screen.getByText('Connectors page (all)')).toBeInTheDocument();+ });++ it('shows this month’s tasks and the team size on Billing', async () => {+ useHomeStore.getState().openSettings('billing');+ renderSettings();+ expect(await screen.findByText('12')).toBeInTheDocument();+ expect(screen.getByText('3')).toBeInTheDocument();+ expect(sendRequest).toHaveBeenCalledWith('get_employee_usage', {});+ });++ it('shows a dash when this month’s count can’t be read', async () => {+ sendRequest.mockResolvedValue({ success: false, error: 'database locked' });+ useHomeStore.getState().openSettings('billing');+ renderSettings();+ expect(await screen.findByText('—')).toBeInTheDocument();+ });+});diff --git a/client/src/features/home/__tests__/plugins.test.tsx b/client/src/features/home/__tests__/plugins.test.tsxnew file mode 100644index 00000000..5848f1fa--- /dev/null+++ b/client/src/features/home/__tests__/plugins.test.tsx@@ -0,0 +1,118 @@+/**+ * Settings > Plugins: Install adds a bundle's missing skills, switches on+ * the ones that are off, then starts a hire from its job on the hire view;+ * a bundle whose skills are all in the library counts as installed; nothing+ * installs while a setup is being written. The starter list itself parses,+ * and the composer's chips still read it.+ */++import { beforeEach, describe, expect, it, vi } from 'vitest';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import type { UserSkill } from '@/hooks/useUserSkills';++let library: UserSkill[] = [];+const builtIns = ['write-like-a-person', 'short-reports', 'social-posts'].map((name) => ({+ name,+ description: `Use for ${name}.`,+ metadata: { title: name, summary: name },+}));++const sendRequest = vi.fn(async (type: string, data: Record<string, any> = {}) => {+ switch (type) {+ case 'get_user_skills':+ return { skills: library };+ case 'scan_skill_folder':+ return { success: true, skills: builtIns };+ case 'get_skill_content':+ return { success: true, instructions: `Do ${data.skill_name}.` };+ case 'create_user_skill':+ library = [...library, row(data.name)];+ return { skill: library.at(-1) };+ case 'update_user_skill':+ library = library.map((entry) => (entry.name === data.name ? { ...entry, is_active: data.is_active } : entry));+ return { skill: library.find((entry) => entry.name === data.name) };+ default:+ return {};+ }+});++const draft = { busy: false, start: vi.fn() };++vi.mock('@/contexts/WebSocketContext', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/contexts/WebSocketContext')>()),+ useWebSocketActions: () => ({ sendRequest, isReady: true, addEventListener: () => () => {} }),+}));+vi.mock('../genui', () => ({ useStartHire: () => draft }));+vi.mock('../ui/pillToast', () => ({ pillToast: vi.fn() }));++import { ThemeProvider } from '@/contexts/ThemeContext';+import { HIRE_TEMPLATES, STARTERS } from '../hire/templates';+import { PluginsTab } from '../settings/PluginsTab';+import { useHomeStore } from '../state/homeStore';+import { pillToast } from '../ui/pillToast';++function row(name: string, patch: Partial<UserSkill> = {}): UserSkill {+ return { name, display_name: name, description: '', instructions: 'x', icon: '', color: '', category: 'custom', is_active: true, ...patch };+}++function renderTab() {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ render(+ <ThemeProvider>+ <QueryClientProvider client={client}>+ <PluginsTab />+ </QueryClientProvider>+ </ThemeProvider>,+ );+}++const inbox = STARTERS.find((starter) => starter.id === 'inbox-assistant')!;++beforeEach(() => {+ library = [];+ sendRequest.mockClear();+ draft.busy = false;+ draft.start.mockReset();+ vi.mocked(pillToast).mockClear();+ useHomeStore.setState({ settingsOpen: true, view: { kind: 'employee', workflowId: 'w1' } });+});++describe('PluginsTab', () => {+ it('installs a bundle: its skills into the library, then a hire from its job', async () => {+ library = [row('short-reports', { is_active: false })];+ renderTab();+ fireEvent.click(await screen.findByRole('button', { name: 'Install Inbox assistant' }));+ await waitFor(() => expect(draft.start).toHaveBeenCalledWith(inbox.job));+ expect(sendRequest).toHaveBeenCalledWith('create_user_skill', expect.objectContaining({ name: 'write-like-a-person' }));+ expect(sendRequest).toHaveBeenCalledWith('update_user_skill', { name: 'short-reports', is_active: true });+ expect(useHomeStore.getState().settingsOpen).toBe(false);+ expect(useHomeStore.getState().view).toEqual({ kind: 'hire' });+ });++ it('counts a bundle as installed when all its skills are in the library', async () => {+ library = [row('social-posts'), row('write-like-a-person', { is_active: false })];+ renderTab();+ expect(await screen.findByRole('img', { name: 'Social media helper added' })).toBeInTheDocument();+ fireEvent.click(screen.getByRole('radio', { name: /Yours/ }));+ expect(screen.getByText('Social media helper')).toBeInTheDocument();+ expect(screen.queryByText('Bookkeeper')).not.toBeInTheDocument();+ });++ it('waits while a setup is being written', async () => {+ draft.busy = true;+ renderTab();+ fireEvent.click(await screen.findByRole('button', { name: 'Install Bookkeeper' }));+ expect(pillToast).toHaveBeenCalledWith('Finish the setup you are working on first', { tone: 'info' });+ expect(sendRequest).not.toHaveBeenCalledWith('create_user_skill', expect.anything());+ expect(draft.start).not.toHaveBeenCalled();+ });+});++describe('starters', () => {+ it('parse, and the composer chips read the same list', () => {+ expect(HIRE_TEMPLATES).toBe(STARTERS);+ expect(STARTERS.map((starter) => starter.label)).toEqual(['Receptionist', 'Inbox assistant', 'Bookkeeper', 'Social media helper']);+ for (const starter of STARTERS) expect(starter.skills.length).toBeGreaterThan(0);+ });+});diff --git a/client/src/features/home/__tests__/skills.test.tsx b/client/src/features/home/__tests__/skills.test.tsxnew file mode 100644index 00000000..28703864--- /dev/null+++ b/client/src/features/home/__tests__/skills.test.tsx@@ -0,0 +1,172 @@+/**+ * Settings > Skills: "+" copies a built-in's text into the library; the+ * Yours switch turns a skill on or off for new hires; Remove deletes it;+ * Create gives a new skill a name of its own, never a taken or built-in+ * one. Plus the naming and summary helpers, and the shared folder fetcher.+ */++import { beforeEach, describe, expect, it, vi } from 'vitest';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import type { UserSkill } from '@/hooks/useUserSkills';++type Row = UserSkill;+let library: Row[] = [];+const builtIns = [+ {+ name: 'book-appointments',+ description: 'Use when someone wants to book.',+ metadata: { title: 'Book appointments', summary: 'Offers free times.', icon: 'lucide:CalendarCheck', category: 'scheduling' },+ },+ {+ name: 'short-reports',+ description: 'Use when reporting.',+ metadata: { title: 'Short reports', summary: 'Reports you read fast.', category: 'reporting' },+ },+];++const sendRequest = vi.fn(async (type: string, data: Record<string, any> = {}) => {+ switch (type) {+ case 'get_user_skills':+ return { skills: library };+ case 'scan_skill_folder':+ return { success: true, skills: builtIns };+ case 'get_skill_content':+ return { success: true, instructions: `# ${data.skill_name}\nDo it well.` };+ case 'lookup_skill_metadata':+ return { success: true, skills: builtIns.filter((skill) => data.names.includes(skill.name)) };+ case 'create_user_skill': {+ const row: Row = {+ name: data.name,+ display_name: data.display_name,+ description: data.description,+ instructions: data.instructions,+ icon: data.icon ?? 'star',+ color: '',+ category: data.category,+ is_active: true,+ metadata: data.metadata,+ };+ library = [...library, row];+ return { skill: row };+ }+ case 'update_user_skill':+ library = library.map((row) => (row.name === data.name ? { ...row, is_active: data.is_active } : row));+ return { skill: library.find((row) => row.name === data.name) };+ case 'delete_user_skill':+ library = library.filter((row) => row.name !== data.name);+ return { success: true };+ default:+ return {};+ }+});++vi.mock('@/contexts/WebSocketContext', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/contexts/WebSocketContext')>()),+ useWebSocketActions: () => ({ sendRequest, isReady: true, addEventListener: () => () => {} }),+}));+vi.mock('../ui/pillToast', () => ({ pillToast: vi.fn() }));++import { ThemeProvider } from '@/contexts/ThemeContext';+import { fetchFolderSkills } from '@/hooks/useFolderSkills';+import { firstSentence, librarySkillName } from '../data/skills';+import { SkillsTab } from '../settings/SkillsTab';++function row(name: string, patch: Partial<Row> = {}): Row {+ return { name, display_name: name, description: '', instructions: 'x', icon: '', color: '', category: 'custom', is_active: true, ...patch };+}++function renderTab() {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ render(+ <ThemeProvider>+ <QueryClientProvider client={client}>+ <SkillsTab />+ </QueryClientProvider>+ </ThemeProvider>,+ );+}++beforeEach(() => {+ library = [];+ sendRequest.mockClear();+});++describe('SkillsTab', () => {+ it('adds a built-in by copying its text into the library', async () => {+ renderTab();+ fireEvent.click(await screen.findByRole('button', { name: 'Add Book appointments' }));+ await waitFor(() =>+ expect(sendRequest).toHaveBeenCalledWith(+ 'create_user_skill',+ expect.objectContaining({+ name: 'book-appointments',+ display_name: 'Book appointments',+ instructions: '# book-appointments\nDo it well.',+ }),+ ),+ );+ expect(sendRequest).toHaveBeenCalledWith('get_skill_content', { skill_name: 'book-appointments' });+ expect(await screen.findByRole('button', { name: 'Remove Book appointments' })).toBeInTheDocument();+ });++ it('switches a skill off for new hires, and removes one', async () => {+ library = [row('short-reports', { display_name: 'Short reports' })];+ renderTab();+ fireEvent.click(await screen.findByRole('radio', { name: /Yours/ }));+ fireEvent.click(await screen.findByRole('switch', { name: 'Short reports' }));+ await waitFor(() => expect(sendRequest).toHaveBeenCalledWith('update_user_skill', { name: 'short-reports', is_active: false }));+ fireEvent.click(screen.getByRole('button', { name: 'Remove Short reports' }));+ await waitFor(() => expect(sendRequest).toHaveBeenCalledWith('delete_user_skill', { name: 'short-reports' }));+ });++ it('creates a skill under a name of its own', async () => {+ library = [row('front-desk')];+ renderTab();+ fireEvent.click(await screen.findByRole('button', { name: 'Create' }));+ const add = screen.getByRole('button', { name: 'Add' });+ expect(add).toBeDisabled();+ fireEvent.change(screen.getByRole('textbox', { name: 'Skill name' }), { target: { value: 'Front desk' } });+ fireEvent.change(screen.getByRole('textbox', { name: 'How it’s done' }), {+ target: { value: 'Greet everyone by name. Keep it short.' },+ });+ fireEvent.click(add);+ await waitFor(() =>+ expect(sendRequest).toHaveBeenCalledWith(+ 'create_user_skill',+ expect.objectContaining({+ name: 'front-desk-2',+ display_name: 'Front desk',+ description: 'Front desk: Greet everyone by name.',+ metadata: { title: 'Front desk', summary: 'Greet everyone by name.' },+ }),+ ),+ );+ });+});++describe('skill helpers', () => {+ it('names a new skill by its title, past taken, built-in and reserved names', async () => {+ const send = vi.fn(async (_type: string, data: Record<string, any> = {}) => ({+ success: true,+ skills: data.names.includes('book-appointments') ? [{ name: 'book-appointments' }] : [],+ }));+ expect(await librarySkillName(send as never, 'Front Desk!', [])).toBe('front-desk');+ expect(await librarySkillName(send as never, 'Front desk', [row('front-desk')])).toBe('front-desk-2');+ expect(await librarySkillName(send as never, 'Book appointments', [])).toBe('book-appointments-2');+ expect(await librarySkillName(send as never, 'Pirate personality', [])).toBe('pirate-personality-2');+ expect(await librarySkillName(send as never, '!!!', [])).toBe('my-skill');+ });++ it('takes the first sentence of plain-words instructions', () => {+ expect(firstSentence('Greet people by name. Then help.')).toBe('Greet people by name.');+ expect(firstSentence('\n# Front desk\nGreet people.')).toBe('Front desk');+ expect(firstSentence('')).toBe('');+ });++ it('keeps a folder skill’s metadata', async () => {+ const send = async () => ({ success: true, skills: [{ name: 'a-b', description: 'd', metadata: { title: 'T' } }] });+ const [skill] = await fetchFolderSkills(send as never, 'employee');+ expect(skill).toMatchObject({ skillName: 'a-b', displayName: 'A B', metadata: { title: 'T' } });+ });+});diff --git a/client/src/features/home/data/connectors.ts b/client/src/features/home/data/connectors.tsindex 4182d393..49df949d 100644--- a/client/src/features/home/data/connectors.ts+++ b/client/src/features/home/data/connectors.ts@@ -1,8 +1,8 @@/*** Normal mode's view of the credential catalogue: the providers an owner- * can connect (those with a `consumer_category`), grouped the way the- * Connectors tab shows them. Same cache as the editor's Credentials modal,- * read through the stable actions context.+ * can connect (those with a `consumer_category`), in the order of their+ * categories (apps before AI models). Same cache as the editor's+ * Credentials modal, read through the stable actions context.*/import { useMemo } from 'react';@@ -21,10 +21,14 @@ export function useHomeCatalogue() {return useCatalogueQueryCore(sendRequest, isReady);}+/** Consumer providers, sorted by their category's place in `consumer_categories`+ * (a stable sort, so the catalogue's own order holds within a category). */export function consumerProviders(catalogue: CatalogueResponse | undefined): ConsumerProvider[] {- return (catalogue?.providers ?? []).filter((provider): provider is ConsumerProvider =>- Boolean(provider.consumer_category),- );+ const order = new Map((catalogue?.consumer_categories ?? []).map((category, index) => [category.key, index]));+ const rank = (provider: ConsumerProvider) => order.get(provider.consumer_category) ?? order.size;+ return (catalogue?.providers ?? [])+ .filter((provider): provider is ConsumerProvider => Boolean(provider.consumer_category))+ .sort((a, b) => rank(a) - rank(b));}export function isConnected(provider: ServerProviderConfig): boolean {@@ -34,7 +38,6 @@ export function isConnected(provider: ServerProviderConfig): boolean {export interface ConnectorsView {categories: ServerCategory[];providers: ConsumerProvider[];- connectedCount: number;/** Connected apps (not AI providers), for the composer's apps pill. */connectedApps: ConsumerProvider[];hasAi: boolean;@@ -48,20 +51,9 @@ export function useConnectors(): ConnectorsView & { isLoading: boolean } {return {categories: data?.consumer_categories ?? [],providers,- connectedCount: connected.length,connectedApps: connected.filter((p) => p.consumer_category !== 'ai'),hasAi: connected.some((p) => p.consumer_category === 'ai'),};}, [data]);return { ...view, isLoading };}--/** Providers matching a search term and a category ('all' for every one). */-export function filterProviders(providers: ConsumerProvider[], query: string, category: string): ConsumerProvider[] {- const q = query.trim().toLowerCase();- return providers.filter((provider) => {- if (category !== 'all' && provider.consumer_category !== category) return false;- if (!q) return true;- return `${provider.name} ${provider.description ?? ''}`.toLowerCase().includes(q);- });-}diff --git a/client/src/features/home/data/skills.ts b/client/src/features/home/data/skills.tsnew file mode 100644index 00000000..0f43f796--- /dev/null+++ b/client/src/features/home/data/skills.ts@@ -0,0 +1,185 @@+/**+ * Settings > Skills: the owner's skill library, and the built-in skills+ * they can add to it.+ *+ * - The library is the user-skills table (`get_user_skills`). A row that is+ * on (`is_active`) goes to every employee hired afterwards, copied into+ * that employee's Skills node, so later changes here never alter an+ * employee already hired.+ * - Discover is the built-in `employee` folder: short, tool-free skills+ * written for AI employees (server/skills/employee/).+ * - Adding a built-in copies its text into the library under the same name.+ * A skill the owner writes gets a name of its own, never a built-in's.+ *+ * Refreshes come from the `skill_lifecycle` broadcast (WebSocketContext);+ * each action also refetches the library itself.+ */++import { useMemo } from 'react';+import { useQueryClient } from '@tanstack/react-query';+import { useWebSocketActions, type WebSocketActions } from '@/contexts/WebSocketContext';+import { useFolderSkillsCore, type AvailableSkill } from '@/hooks/useFolderSkills';+import { USER_SKILLS_QUERY_KEY, useUserSkillsQueryCore, type UserSkill } from '@/hooks/useUserSkills';++/** The built-in folder Settings > Skills offers. */+export const DISCOVER_SKILL_FOLDER = 'employee';++/** Names a skill must never take in the library: `skill` is the Skill+ * tool's own entry, and a `*-personality` skill replaces an employee's+ * whole instructions. */+export function isReservedSkillName(name: string): boolean {+ return name === 'skill' || name.endsWith('-personality');+}++type Send = WebSocketActions['sendRequest'];++export function useSkillLibrary() {+ const { sendRequest, isReady } = useWebSocketActions();+ return useUserSkillsQueryCore(sendRequest, isReady);+}++export function useDiscoverSkills() {+ const { sendRequest, isReady } = useWebSocketActions();+ return useFolderSkillsCore(DISCOVER_SKILL_FOLDER, sendRequest, isReady);+}++/** A skill's name on its card: the SKILL.md title, else the row's name. */+export function skillTitle(skill: AvailableSkill): string {+ const title = skill.metadata?.title;+ return typeof title === 'string' && title.trim() ? title.trim() : skill.displayName;+}++/** A skill's card line, in the owner's words: the SKILL.md summary, else its description. */+export function skillSummary(skill: AvailableSkill | UserSkill): string {+ const summary = skill.metadata?.summary;+ return typeof summary === 'string' && summary.trim() ? summary.trim() : skill.description;+}++/** The first sentence of plain-words instructions, for a card. */+export function firstSentence(text: string): string {+ const line = text+ .split('\n')+ .map((part) => part.replace(/^[#>*\-\s]+/, '').trim())+ .find(Boolean);+ if (!line) return '';+ const end = line.search(/[.!?](\s|$)/);+ const sentence = end >= 0 ? line.slice(0, end + 1) : line;+ return sentence.length > 120 ? `${sentence.slice(0, 119).trimEnd()}…` : sentence;+}++/** A free library name for a skill titled `title`: its slug, then -2 to -9,+ * skipping reserved names, names in the library, and built-in names. */+export async function librarySkillName(send: Send, title: string, library: UserSkill[]): Promise<string> {+ const slug =+ title+ .toLowerCase()+ .normalize('NFKD')+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-+|-+$/g, '')+ .slice(0, 60)+ .replace(/-+$/g, '') || 'my-skill';+ const candidates = [slug, ...Array.from({ length: 8 }, (_, i) => `${slug}-${i + 2}`)].filter(+ (name) => !isReservedSkillName(name),+ );+ const taken = new Set(library.map((row) => row.name));+ const lookup = await send<{ skills?: Array<{ name: string }> }>('lookup_skill_metadata', { names: candidates });+ for (const found of lookup?.skills ?? []) taken.add(found.name);+ const name = candidates.find((candidate) => !taken.has(candidate));+ if (!name) throw new Error('Pick a different name for this skill');+ return name;+}++function failed(response: { success?: boolean; skill?: unknown } | undefined): boolean {+ return !response || response.success === false || (response.skill === undefined && response.success !== true);+}++/** The Skills page's actions, bound to the socket. Each one throws with a+ * message the page can show. */+export function useSkillActions() {+ const { sendRequest } = useWebSocketActions();+ const queryClient = useQueryClient();+ return useMemo(() => {+ const refresh = () => queryClient.invalidateQueries({ queryKey: USER_SKILLS_QUERY_KEY });+ const library = () => queryClient.getQueryData<UserSkill[]>(USER_SKILLS_QUERY_KEY) ?? [];++ const setOn = async (name: string, on: boolean) => {+ const before = queryClient.getQueryData<UserSkill[]>(USER_SKILLS_QUERY_KEY);+ queryClient.setQueryData<UserSkill[]>(USER_SKILLS_QUERY_KEY, (rows) =>+ rows?.map((row) => (row.name === name ? { ...row, is_active: on } : row)),+ );+ try {+ const response = await sendRequest<{ success?: boolean; skill?: unknown; error?: string }>('update_user_skill', {+ name,+ is_active: on,+ });+ if (failed(response)) throw new Error(response?.error || "Couldn't change that skill");+ } catch (error) {+ queryClient.setQueryData(USER_SKILLS_QUERY_KEY, before);+ throw error;+ } finally {+ void refresh();+ }+ };++ /** Add a built-in skill to the library (or switch its copy back on). */+ const add = async (skill: AvailableSkill) => {+ const title = skillTitle(skill);+ if (library().some((row) => row.name === skill.skillName)) {+ await setOn(skill.skillName, true);+ return;+ }+ const content = await sendRequest<{ success?: boolean; instructions?: string; error?: string }>('get_skill_content', {+ skill_name: skill.skillName,+ });+ if (!content?.success || !content.instructions) throw new Error(`Couldn't read ${title}`);+ const created = await sendRequest<{ success?: boolean; skill?: unknown; error?: string }>('create_user_skill', {+ name: skill.skillName,+ display_name: title,+ description: skill.description,+ instructions: content.instructions,+ category: typeof skill.metadata?.category === 'string' ? skill.metadata.category : 'custom',+ icon: skill.icon,+ color: skill.color,+ metadata: skill.metadata ?? {},+ });+ if (failed(created)) {+ // Another tab may have added it a moment ago: switch that copy on.+ await refresh();+ if (library().some((row) => row.name === skill.skillName)) {+ await setOn(skill.skillName, true);+ return;+ }+ throw new Error(created?.error || `Couldn't add ${title}`);+ }+ await refresh();+ };++ /** Write a new skill: a title and plain-words instructions. */+ const create = async (title: string, instructions: string) => {+ const name = await librarySkillName(sendRequest, title, library());+ const summary = firstSentence(instructions);+ const created = await sendRequest<{ success?: boolean; skill?: unknown; error?: string }>('create_user_skill', {+ name,+ display_name: title,+ description: summary ? `${title}: ${summary}` : title,+ instructions,+ category: 'custom',+ // No icon: the card shows the skill's initials (the handler's+ // default, "star", is not an icon reference).+ icon: '',+ metadata: { title, summary },+ });+ if (failed(created)) throw new Error(created?.error || `Couldn't create ${title}`);+ await refresh();+ return name;+ };++ const remove = async (name: string) => {+ const response = await sendRequest<{ success?: boolean; error?: string }>('delete_user_skill', { name });+ if (!response?.success) throw new Error(response?.error || "Couldn't remove that skill");+ await refresh();+ };++ return { add, create, setOn, remove };+ }, [sendRequest, queryClient]);+}diff --git a/client/src/features/home/data/usage.ts b/client/src/features/home/data/usage.tsnew file mode 100644index 00000000..53553929--- /dev/null+++ b/client/src/features/home/data/usage.ts@@ -0,0 +1,34 @@+/**+ * Settings > Billing's usage (`get_employee_usage`): the team's completed+ * tasks so far this month, counted on the server from the run records in+ * the owner's time zone. Refetched whenever Billing opens, because runs+ * finish while it is closed.+ */++import { useQuery } from '@tanstack/react-query';+import { z } from 'zod';+import { useWebSocketActions } from '@/contexts/WebSocketContext';++export const EMPLOYEE_USAGE_QUERY_KEY = ['employeeUsage'] as const;++const usageSchema = z.object({ tasks_this_month: z.number().int().min(0) });++export interface EmployeeUsage {+ tasksThisMonth: number;+}++export function useEmployeeUsageQuery() {+ const { sendRequest, isReady } = useWebSocketActions();+ return useQuery<EmployeeUsage, Error>({+ queryKey: EMPLOYEE_USAGE_QUERY_KEY,+ queryFn: async () => {+ const response = await sendRequest<{ success?: boolean; error?: string }>('get_employee_usage', {});+ if (response?.success === false) throw new Error(response.error || "Couldn't count this month's tasks");+ const parsed = usageSchema.safeParse(response);+ if (!parsed.success) throw new Error("Couldn't count this month's tasks");+ return { tasksThisMonth: parsed.data.tasks_this_month };+ },+ enabled: isReady,+ refetchOnMount: 'always',+ });+}diff --git a/client/src/features/home/employee/EmployeeView.tsx b/client/src/features/home/employee/EmployeeView.tsxindex 28ce781f..6ed29bc8 100644--- a/client/src/features/home/employee/EmployeeView.tsx+++ b/client/src/features/home/employee/EmployeeView.tsx@@ -70,7 +70,7 @@ function TaskBox({ employee }: { employee: EmployeeSummary }) {],{ duration: 520, easing: 'spring', fill: 'backwards' },);- animate(text?.closest('[data-employee]'), [{ borderColor: 'var(--status-working-border)' }, { borderColor: 'var(--border-default)' }], {+ animate(text?.closest('[data-employee]'), [{ borderColor: 'var(--glow-task)' }, { borderColor: 'var(--border-default)' }], {duration: 'glow',fill: 'none',});diff --git a/client/src/features/home/genui/__tests__/HireDraftPanel.test.tsx b/client/src/features/home/genui/__tests__/HireDraftPanel.test.tsxindex df176776..71c2451d 100644--- a/client/src/features/home/genui/__tests__/HireDraftPanel.test.tsx+++ b/client/src/features/home/genui/__tests__/HireDraftPanel.test.tsx@@ -24,7 +24,6 @@ vi.mock('../../data/connectors', () => ({useConnectors: () => ({providers: [{ id: 'whatsapp', name: 'WhatsApp', consumer_category: 'messages', connected: false }],categories: [],- connectedCount: 0,connectedApps: [],hasAi: true,isLoading: false,diff --git a/client/src/features/home/genui/__tests__/draftStore.test.ts b/client/src/features/home/genui/__tests__/draftStore.test.tsindex 8c750a5f..800a1a9b 100644--- a/client/src/features/home/genui/__tests__/draftStore.test.ts+++ b/client/src/features/home/genui/__tests__/draftStore.test.ts@@ -6,6 +6,7 @@*/import { afterEach, describe, expect, it, vi } from 'vitest';+import { SPIKE, orbState } from '../../orb/orb';import corpus from '../__fixtures__/replies.json';import {HISTORY_TURNS,@@ -134,6 +135,18 @@ describe('submitDraft', () => {setRefining(true);expect(useDraftStore.getState().refining).toBe(false);});++ it('spikes the orb when a setup is ready, and less when it fails', async () => {+ orbState.spike = 0;+ const send = vi.fn<Send>().mockResolvedValue({ success: true, reply: GOOD_REPLY });+ await submitDraft(send, 'job');+ expect(orbState.spike).toBe(SPIKE.draftReady);+ orbState.spike = 0;+ send.mockResolvedValueOnce({ success: false, error: 'timeout' });+ await submitDraft(send, 'job');+ expect(orbState.spike).toBe(SPIKE.draftFailed);+ orbState.spike = 0;+ });});describe('beginHire', () => {diff --git a/client/src/features/home/genui/draftStore.ts b/client/src/features/home/genui/draftStore.tsindex 3fb0679e..dd53bfc6 100644--- a/client/src/features/home/genui/draftStore.ts+++ b/client/src/features/home/genui/draftStore.ts@@ -23,6 +23,7 @@ import { useMemo } from 'react';import { create } from 'zustand';import { useWebSocketActions } from '@/contexts/WebSocketContext';import { appRefSchema, type AppRef } from '../data/schemas';+import { SPIKE, spikeOrb } from '../orb/orb';import { setPath, type UiState } from './expressions';import { normalizeSpec, type NormalizedSpec } from './normalize';import { parseReply } from './parse';@@ -190,6 +191,7 @@ export function failRequest(token: string, code: SetupErrorCode, request: Pendin// Cancelled by a newer request or by Discard; whoever did that owns the state.if (code === 'cancelled') return false;useDraftStore.setState({ status: 'failed', token: null, failure: { code, ...request } });+ spikeOrb(SPIKE.draftFailed);return true;}@@ -216,6 +218,7 @@ export function acceptReply(token: string, response: SetupResponse, request: Penapps: parseApps(response.apps),version: state.version + 1,});+ spikeOrb(SPIKE.draftReady);return true;}diff --git a/client/src/features/home/genui/index.ts b/client/src/features/home/genui/index.tsindex 0a0a546b..a620115c 100644--- a/client/src/features/home/genui/index.ts+++ b/client/src/features/home/genui/index.ts@@ -7,3 +7,4 @@export { HireDraftPanel } from './HireDraftPanel';export { MessagePreview as DraftMessagePreview } from './render';export { useHireComposer } from './useHireComposer';+export { useStartHire } from './useStartHire';diff --git a/client/src/features/home/genui/useHireComposer.ts b/client/src/features/home/genui/useHireComposer.tsindex 641eb5e6..8a4f29d7 100644--- a/client/src/features/home/genui/useHireComposer.ts+++ b/client/src/features/home/genui/useHireComposer.ts@@ -12,6 +12,7 @@import { useCallback, useEffect, useRef } from 'react';import { useHomeStore } from '../state/homeStore';import { useDraftActions, useDraftStore } from './draftStore';+import { useStartHire } from './useStartHire';export function useHireComposer() {const value = useDraftStore((s) => s.input);@@ -20,6 +21,7 @@ export function useHireComposer() {const hiring = useDraftStore((s) => s.hiring);const failure = useDraftStore((s) => s.failure);const actions = useDraftActions();+ const { start } = useStartHire();// Open Connectors > AI once per "no AI model" answer.const handled = useRef<unknown>(null);@@ -40,6 +42,6 @@ export function useHireComposer() {onStopRefining: useCallback(() => actions.setRefining(false), [actions]),working: status === 'working' || hiring,/** A template: its job replaces whatever is in the box and is sent. */- pick: useCallback((job: string) => send(job, { refine: false }), [send]),+ pick: useCallback((job: string) => void start(job), [start]),};}diff --git a/client/src/features/home/genui/useStartHire.ts b/client/src/features/home/genui/useStartHire.tsnew file mode 100644index 00000000..d17827b3--- /dev/null+++ b/client/src/features/home/genui/useStartHire.ts@@ -0,0 +1,17 @@+/**+ * Start a new hire from a job written for the owner (a template chip, a+ * starter bundle in Settings > Plugins): the text goes to the setup model+ * as a fresh job, exactly as the composer would send it. `busy` while a+ * setup is being written or a hire is in flight, when a start would be+ * refused.+ */++import { useCallback } from 'react';+import { useDraftActions, useDraftStore } from './draftStore';++export function useStartHire() {+ const busy = useDraftStore((s) => s.status === 'working' || s.hiring);+ const actions = useDraftActions();+ const start = useCallback((job: string) => actions.submit(job, { refine: false }), [actions]);+ return { busy, start };+}diff --git a/client/src/features/home/hire/Composer.tsx b/client/src/features/home/hire/Composer.tsxindex d4ad3753..96f727ee 100644--- a/client/src/features/home/hire/Composer.tsx+++ b/client/src/features/home/hire/Composer.tsx@@ -91,7 +91,7 @@ export function Composer({boxRef.current?.focus();animate(surfaceRef.current,- [{ boxShadow: '0 0 0 0 var(--node-agent-edge)' }, { boxShadow: '0 0 0 6px transparent' }],+ [{ boxShadow: 'var(--glow-refine)' }, { boxShadow: 'var(--glow-refine-out)' }],{ duration: 900, fill: 'none' },);}, [refining]);diff --git a/client/src/features/home/hire/starters.json b/client/src/features/home/hire/starters.jsonnew file mode 100644index 00000000..81020709--- /dev/null+++ b/client/src/features/home/hire/starters.json@@ -0,0 +1,38 @@+[+ {+ "id": "receptionist",+ "label": "Receptionist",+ "role": "agent",+ "summary": "Answers customer messages and books appointments for you.",+ "job": "A receptionist who answers customer messages on WhatsApp, handles common questions and books appointments in my calendar.",+ "apps": ["WhatsApp", "Google Calendar"],+ "skills": ["write-like-a-person", "reply-in-their-language", "book-appointments"]+ },+ {+ "id": "inbox-assistant",+ "label": "Inbox assistant",+ "role": "model",+ "summary": "Sorts your email, flags what's urgent and drafts replies.",+ "job": "An inbox assistant who sorts my email every morning, flags anything urgent and drafts replies for me to approve.",+ "apps": ["Gmail"],+ "skills": ["write-like-a-person", "short-reports"]+ },+ {+ "id": "bookkeeper",+ "label": "Bookkeeper",+ "role": "workflow",+ "summary": "Tracks payments, chases unpaid invoices and reports weekly.",+ "job": "A bookkeeper who tracks payments in Stripe, politely chases unpaid invoices and sends me a weekly summary.",+ "apps": ["Stripe"],+ "skills": ["chase-late-payments", "short-reports"]+ },+ {+ "id": "social-media-helper",+ "label": "Social media helper",+ "role": "trigger",+ "summary": "Drafts posts about your business for you to approve.",+ "job": "A social media helper who drafts three posts a week about my business and sends them to me for approval.",+ "apps": [],+ "skills": ["social-posts", "write-like-a-person"]+ }+]diff --git a/client/src/features/home/hire/templates.ts b/client/src/features/home/hire/templates.tsindex fd592f8a..9bc72968 100644--- a/client/src/features/home/hire/templates.ts+++ b/client/src/features/home/hire/templates.ts@@ -1,35 +1,32 @@/**- * Starter jobs for the hire composer (design handoff "Template chips"): a- * label, the role colour it wears, and the plain-English job it sends.+ * Starter jobs (design handoff "Template chips" and Settings > Plugins).+ * One list, in starters.json, serves both: the chips under the composer+ * send a starter's job, and Plugins installs a starter (its skills into the+ * library, then its job to the setup model).+ *+ * Each starter names the apps its job needs; the job text names them too,+ * since it is all the setup model reads. The skills are built-ins from the+ * employee folder. server/tests/test_home_catalog_contract.py checks both.*/-import type { ColorRole } from '../data/schemas';+import { z } from 'zod';+import { COLOR_ROLES } from '../data/schemas';+import starters from './starters.json';-export interface HireTemplate {- label: string;- role: ColorRole;- job: string;-}+const starterSchema = z.object({+ id: z.string().min(1),+ label: z.string().min(1),+ role: z.enum(COLOR_ROLES),+ summary: z.string().min(1),+ job: z.string().min(1),+ apps: z.array(z.string().min(1)),+ skills: z.array(z.string().min(1)).min(1),+});-export const HIRE_TEMPLATES: readonly HireTemplate[] = [- {- label: 'Receptionist',- role: 'agent',- job: 'A receptionist who answers customer messages on WhatsApp, handles common questions and books appointments in my calendar.',- },- {- label: 'Inbox assistant',- role: 'model',- job: 'An inbox assistant who sorts my email every morning, flags anything urgent and drafts replies for me to approve.',- },- {- label: 'Bookkeeper',- role: 'workflow',- job: 'A bookkeeper who tracks payments in Stripe, politely chases unpaid invoices and sends me a weekly summary.',- },- {- label: 'Social media helper',- role: 'trigger',- job: 'A social media helper who drafts three posts a week about my business and sends them to me for approval.',- },-];+export type Starter = z.infer<typeof starterSchema>;++export const STARTERS: readonly Starter[] = z.array(starterSchema).parse(starters);++/** The composer's chips read the same list. */+export type HireTemplate = Starter;+export const HIRE_TEMPLATES = STARTERS;diff --git a/client/src/features/home/orb/orb.ts b/client/src/features/home/orb/orb.tsindex c5078c6e..32cf7882 100644--- a/client/src/features/home/orb/orb.ts+++ b/client/src/features/home/orb/orb.ts@@ -12,7 +12,18 @@ import { prefersReducedMotion } from '@/lib/useReducedMotion';/** The prototype's energy levels and event bursts. */export const ENERGY = { idle: 0.15, focus: 0.35, typing: 0.55, generating: 1 } as const;-export const SPIKE = { hire: 1, connect: 0.7, theme: 1, mode: 0.9, task: 0.35 } as const;+export const SPIKE = {+ hire: 1,+ connect: 0.7,+ theme: 1,+ mode: 0.9,+ task: 0.35,+ settings: 0.5,+ workspace: 0.5,+ draftReady: 0.8,+ draftFailed: 0.4,+ profileSaved: 0.7,+} as const;/** Read by the engine every frame; the engine decays `spike` itself. */export const orbState = {diff --git a/client/src/features/home/orb/orbEngine.ts b/client/src/features/home/orb/orbEngine.tsindex e5331d3b..a8f87eba 100644--- a/client/src/features/home/orb/orbEngine.ts+++ b/client/src/features/home/orb/orbEngine.ts@@ -68,11 +68,14 @@ export function createOrbEngine(onLost: () => void) {const amb = new AmbientLight(0xffffff, 0.35 * PI);const key = new DirectionalLight(0xffffff, 1.1 * PI);key.position.set(3, 4, 5);+ // Rim light: off in dark, it puts the white highlights on the light theme's black.+ const rim = new DirectionalLight(0xffffff, 0);+ rim.position.set(-4, 3, -2);const p1 = new PointLight(0xbd93f9, 2.4 * POINT, 20, 0);p1.position.set(-3, 1, 3);const p2 = new PointLight(0x8be9fd, 2.4 * POINT, 20, 0);p2.position.set(3, -1.5, 2.5);- scene.add(amb, key, p1, p2);+ scene.add(amb, rim, key, p1, p2);const c = document.createElement('canvas');c.width = c.height = 128;@@ -86,11 +89,13 @@ export function createOrbEngine(onLost: () => void) {g.fillRect(0, 0, 128, 128);}const glowTex = new CanvasTexture(c);+ const sprites: Sprite[] = [];const glow = (color: number, size: number, opacity: number) => {const s = new Sprite(new SpriteMaterial({ map: glowTex, color, transparent: true, opacity, blending: AdditiveBlending, depthWrite: false }),);s.scale.setScalar(size);+ sprites.push(s);return s;};@@ -99,7 +104,7 @@ export function createOrbEngine(onLost: () => void) {orb.add(tilt);scene.add(orb);- // Ring: vertex colours purple -> cyan by angle; the light theme's greys kept beside them.+ // Ring: vertex colours purple -> cyan by angle; the light theme's near-blacks kept beside them.const rg = new TorusGeometry(1.2, 0.24, 48, 220);const pos = rg.attributes.position;const ringDark = new Float32Array(pos.count * 3);@@ -107,7 +112,7 @@ export function createOrbEngine(onLost: () => void) {const tmp = new Color();const pairs = [[new Color(0xbd93f9), new Color(0x8be9fd), ringDark],- [new Color(0x1a1d21), new Color(0x3a3f47), ringLight],+ [new Color(0x050506), new Color(0x16181c), ringLight],] as const;for (let i = 0; i < pos.count; i++) {const t = (Math.sin(Math.atan2(pos.getY(i), pos.getX(i)) - 0.8) + 1) / 2;@@ -147,14 +152,14 @@ export function createOrbEngine(onLost: () => void) {const pk = glow(col, 0.45, 0.9);orb.add(m, line, pk);const cd = new Color(col);- const cl = new Color([0x1a1d21, 0x2b2f37][i % 2]);+ const cl = new Color([0x060607, 0x0e0f12][i % 2]);return { m, mat, halo, line, pk, cd, cl, phase: (i * PI) / 2 + PI / 4, r: 2.0 + (i % 2) * 0.15, off: Math.random() };});const N = 900;const pp = new Float32Array(N * 3);const pc = new Float32Array(N * 3);- const pal = [0x8be9fd, 0xbd93f9, 0x6272a4, 0xff79c6].map((hex) => new Color(hex));+ const pal = [0xffffff, 0xf8f8f2, 0xe8eaed, 0xffffff].map((hex) => new Color(hex));for (let i = 0; i < N; i++) {const r = 3 + Math.random() * 6;const th = Math.random() * PI * 2;@@ -181,12 +186,14 @@ export function createOrbEngine(onLost: () => void) {const tc = {lD: new Color(0x6272a4),- lL: new Color(0x6b7280),+ lL: new Color(0x1a1d21),eD: new Color(0x2a1d4a),black: new Color(0x000000),+ white: new Color(0xffffff),gD: new Color(0xf8f8f2),- gL: new Color(0x1a1d21),- cK: new Color(0x111317),+ cK: new Color(0x030303),+ p1: new Color(0xbd93f9),+ p2: new Color(0x8be9fd),};const bez = new QuadraticBezierCurve3(new Vector3(), new Vector3(), new Vector3());const vh = 2 * 9 * Math.tan((17.5 * PI) / 180);@@ -220,6 +227,7 @@ export function createOrbEngine(onLost: () => void) {let lf = document.documentElement.classList.contains('dark') ? 0 : 1;let lfApplied = -1;let appliedLight: boolean | null = null;+ let ptBase = 0.6;const loop = (now: number) => {raf = requestAnimationFrame(loop);@@ -279,15 +287,15 @@ export function createOrbEngine(onLost: () => void) {n.pk.material.opacity = 0.3 + e * 0.7;});- // Light theme: monochrome, blended over ~0.3 s.+ // Light theme: glossy piano-black, blended over ~0.3 s.const light = !document.documentElement.classList.contains('dark');- ptsMat.opacity += ((light ? 0.45 : 0.6) - ptsMat.opacity) * k;+ ptBase += ((light ? 0.85 : 0.8) - ptBase) * k;pts.rotation.y += dt * 0.02 * mot * (1 + e * 3);pts.rotation.x = rx * 0.3;lf += ((light ? 1 : 0) - lf) * Math.min(1, dt * 3.2);nodes.forEach((n) => n.line.material.color.copy(tc.lD).lerp(tc.lL, lf));ringMat.emissive.copy(tc.eD).lerp(tc.black, lf);- coreGlow.material.color.copy(tc.gD).lerp(tc.gL, lf);+ coreGlow.material.color.copy(tc.gD).lerp(tc.black, lf);ringMat.iridescence = 0.7 * (1 - lf);ringMat.metalness = 0.25 * (1 - lf);ringMat.emissiveIntensity = 0.5 - 0.2 * lf;@@ -302,35 +310,49 @@ export function createOrbEngine(onLost: () => void) {nodes.forEach((n) => {n.mat.color.copy(n.cd).lerp(n.cl, lf);n.mat.emissive.copy(n.cd).lerp(tc.black, lf);- n.pk.material.color.copy(n.cd).lerp(tc.gL, lf);+ n.pk.material.color.setScalar(1 - lf);+ n.halo.material.color.copy(n.mat.color);});const pa = pg.attributes.color.array as Float32Array;for (let i = 0; i < pa.length; i += 3) {- pa[i] = ptDark[i] + (0.3 - ptDark[i]) * lf;- pa[i + 1] = ptDark[i + 1] + (0.31 - ptDark[i + 1]) * lf;- pa[i + 2] = ptDark[i + 2] + (0.33 - ptDark[i + 2]) * lf;+ pa[i] = ptDark[i] - ptDark[i] * lf;+ pa[i + 1] = ptDark[i + 1] - ptDark[i + 1] * lf;+ pa[i + 2] = ptDark[i + 2] + (0.01 - ptDark[i + 2]) * lf;}pg.attributes.color.needsUpdate = true;}- ringMat.clearcoat = 1 - 0.6 * lf;- ringMat.roughness = 0.18 + 0.2 * lf;+ ringMat.clearcoatRoughness = 0.1 - 0.06 * lf;+ ringMat.roughness = 0.18 - 0.08 * lf;+ coreMat.roughness = 0.3 - 0.2 * lf;nodes.forEach((n) => {- n.mat.emissiveIntensity = 0.35 - 0.2 * lf;- n.mat.clearcoat = 1 - 0.6 * lf;- n.halo.material.opacity = 0.5 - 0.3 * lf;+ n.mat.emissiveIntensity = 0.35 * (1 - lf);+ n.mat.roughness = 0.25 - 0.15 * lf;+ n.halo.material.opacity = 0.5 - 0.35 * lf;});- ringGlow.material.opacity *= 1 - 0.8 * lf;- coreGlow.material.opacity *= 1 - 0.9 * lf;- R.toneMappingExposure = 1.1 - 0.1 * lf;- amb.intensity = (0.35 + 0.2 * lf) * PI;- key.intensity = (1.1 - 0.4 * lf) * PI;+ R.toneMappingExposure = 1.1 - 0.2 * lf;+ amb.intensity = (0.35 - 0.2 * lf) * PI;+ key.intensity = (1.1 + 1.4 * lf) * PI;+ rim.intensity = 2.2 * lf * PI;p1.intensity = p2.intensity = (2.4 - 1.2 * lf) * POINT;+ p1.color.copy(tc.p1).lerp(tc.white, lf);+ p2.color.copy(tc.p2).lerp(tc.white, lf);++ // Additive glow vanishes on white, so light uses normal blending. The swap+ // happens at lf .5, where sprites and particles fade through zero. Runs+ // last: every opacity above is reset each frame before this scales it.const wantLight = lf > 0.5;if (appliedLight !== wantLight) {appliedLight = wantLight;- ptsMat.blending = ringGlow.material.blending = wantLight ? NormalBlending : AdditiveBlending;- ptsMat.needsUpdate = ringGlow.material.needsUpdate = true;+ for (const material of [ptsMat, ...sprites.map((sprite) => sprite.material)]) {+ material.blending = wantLight ? NormalBlending : AdditiveBlending;+ material.needsUpdate = true;+ }}+ const xf = Math.min(1, Math.abs(lf - 0.5) * 4);+ ptsMat.opacity = ptBase * xf;+ ptsMat.size = 0.08 + 0.02 * lf;+ const sk = xf * (wantLight ? 0.5 : 1);+ for (const sprite of sprites) sprite.material.opacity *= sk;R.render(scene, cam);};diff --git a/client/src/features/home/settings/BillingTab.tsx b/client/src/features/home/settings/BillingTab.tsxnew file mode 100644index 00000000..c78650d5--- /dev/null+++ b/client/src/features/home/settings/BillingTab.tsx@@ -0,0 +1,44 @@+/**+ * Settings > Billing, usage only: what the team did this month, and how+ * many employees it has (the sidebar's count). No billing account sits+ * behind OpenCompany yet, so there are no plans, payment method or+ * invoices (docs-internal/normal_mode.md, Known gaps). A count that can't+ * be read shows a dash, never a false zero.+ */++import { Skeleton } from '@/components/ui/skeleton';+import { useEmployeesQuery } from '../data/employees';+import { useEmployeeUsageQuery } from '../data/usage';+import { MicroLabel } from '../ui/primitives';++function Stat({ label, value, loading }: { label: string; value: number | null; loading: boolean }) {+ return (+ <div className="flex flex-col gap-1.5 rounded-card border border-border-default bg-bg-elevated p-4">+ <MicroLabel>{label}</MicroLabel>+ {loading ? (+ <Skeleton className="h-7 w-14" />+ ) : (+ <span className="text-title font-semibold tracking-[-0.02em] text-fg-default tabular-nums">{value ?? '—'}</span>+ )}+ </div>+ );+}++export function BillingTab() {+ const usage = useEmployeeUsageQuery();+ const team = useEmployeesQuery();+ return (+ <div className="flex max-w-170 flex-col gap-5 px-8 pt-7 pb-8">+ <div data-stagger className="flex flex-col gap-1 pr-9">+ <h2 className="text-lg font-semibold tracking-[-0.01em] text-fg-default">Billing</h2>+ <p className="text-sm text-pretty text-fg-muted">What your employees have done this month.</p>+ </div>+ <div data-stagger className="grid grid-cols-[repeat(auto-fit,minmax(180px,1fr))] gap-2.5">+ <Stat label="Tasks done this month" value={usage.data?.tasksThisMonth ?? null} loading={usage.isPending} />+ <Stat label="Employees" value={team.data?.length ?? null} loading={team.isPending} />+ </div>+ </div>+ );+}++export default BillingTab;diff --git a/client/src/features/home/settings/CatalogLayout.tsx b/client/src/features/home/settings/CatalogLayout.tsxnew file mode 100644index 00000000..7c0e8b35--- /dev/null+++ b/client/src/features/home/settings/CatalogLayout.tsx@@ -0,0 +1,390 @@+/**+ * The shared catalog page behind Settings > Skills, Connectors and Plugins+ * (design handoff "Settings: Billing, Skills, Plugins"): a title with Yours /+ * Discover, search, an optional category filter and primary action, and a+ * grid of cards.+ *+ * Every rule follows from the props and the item data, never from which+ * page is showing:+ * - the page supplies both lists, and Yours counts its own;+ * - the category filter exists when there are categories, and starts open+ * when the page is opened on one;+ * - Discover shows DISCOVER_LIMIT cards until "Show all";+ * - a card offers remove only with `onRemove`, and a switch only with+ * `onToggle`;+ * - a card glows when its item turns 'added' while it is on screen, then+ * `onItemAdded` runs (never on first render).+ *+ * The view, search and filter live here, so they start fresh each time the+ * page mounts (the Settings tabs unmount when hidden).+ */++import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';+import { ArrowRight, BadgeCheck, Check, LoaderCircle, Plus, SlidersHorizontal } from 'lucide-react';+import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import { Skeleton } from '@/components/ui/skeleton';+import { Switch } from '@/components/ui/switch';+import { Toggle } from '@/components/ui/toggle';+import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';+import { animate } from '@/lib/motion';+import { cn } from '@/lib/utils';+import { AppMark, SearchField } from '../ui/primitives';+import { DISCOVER_LIMIT, catalogSlice, type CatalogItem, type CatalogView } from './catalog';+import { staggerSettings } from './stagger';++export interface CatalogLayoutProps {+ title: string;+ /** Also the search box's accessible name. */+ searchPlaceholder: string;+ yours: { items: CatalogItem[]; sectionTitle: string; empty: { title: string; detail: string } };+ discover: { items: CatalogItem[]; sectionTitle: string };+ loading?: boolean;+ categories?: { key: string; label: string }[];+ initialCategory?: string;+ verbs: { add: string; remove?: string; busy?: string };+ onAdd: (item: CatalogItem) => void;+ onRemove?: (item: CatalogItem) => void;+ onToggle?: (item: CatalogItem, on: boolean) => void;+ onItemAdded?: (item: CatalogItem) => void;+ /** A header button that opens an inline form above the list. */+ primaryAction?: { label: string; form: (close: () => void) => ReactNode };+}++const GRID = '-mt-2 grid grid-cols-[repeat(auto-fill,minmax(300px,1fr))] gap-3';++export function CatalogLayout({+ title,+ searchPlaceholder,+ yours,+ discover,+ loading = false,+ categories = [],+ initialCategory = 'all',+ verbs,+ onAdd,+ onRemove,+ onToggle,+ onItemAdded,+ primaryAction,+}: CatalogLayoutProps) {+ const [view, setView] = useState<CatalogView>('discover');+ const [category, setCategory] = useState(initialCategory);+ const [filterOpen, setFilterOpen] = useState(initialCategory !== 'all');+ const [query, setQuery] = useState('');+ const [showAll, setShowAll] = useState(false);+ const [formOpen, setFormOpen] = useState(false);+ const rootRef = useRef<HTMLDivElement>(null);+ const shownKey = useRef(`${view}|${category}`);++ // The blocks rise in again on a new view or category. The first render is+ // the dialog's to stagger.+ useLayoutEffect(() => {+ const key = `${view}|${category}`;+ if (shownKey.current === key) return;+ shownKey.current = key;+ staggerSettings(rootRef.current);+ }, [view, category]);++ const list = view === 'yours' ? yours.items : discover.items;+ const { shown, total } = catalogSlice(list, { category, query, cap: view === 'discover' && !showAll ? DISCOVER_LIMIT : null });+ const canShowAll = view === 'discover' && total > DISCOVER_LIMIT;+ const q = query.trim();++ const changeView = (next: CatalogView) => {+ setView(next);+ setShowAll(false);+ };+ const toggleFilter = (open: boolean) => {+ setFilterOpen(open);+ if (!open) setCategory('all');+ };++ const filtered = q !== '' || category !== 'all';+ const empty = filtered+ ? {+ title: q ? `Nothing matches “${q}”` : 'Nothing in this category',+ detail: q ? 'Try another word.' : 'Try another category.',+ discover: false,+ }+ : view === 'yours'+ ? { ...yours.empty, discover: true }+ : { title: 'Nothing here yet', detail: 'Check back soon.', discover: false };++ return (+ <div ref={rootRef} className="flex flex-col gap-5.5 px-8 pt-6.5 pb-8">+ <div data-stagger className="flex flex-wrap items-center gap-3.5 pr-10">+ <h2 className="text-xl font-semibold tracking-[-0.02em] text-fg-default">{title}</h2>+ <ToggleGroup+ type="single"+ variant="segmented"+ aria-label={`${title} to show`}+ value={view}+ onValueChange={(next) => next && changeView(next as CatalogView)}+ >+ <ToggleGroupItem value="yours" className="px-3 text-sm">+ Yours+ <span className="font-mono text-2xs font-normal text-fg-faint">{yours.items.length}</span>+ </ToggleGroupItem>+ <ToggleGroupItem value="discover" className="px-3 text-sm">+ Discover+ </ToggleGroupItem>+ </ToggleGroup>+ <div className="ml-auto flex flex-[1_1_280px] items-center justify-end gap-2">+ <SearchField value={query} onChange={setQuery} placeholder={searchPlaceholder} className="max-w-75 flex-1" />+ {categories.length > 0 && (+ <Toggle+ variant="chips"+ pressed={filterOpen}+ onPressedChange={toggleFilter}+ aria-label="Filter by category"+ title="Filter"+ className="size-9 rounded-row px-0 [&_svg:not([class*='size-'])]:size-4"+ >+ <SlidersHorizontal strokeWidth={1.75} />+ </Toggle>+ )}+ {primaryAction && (+ <Button+ variant="invert"+ size="lg"+ aria-expanded={formOpen}+ onClick={() => setFormOpen((open) => !open)}+ className="rounded-row pr-3.5 pl-3 font-semibold active:scale-97"+ >+ <Plus strokeWidth={2.2} />+ {primaryAction.label}+ </Button>+ )}+ </div>+ </div>++ {categories.length > 0 && filterOpen && (+ <ToggleGroup+ data-stagger+ type="single"+ variant="chips"+ size="lg"+ className="-mt-2 gap-2"+ aria-label="Category"+ value={category}+ onValueChange={(next) => next && setCategory(next)}+ >+ <ToggleGroupItem value="all">All</ToggleGroupItem>+ {categories.map((c) => (+ <ToggleGroupItem key={c.key} value={c.key}>+ {c.label}+ </ToggleGroupItem>+ ))}+ </ToggleGroup>+ )}++ {primaryAction && formOpen && (+ <div data-stagger className="flex flex-col gap-2.5 rounded-card border border-border-strong bg-bg-elevated p-4">+ {primaryAction.form(() => setFormOpen(false))}+ </div>+ )}++ <div data-stagger className="flex items-center gap-2.5">+ <span className="text-lead font-semibold whitespace-nowrap text-fg-default">+ {view === 'yours' ? yours.sectionTitle : discover.sectionTitle}+ </span>+ <Badge variant="outline" className="rounded-md border-border-default bg-bg-app px-1.75 font-mono text-2xs text-fg-muted">+ {total}+ </Badge>+ {canShowAll && (+ <Button variant="quiet" size="sm" onClick={() => setShowAll((all) => !all)} className="ml-auto text-row text-fg-default">+ {showAll ? 'Show less' : 'Show all'}+ <ArrowRight />+ </Button>+ )}+ </div>++ {loading && list.length === 0 ? (+ <div className={GRID}>+ {[0, 1, 2, 3].map((i) => (+ <Skeleton key={i} className="h-30 rounded-card" />+ ))}+ </div>+ ) : total > 0 ? (+ <div className={GRID}>+ {shown.map((item) => (+ <CatalogCard+ key={item.id}+ item={item}+ view={view}+ verbs={verbs}+ onAdd={onAdd}+ onRemove={onRemove}+ onToggle={onToggle}+ onItemAdded={onItemAdded}+ />+ ))}+ </div>+ ) : (+ <div+ data-stagger+ className="flex flex-col items-center gap-2.5 rounded-panel border border-dashed border-border-strong px-5 py-10 text-center"+ >+ <span className="text-base font-medium text-fg-default">{empty.title}</span>+ <span className="text-sm text-fg-muted">{empty.detail}</span>+ {empty.discover && (+ <Button+ variant="quiet"+ size="sm"+ onClick={() => changeView('discover')}+ className="mt-1 h-8 border-border-strong px-3.5 font-semibold text-fg-default"+ >+ Discover+ </Button>+ )}+ </div>+ )}+ </div>+ );+}++function CatalogCard({+ item,+ view,+ verbs,+ onAdd,+ onRemove,+ onToggle,+ onItemAdded,+}: {+ item: CatalogItem;+ view: CatalogView;+ verbs: CatalogLayoutProps['verbs'];+ onAdd: CatalogLayoutProps['onAdd'];+ onRemove?: CatalogLayoutProps['onRemove'];+ onToggle?: CatalogLayoutProps['onToggle'];+ onItemAdded?: CatalogLayoutProps['onItemAdded'];+}) {+ const ref = useRef<HTMLDivElement>(null);+ const lastState = useRef(item.state);+ const added = item.state === 'added';++ useEffect(() => {+ const before = lastState.current;+ lastState.current = item.state;+ if (item.state !== 'added' || before === 'added') return;+ animate(ref.current, [{ boxShadow: 'var(--glow-connect)' }, { boxShadow: '0 0 0 0 transparent' }], {+ duration: 1200,+ easing: 'default',+ fill: 'none',+ });+ onItemAdded?.(item);+ }, [item, onItemAdded]);++ return (+ <div+ ref={ref}+ data-catalog-item={item.id}+ data-stagger+ className={cn(+ 'flex gap-3.5 rounded-card border bg-bg-elevated p-4.5 transition-[border-color,translate,box-shadow] duration-(--dur-default) ease-(--ease-default) hover:-translate-y-0.5 hover:border-border-strong hover:shadow-popover motion-reduce:hover:translate-y-0',+ added ? 'border-status-working-border' : 'border-border-default',+ )}+ >+ <AppMark name={item.name} iconRef={item.tile.iconRef} tone={item.tile.tone} size="xl" />+ <div className="flex min-w-0 flex-1 flex-col gap-1">+ <div className="flex min-w-0 items-center gap-1.5">+ <span className="truncate text-lead font-semibold text-fg-default">{item.name}</span>+ {item.verified && (+ <BadgeCheck role="img" aria-label="Verified" strokeWidth={1.75} className="size-3.75 shrink-0 text-fg-faint" />+ )}+ </div>+ {item.description && <p className="line-clamp-2 text-row leading-snug text-fg-muted">{item.description}</p>}+ {item.byline && <span className="mt-0.5 text-sm text-fg-faint">{item.byline}</span>}+ {item.meta && <span className="mt-0.5 font-mono text-2xs text-fg-faint">{item.meta}</span>}+ </div>+ <div className="flex shrink-0 flex-col items-end gap-2">+ <CardAction item={item} view={view} verbs={verbs} onAdd={onAdd} onRemove={onRemove} onToggle={onToggle} />+ </div>+ </div>+ );+}++const DONE = 'size-8.5 rounded-lg border border-action-run-border bg-action-run-soft text-action-run-ink';++function CardAction({+ item,+ view,+ verbs,+ onAdd,+ onRemove,+ onToggle,+}: {+ item: CatalogItem;+ view: CatalogView;+ verbs: CatalogLayoutProps['verbs'];+ onAdd: CatalogLayoutProps['onAdd'];+ onRemove?: CatalogLayoutProps['onRemove'];+ onToggle?: CatalogLayoutProps['onToggle'];+}) {+ const removeVerb = verbs.remove ?? 'Remove';+ if (item.state === 'busy') {+ return (+ <span+ role="status"+ aria-label={`${item.name}: ${verbs.busy ?? 'Working…'}`}+ className="grid size-8.5 place-items-center rounded-lg border border-status-ready-border bg-status-ready-fill"+ >+ <LoaderCircle aria-hidden className="size-3.5 animate-spin text-status-ready-ink" />+ </span>+ );+ }+ if (view === 'discover') {+ if (item.state === 'available') {+ return (+ <Button+ variant="quiet"+ size="icon"+ aria-label={`${verbs.add} ${item.name}`}+ title={`${verbs.add} ${item.name}`}+ onClick={() => onAdd(item)}+ className="size-8.5 border-border-strong bg-bg-app text-fg-default hover:border-action-run-border hover:bg-action-run-soft hover:text-action-run-ink active:scale-92"+ >+ <Plus />+ </Button>+ );+ }+ return onRemove ? (+ <Button+ variant="quiet"+ size="icon"+ aria-label={`${removeVerb} ${item.name}`}+ title={`${removeVerb} ${item.name}`}+ onClick={() => onRemove(item)}+ className={cn(DONE, 'hover:border-action-stop-border hover:bg-action-stop-soft hover:text-action-stop-ink')}+ >+ <Check strokeWidth={2.2} />+ </Button>+ ) : (+ <span role="img" aria-label={`${item.name} added`} className={cn('grid place-items-center', DONE)}>+ <Check aria-hidden strokeWidth={2.2} className="size-4" />+ </span>+ );+ }+ return (+ <>+ {onToggle && (+ <Switch size="md" tone="run" checked={item.enabled ?? false} onCheckedChange={(on) => onToggle(item, on)} aria-label={item.name} />+ )}+ {onRemove && (+ <Button+ variant="quiet"+ size="xs"+ aria-label={`${removeVerb} ${item.name}`}+ onClick={() => onRemove(item)}+ className="mt-auto h-6.5 px-2 text-xs text-fg-faint hover:bg-action-stop-soft hover:text-action-stop-ink"+ >+ {removeVerb}+ </Button>+ )}+ </>+ );+}++export default CatalogLayout;diff --git a/client/src/features/home/settings/ConnectorsTab.tsx b/client/src/features/home/settings/ConnectorsTab.tsxindex 893f70c9..126f8693 100644--- a/client/src/features/home/settings/ConnectorsTab.tsx+++ b/client/src/features/home/settings/ConnectorsTab.tsx@@ -1,18 +1,18 @@/*** Settings > Connectors (design handoff): every app the owner can connect,- * searchable and grouped by consumer category, each with Connect or a- * Connected state and Disconnect.+ * on the shared catalog page. Discover lists them all, apps before AI+ * models; Yours lists the connected ones.*- * Connect opens the provider's own credential panel (ConnectDialog).+ * "+" opens the provider's own credential panel (ConnectDialog).* Disconnect removes what the panel would remove for API-key and signed-in* providers, after a confirmation; for the rest (a paired phone, an email* account) it opens the panel, which owns those steps. A card glows and a* toast confirms only when a provider actually flips to connected while- * the tab is open, never on first render.+ * the page is open, never on first render. There is no custom connector:+ * nothing serves one yet, so the page has no Add button.*/-import { useEffect, useMemo, useRef, useState } from 'react';-import { Search } from 'lucide-react';+import { useMemo, useState } from 'react';import {AlertDialog,AlertDialogAction,@@ -23,17 +23,11 @@ import {AlertDialogHeader,AlertDialogTitle,} from '@/components/ui/alert-dialog';-import { Button } from '@/components/ui/button';-import { Input } from '@/components/ui/input';-import { Skeleton } from '@/components/ui/skeleton';-import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';import { useWebSocketActions } from '@/contexts/WebSocketContext';-import { animate } from '@/lib/motion';-import { cn } from '@/lib/utils';-import { filterProviders, isConnected, useConnectors, type ConsumerProvider } from '../data/connectors';-import { useHomeStore } from '../state/homeStore';-import { AppMark, StatusDot } from '../ui/primitives';+import { isConnected, useConnectors, type ConsumerProvider } from '../data/connectors';import { pillToast } from '../ui/pillToast';+import type { CatalogItem } from './catalog';+import { CatalogLayout } from './CatalogLayout';/** Remove a provider's credential the way its panel would. False when the* panel has to do it (QR pairing, the IMAP/SMTP account). */@@ -55,95 +49,40 @@ async function disconnect(return false;}-function ConnectorCard({- provider,- onConnect,- onDisconnect,-}: {- provider: ConsumerProvider;- onConnect: () => void;- onDisconnect: () => void;-}) {+function toItem(provider: ConsumerProvider): CatalogItem {const connected = isConnected(provider);- const ref = useRef<HTMLDivElement>(null);- const wasConnected = useRef(connected);-- useEffect(() => {- if (connected && !wasConnected.current) {- animate(- ref.current,- [- { boxShadow: '0 0 0 1px var(--action-run-border), 0 0 28px var(--status-working-border)' },- { boxShadow: '0 0 0 0 transparent' },- ],- { duration: 1200, easing: 'default', fill: 'none' },- );- pillToast(`${provider.name} is connected`);- }- wasConnected.current = connected;- }, [connected, provider.name]);-- return (- <div- ref={ref}- data-connector={provider.id}- data-stagger- className={cn(- 'flex gap-3 rounded-card border bg-bg-elevated p-3.5 transition-[border-color,translate] duration-(--dur-slow) hover:-translate-y-px motion-reduce:hover:translate-y-0',- connected ? 'border-status-working-border' : 'border-border-default',- )}- >- <AppMark name={provider.name} iconRef={provider.icon_ref} size="lg" />- <div className="flex min-w-0 flex-1 flex-col gap-1">- <div className="flex items-center gap-2">- <span className="truncate text-base font-semibold text-fg-default">{provider.name}</span>- {provider.runs_locally && (- <span className="rounded-sm border border-node-workflow-edge px-1.25 font-mono text-[10px] font-medium tracking-label text-node-workflow-ink">- LOCAL- </span>- )}- </div>- {provider.description && <p className="text-meta leading-relaxed text-pretty text-fg-muted">{provider.description}</p>}- <div className="mt-1.5 flex min-h-7 items-center gap-2">- {connected ? (- <>- <StatusDot tone="working" className="size-1.5 shadow-[0_0_6px_var(--status-working-dot)]" />- <span className="truncate text-xs font-medium text-status-working-ink">- Connected{provider.account_label ? ` as ${provider.account_label}` : ''}- </span>- <Button- variant="quiet"- size="xs"- onClick={onDisconnect}- className="ml-auto h-6.5 rounded-lg px-2.5 hover:border-action-stop-border hover:bg-action-stop-soft hover:text-action-stop-ink"- >- Disconnect- </Button>- </>- ) : (- <Button- variant="quiet"- size="xs"- onClick={onConnect}- className="h-7 rounded-lg border-border-strong px-3 font-semibold text-fg-default hover:border-action-run-border hover:bg-action-run-soft hover:text-action-run-ink"- >- Connect- </Button>- )}- </div>- </div>- </div>- );+ const meta = [+ connected && provider.account_label ? `Connected as ${provider.account_label}` : null,+ provider.runs_locally ? 'Runs on this computer' : null,+ ]+ .filter(Boolean)+ .join(' · ');+ return {+ id: provider.id,+ name: provider.name,+ description: provider.description,+ byline: provider.publisher ? `by ${provider.publisher}` : undefined,+ verified: provider.verified,+ category: provider.consumer_category,+ meta: meta || undefined,+ tile: { iconRef: provider.icon_ref },+ state: connected ? 'added' : 'available',+ };}-export function ConnectorsTab({ onConnect }: { onConnect: (providerId: string) => void }) {- const { providers, categories, connectedCount, isLoading } = useConnectors();- const category = useHomeStore((s) => s.settingsCategory);- const setCategory = useHomeStore((s) => s.setSettingsCategory);+export function ConnectorsTab({+ onConnect,+ initialCategory = 'all',+}: {+ onConnect: (providerId: string) => void;+ initialCategory?: string;+}) {+ const { providers, categories, isLoading } = useConnectors();const { sendRequest } = useWebSocketActions();- const [query, setQuery] = useState('');const [confirming, setConfirming] = useState<ConsumerProvider | null>(null);- const shown = useMemo(() => filterProviders(providers, query, category), [providers, query, category]);+ const byId = useMemo(() => new Map(providers.map((provider) => [provider.id, provider])), [providers]);+ const items = useMemo(() => providers.map(toItem), [providers]);+ const connected = useMemo(() => items.filter((item) => item.state === 'added'), [items]);const confirmDisconnect = async () => {const provider = confirming;@@ -159,63 +98,24 @@ export function ConnectorsTab({ onConnect }: { onConnect: (providerId: string) =};return (- <div className="flex flex-col gap-4.5 px-8 pt-7 pb-8">- <div data-stagger className="flex items-start gap-4 pr-9">- <div className="flex flex-1 flex-col gap-1">- <h2 className="text-lg font-semibold text-fg-default">Connectors</h2>- <p className="text-sm text-pretty text-fg-muted">- Give your agents access to the apps you use. Credentials stay on this device.- </p>- </div>- <span className="shrink-0 rounded-pill border border-action-run-border bg-action-run-soft px-2.5 py-1 font-mono text-2xs font-medium tracking-label text-action-run-ink uppercase">- {connectedCount} connected- </span>- </div>-- <div data-stagger className="flex flex-wrap items-center gap-2">- <div className="relative min-w-0 flex-[1_1_220px]">- <Search aria-hidden className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-fg-faint" />- <Input- value={query}- onChange={(event) => setQuery(event.target.value)}- placeholder="Search connectors"- aria-label="Search connectors"- className="h-9.5 bg-bg-app pl-8.5 text-base md:text-base dark:bg-bg-app"- />- </div>- <ToggleGroup- type="single"- variant="chips"- size="lg"- className="gap-2"- aria-label="Category"- value={category}- onValueChange={(next) => next && setCategory(next)}- >- <ToggleGroupItem value="all">All</ToggleGroupItem>- {categories.map((c) => (- <ToggleGroupItem key={c.key} value={c.key}>- {c.label}- </ToggleGroupItem>- ))}- </ToggleGroup>- </div>-- <div className="grid grid-cols-[repeat(auto-fill,minmax(270px,1fr))] gap-2.5">- {isLoading && providers.length === 0- ? [0, 1, 2, 3].map((i) => <Skeleton key={i} className="h-28 rounded-card" />)- : shown.map((provider) => (- <ConnectorCard- key={provider.id}- provider={provider}- onConnect={() => onConnect(provider.id)}- onDisconnect={() => setConfirming(provider)}- />- ))}- </div>- {!isLoading && shown.length === 0 && (- <p className="text-sm text-fg-muted">No apps match {query ? `"${query}"` : 'this category'}.</p>- )}+ <>+ <CatalogLayout+ title="Connectors"+ searchPlaceholder="Search connectors"+ loading={isLoading}+ categories={categories}+ initialCategory={initialCategory}+ yours={{+ items: connected,+ sectionTitle: 'Connected',+ empty: { title: 'No apps connected yet', detail: 'Connect the apps your employees should work in.' },+ }}+ discover={{ items, sectionTitle: 'Top connectors' }}+ verbs={{ add: 'Connect', remove: 'Disconnect' }}+ onAdd={(item) => onConnect(item.id)}+ onRemove={(item) => setConfirming(byId.get(item.id) ?? null)}+ onItemAdded={(item) => pillToast(`${item.name} is connected`)}+ /><AlertDialog open={confirming !== null} onOpenChange={(open) => !open && setConfirming(null)}><AlertDialogContent>@@ -231,7 +131,7 @@ export function ConnectorsTab({ onConnect }: { onConnect: (providerId: string) =</AlertDialogFooter></AlertDialogContent></AlertDialog>- </div>+ </>);}diff --git a/client/src/features/home/settings/HomeSettings.tsx b/client/src/features/home/settings/HomeSettings.tsxindex 65650c37..97119499 100644--- a/client/src/features/home/settings/HomeSettings.tsx+++ b/client/src/features/home/settings/HomeSettings.tsx@@ -1,25 +1,132 @@/**- * Normal mode's Settings (design handoff "Settings modal"): Profile and- * Connectors behind a left nav, in the shared Modal with its spring- * entrance. Connect dialogs open on top from either tab (and from the- * employee card's "Connect {App}"), through `useHomeConnect`.+ * Normal mode's Settings (design handoff "Settings modal"): the pages+ * behind a left nav, in the shared Modal with its spring entrance. One+ * `PAGES` list drives both the nav and the panels. The nav's search keeps+ * the pages whose label or keywords match, and drops a group with none.+ * Connect dialogs open on top from Connectors (and from the employee card's+ * "Connect {App}"); HomeShell owns them.*/-import { Plug, User, X } from 'lucide-react';-import { useLayoutEffect, useRef } from 'react';+import { useId, useLayoutEffect, useRef, useState, type ReactNode } from 'react';+import { CircleUserRound, CreditCard, Grid2x2Plus, Plug, Star, X, type LucideIcon } from 'lucide-react';import { Tabs as TabsPrimitive } from 'radix-ui';import { OcLogo } from '@/components/brand/Logo';import { Button } from '@/components/ui/button';import Modal from '@/components/ui/Modal';-import { stagger } from '@/lib/motion';-import { cn } from '@/lib/utils';-import { useConnectors } from '../data/connectors';import { useHomeStore, type SettingsTab } from '../state/homeStore';+import { MicroLabel, SearchField } from '../ui/primitives';+import { BillingTab } from './BillingTab';import { ConnectorsTab } from './ConnectorsTab';+import { PluginsTab } from './PluginsTab';import { ProfileTab } from './ProfileTab';+import { SkillsTab } from './SkillsTab';+import { staggerSettings } from './stagger';const NAV_ITEM =- 'flex h-9 w-full items-center gap-2.5 rounded-lg px-2.5 text-left text-sm font-medium text-fg-muted outline-none transition-colors hover:bg-bg-hover hover:text-fg-default focus-visible:ring-3 focus-visible:ring-ring/50 data-[state=active]:bg-bg-hover data-[state=active]:text-fg-default';+ 'flex h-9 w-full items-center gap-2.5 rounded-lg px-2.5 text-left text-row font-medium text-fg-muted outline-none transition-colors hover:bg-bg-hover hover:text-fg-default focus-visible:ring-3 focus-visible:ring-ring/50 data-[state=active]:bg-bg-hover data-[state=active]:text-fg-default';++interface PageContext {+ close: () => void;+ onConnect: (providerId: string) => void;+ /** The category the page was opened on ('all' when none). */+ initialCategory: string;+}++interface Page {+ tab: SettingsTab;+ group: 'settings' | 'customize';+ label: string;+ icon: LucideIcon;+ /** Extra words the nav search matches. */+ keywords: string;+ render: (context: PageContext) => ReactNode;+}++const GROUPS = [+ { key: 'settings', label: 'Settings' },+ { key: 'customize', label: 'Customize' },+] as const;++const PAGES: Page[] = [+ {+ tab: 'profile',+ group: 'settings',+ label: 'Profile',+ icon: CircleUserRound,+ keywords: 'account name',+ render: ({ close }) => <ProfileTab onDone={close} />,+ },+ {+ tab: 'billing',+ group: 'settings',+ label: 'Billing',+ icon: CreditCard,+ keywords: 'plan invoices usage',+ render: () => <BillingTab />,+ },+ {+ tab: 'skills',+ group: 'customize',+ label: 'Skills',+ icon: Star,+ keywords: 'library abilities instructions',+ render: () => <SkillsTab />,+ },+ {+ tab: 'connectors',+ group: 'customize',+ label: 'Connectors',+ icon: Grid2x2Plus,+ keywords: 'apps',+ render: ({ onConnect, initialCategory }) => <ConnectorsTab onConnect={onConnect} initialCategory={initialCategory} />,+ },+ {+ tab: 'plugins',+ group: 'customize',+ label: 'Plugins',+ icon: Plug,+ keywords: 'bundles starters templates',+ render: () => <PluginsTab />,+ },+];++/** The nav column. Rendered inside the dialog, so its search starts empty+ * each time Settings opens. */+function SettingsNav() {+ const [query, setQuery] = useState('');+ const idBase = useId();+ const q = query.trim().toLowerCase();+ const matches = PAGES.filter((page) => !q || `${page.label} ${page.keywords}`.toLowerCase().includes(q));+ return (+ <div className="flex w-(--w-settings-nav) shrink-0 flex-col gap-0.5 overflow-y-auto border-r border-border-default px-3 py-4">+ <SearchField value={query} onChange={setQuery} placeholder="Search" label="Search settings" className="mb-1" />+ {GROUPS.map((group) => {+ const pages = matches.filter((page) => page.group === group.key);+ if (pages.length === 0) return null;+ const labelId = `${idBase}-${group.key}`;+ return (+ <div key={group.key} className="flex flex-col gap-0.5">+ <MicroLabel className="px-2.5 pt-3.5 pb-1.5">+ <span id={labelId}>{group.label}</span>+ </MicroLabel>+ <TabsPrimitive.List aria-labelledby={labelId} className="flex flex-col gap-0.5">+ {pages.map(({ tab, label, icon: Icon }) => (+ <TabsPrimitive.Trigger key={tab} value={tab} className={NAV_ITEM}>+ <Icon aria-hidden strokeWidth={1.75} className="size-4.25" />+ {label}+ </TabsPrimitive.Trigger>+ ))}+ </TabsPrimitive.List>+ </div>+ );+ })}+ <div className="mt-auto flex items-center gap-2 px-2.5 pt-3.5">+ <OcLogo size="settings" wordmark={false} />+ <span className="font-mono text-2xs text-fg-faint">Stored on this device</span>+ </div>+ </div>+ );+}export function HomeSettings({ onConnect }: { onConnect: (providerId: string) => void }) {const open = useHomeStore((s) => s.settingsOpen);@@ -27,22 +134,14 @@ export function HomeSettings({ onConnect }: { onConnect: (providerId: string) =>const category = useHomeStore((s) => s.settingsCategory);const setTab = useHomeStore((s) => s.setSettingsTab);const close = useHomeStore((s) => s.closeSettings);- const { connectedCount } = useConnectors();const bodyRef = useRef<HTMLDivElement>(null);- // The tab's blocks rise in, 30ms apart (design handoff "Settings modal").+ // The page's blocks rise in when the dialog opens or the page changes.useLayoutEffect(() => {- if (!open || !bodyRef.current) return;- stagger(- bodyRef.current.querySelectorAll('[data-stagger]'),- [- { opacity: 0, transform: 'translateY(10px)' },- { opacity: 1, transform: 'none' },- ],- { base: 40, step: 30, cap: 14, duration: 420, easing: 'spring' },- );- }, [open, tab, category]);+ if (open) staggerSettings(bodyRef.current);+ }, [open, tab]);+ const context: PageContext = { close, onConnect, initialCategory: category };return (<ModalisOpen={open}@@ -61,40 +160,16 @@ export function HomeSettings({ onConnect }: { onConnect: (providerId: string) =>onValueChange={(next) => setTab(next as SettingsTab)}className="flex h-full min-h-0">- <div className="flex w-(--w-settings-nav) shrink-0 flex-col gap-1 border-r border-border-default px-3 py-5">- <div className="flex items-center gap-2 px-2.5 pb-3.5">- <OcLogo size="settings" wordmark={false} />- <span className="text-md font-semibold text-fg-default">Settings</span>- </div>- <TabsPrimitive.List aria-label="Settings" className="flex flex-col gap-1">- <TabsPrimitive.Trigger value="profile" className={NAV_ITEM}>- <User aria-hidden className="size-4" />- Profile- </TabsPrimitive.Trigger>- <TabsPrimitive.Trigger value="connectors" className={NAV_ITEM}>- <Plug aria-hidden className="size-4" />- Connectors- <span className="ml-auto font-mono text-2xs text-status-working-ink">{connectedCount}</span>- </TabsPrimitive.Trigger>- </TabsPrimitive.List>- <p className="mt-auto px-2.5 font-mono text-2xs text-fg-faint">Stored on this device</p>- </div>+ <SettingsNav /><div ref={bodyRef} className="relative min-w-0 flex-1 overflow-y-auto">- <TabsPrimitive.Content value="profile" className="outline-none">- <ProfileTab onDone={close} />- </TabsPrimitive.Content>- <TabsPrimitive.Content value="connectors" className="outline-none">- <ConnectorsTab onConnect={onConnect} />- </TabsPrimitive.Content>+ {PAGES.map((page) => (+ <TabsPrimitive.Content key={page.tab} value={page.tab} className="outline-none">+ {page.render(context)}+ </TabsPrimitive.Content>+ ))}</div></TabsPrimitive.Root>- <Button- variant="quiet"- size="icon"- onClick={close}- aria-label="Close settings"- className={cn('absolute top-3.5 right-3.5 z-10')}- >+ <Button variant="quiet" size="icon" onClick={close} aria-label="Close settings" className="absolute top-3.5 right-3.5 z-10"><X /></Button></Modal>diff --git a/client/src/features/home/settings/PluginsTab.tsx b/client/src/features/home/settings/PluginsTab.tsxnew file mode 100644index 00000000..5f2a10c9--- /dev/null+++ b/client/src/features/home/settings/PluginsTab.tsx@@ -0,0 +1,104 @@+/**+ * Settings > Plugins (design handoff "Settings: Billing, Skills, Plugins"),+ * on the shared catalog page: starter bundles, each a job with the apps it+ * needs and the skills that help with it (hire/starters.json).+ *+ * Install adds the bundle's skills to the library (switching on any that+ * are off), then starts a new hire from the bundle's job and shows it on the+ * hire view. A bundle counts as installed when all its skills are in the+ * library, so nothing else is stored; removing a skill is done on Skills.+ */++import { useMemo, useState } from 'react';+import { useStartHire } from '../genui';+import { useDiscoverSkills, useSkillActions, useSkillLibrary } from '../data/skills';+import { STARTERS, type Starter } from '../hire/templates';+import { useHomeStore } from '../state/homeStore';+import { pillToast } from '../ui/pillToast';+import type { CatalogItem } from './catalog';+import { CatalogLayout } from './CatalogLayout';++function meta(starter: Starter): string {+ const skills = `${starter.skills.length} skill${starter.skills.length === 1 ? '' : 's'}`;+ return [skills, starter.apps.join(' + ')].filter(Boolean).join(' · ');+}++export function PluginsTab() {+ const library = useSkillLibrary();+ const discover = useDiscoverSkills();+ const actions = useSkillActions();+ const { busy, start } = useStartHire();+ const [installing, setInstalling] = useState<string | null>(null);++ const rows = useMemo(() => library.data ?? [], [library.data]);+ const items = useMemo<CatalogItem[]>(() => {+ const inLibrary = new Set(rows.map((row) => row.name));+ return STARTERS.map((starter) => ({+ id: starter.id,+ name: starter.label,+ description: starter.summary,+ byline: 'by OpenCompany',+ verified: true,+ meta: meta(starter),+ tile: { tone: starter.role },+ state:+ installing === starter.id ? 'busy' : starter.skills.every((name) => inLibrary.has(name)) ? 'added' : 'available',+ }));+ }, [rows, installing]);++ const install = async (item: CatalogItem) => {+ const starter = STARTERS.find((candidate) => candidate.id === item.id);+ if (!starter || installing) return;+ if (busy) {+ pillToast('Finish the setup you are working on first', { tone: 'info' });+ return;+ }+ setInstalling(starter.id);+ try {+ // The cards show before both lists arrive; an early click waits for them.+ const [libraryRows, builtIns] = await Promise.all([+ library.data ?? library.refetch().then((result) => result.data ?? []),+ discover.data ?? discover.refetch().then((result) => result.data ?? []),+ ]);+ for (const name of starter.skills) {+ const row = libraryRows.find((candidate) => candidate.name === name);+ if (row) {+ if (!row.is_active) await actions.setOn(name, true);+ continue;+ }+ const skill = builtIns.find((candidate) => candidate.skillName === name);+ if (!skill) throw new Error(`${starter.label} needs a skill that isn't available`);+ await actions.add(skill);+ }+ } catch (error) {+ pillToast(error instanceof Error ? error.message : `Couldn't install ${starter.label}`, { tone: 'error' });+ setInstalling(null);+ return;+ }+ setInstalling(null);+ pillToast(`${starter.label} installed`);+ // The draft appears on the hire view while the setup is written.+ void start(starter.job);+ const home = useHomeStore.getState();+ home.closeSettings();+ home.showHire();+ };++ return (+ <CatalogLayout+ title="Plugins"+ searchPlaceholder="Search plugins"+ loading={library.isPending || discover.isPending}+ yours={{+ items: items.filter((item) => item.state === 'added'),+ sectionTitle: 'Installed',+ empty: { title: 'No plugins installed', detail: 'Plugins bundle skills, apps and a routine for a line of work.' },+ }}+ discover={{ items, sectionTitle: 'Top plugins' }}+ verbs={{ add: 'Install', busy: 'Installing…' }}+ onAdd={(item) => void install(item)}+ />+ );+}++export default PluginsTab;diff --git a/client/src/features/home/settings/ProfileTab.tsx b/client/src/features/home/settings/ProfileTab.tsxindex 8f809803..dfe3654e 100644--- a/client/src/features/home/settings/ProfileTab.tsx+++ b/client/src/features/home/settings/ProfileTab.tsx@@ -25,6 +25,7 @@ import {useSaveProfile,type ProfileForm,} from '../data/profile';+import { SPIKE, spikeOrb } from '../orb/orb';import { Avatar } from '../ui/primitives';import { pillToast } from '../ui/pillToast';@@ -87,6 +88,7 @@ export function ProfileTab({ onDone }: { onDone: () => void }) {fill: 'none',});pillToast('Profile saved');+ spikeOrb(SPIKE.profileSaved);} catch (error) {pillToast(error instanceof Error ? error.message : "Couldn't save your profile", { tone: 'error' });}diff --git a/client/src/features/home/settings/SkillsTab.tsx b/client/src/features/home/settings/SkillsTab.tsxnew file mode 100644index 00000000..359c24b2--- /dev/null+++ b/client/src/features/home/settings/SkillsTab.tsx@@ -0,0 +1,180 @@+/**+ * Settings > Skills (design handoff "Settings: Billing, Skills, Plugins"),+ * on the shared catalog page. Yours is the owner's library: each skill is+ * on or off for employees hired from now on. Discover lists the built-in+ * skills written for AI employees. "Create" writes a new skill in plain+ * words. Changes never reach an employee already hired (data/skills.ts).+ */++import { useMemo, useState } from 'react';+import { ActionButton } from '@/components/ui/action-button';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Textarea } from '@/components/ui/textarea';+import { skillSummary, skillTitle, useDiscoverSkills, useSkillActions, useSkillLibrary } from '../data/skills';+import { pillToast } from '../ui/pillToast';+import type { CatalogItem } from './catalog';+import { CatalogLayout } from './CatalogLayout';++const FIELD = 'bg-bg-app text-row font-normal md:text-row dark:bg-bg-app';+const MAX_TITLE = 60;+const MAX_INSTRUCTIONS = 4000;++function errorText(error: unknown, fallback: string): string {+ return error instanceof Error && error.message ? error.message : fallback;+}++function CreateSkillForm({ close, onCreate }: { close: () => void; onCreate: (title: string, instructions: string) => Promise<void> }) {+ const [title, setTitle] = useState('');+ const [instructions, setInstructions] = useState('');+ const [saving, setSaving] = useState(false);+ const ready = title.trim() !== '' && instructions.trim() !== '' && !saving;++ const submit = async () => {+ if (!ready) return;+ setSaving(true);+ try {+ await onCreate(title.trim(), instructions.trim());+ close();+ } catch (error) {+ pillToast(errorText(error, "Couldn't create that skill"), { tone: 'error' });+ setSaving(false);+ }+ };++ return (+ <>+ <span className="text-base font-semibold text-fg-default">New skill</span>+ <Input+ value={title}+ onChange={(event) => setTitle(event.target.value)}+ onKeyDown={(event) => event.key === 'Enter' && void submit()}+ maxLength={MAX_TITLE}+ placeholder="Name it, e.g. Answer like our front desk"+ aria-label="Skill name"+ className={`h-9.5 rounded-lg ${FIELD}`}+ />+ <Textarea+ value={instructions}+ onChange={(event) => setInstructions(event.target.value)}+ maxLength={MAX_INSTRUCTIONS}+ rows={3}+ placeholder="Explain how it’s done, in plain words. Paste your own steps or examples."+ aria-label="How it’s done"+ className={`min-h-20 rounded-lg px-3 py-2.5 leading-normal ${FIELD}`}+ />+ <div className="flex justify-end gap-2">+ <Button variant="quiet" size="sm" onClick={close}>+ Cancel+ </Button>+ <ActionButton intent="run" disabled={!ready} onClick={() => void submit()} className="h-7.5 rounded-lg px-3.5 text-meta">+ {saving ? 'Adding…' : 'Add'}+ </ActionButton>+ </div>+ </>+ );+}++export function SkillsTab() {+ const library = useSkillLibrary();+ const discover = useDiscoverSkills();+ const actions = useSkillActions();+ const [adding, setAdding] = useState<ReadonlySet<string>>(new Set());++ const rows = useMemo(() => library.data ?? [], [library.data]);+ const builtIns = useMemo(() => discover.data ?? [], [discover.data]);+ const builtInByName = useMemo(() => new Map(builtIns.map((skill) => [skill.skillName, skill])), [builtIns]);++ const yours = useMemo<CatalogItem[]>(+ () =>+ rows.map((row) => {+ const builtIn = builtInByName.has(row.name);+ return {+ id: row.name,+ name: row.display_name || row.name,+ description: skillSummary(row),+ byline: builtIn ? 'by OpenCompany' : 'by you',+ verified: builtIn,+ meta: row.is_active ? 'New hires get this skill' : 'Off for new hires',+ tile: { iconRef: row.icon || null, tone: 'tool' },+ state: 'added',+ enabled: row.is_active,+ };+ }),+ [rows, builtInByName],+ );++ const discoverItems = useMemo<CatalogItem[]>(() => {+ const on = new Set(rows.filter((row) => row.is_active).map((row) => row.name));+ return builtIns.map((skill) => ({+ id: skill.skillName,+ name: skillTitle(skill),+ description: skillSummary(skill),+ byline: 'by OpenCompany',+ verified: true,+ tile: { iconRef: skill.icon || null, tone: 'tool' },+ state: adding.has(skill.skillName) ? 'busy' : on.has(skill.skillName) ? 'added' : 'available',+ }));+ }, [builtIns, rows, adding]);++ const add = async (item: CatalogItem) => {+ const skill = builtInByName.get(item.id);+ if (!skill) return;+ setAdding((names) => new Set(names).add(item.id));+ try {+ await actions.add(skill);+ } catch (error) {+ pillToast(errorText(error, `Couldn't add ${item.name}`), { tone: 'error' });+ } finally {+ setAdding((names) => {+ const next = new Set(names);+ next.delete(item.id);+ return next;+ });+ }+ };++ const remove = async (item: CatalogItem) => {+ try {+ await actions.remove(item.id);+ pillToast(`${item.name} removed`, { tone: 'info' });+ } catch (error) {+ pillToast(errorText(error, `Couldn't remove ${item.name}`), { tone: 'error' });+ }+ };++ const toggle = async (item: CatalogItem, on: boolean) => {+ try {+ await actions.setOn(item.id, on);+ } catch (error) {+ pillToast(errorText(error, `Couldn't change ${item.name}`), { tone: 'error' });+ }+ };++ const create = async (title: string, instructions: string) => {+ await actions.create(title, instructions);+ pillToast(`${title} created`);+ };++ return (+ <CatalogLayout+ title="Skills"+ searchPlaceholder="Search skills"+ loading={library.isPending || discover.isPending}+ yours={{+ items: yours,+ sectionTitle: 'Your skills',+ empty: { title: 'No skills yet', detail: 'Add a ready-made skill or write your own.' },+ }}+ discover={{ items: discoverItems, sectionTitle: 'Popular skills' }}+ verbs={{ add: 'Add', remove: 'Remove', busy: 'Adding…' }}+ onAdd={(item) => void add(item)}+ onRemove={(item) => void remove(item)}+ onToggle={(item, on) => void toggle(item, on)}+ onItemAdded={(item) => pillToast(`${item.name} added to your skills`)}+ primaryAction={{ label: 'Create', form: (close) => <CreateSkillForm close={close} onCreate={create} /> }}+ />+ );+}++export default SkillsTab;diff --git a/client/src/features/home/settings/catalog.ts b/client/src/features/home/settings/catalog.tsnew file mode 100644index 00000000..373874eb--- /dev/null+++ b/client/src/features/home/settings/catalog.ts@@ -0,0 +1,46 @@+/**+ * The shared catalog behind Settings > Skills, Connectors and Plugins+ * (design handoff "Settings: Billing, Skills, Plugins"): what one card+ * shows, and how a list is narrowed for display. Each page maps its own+ * records to `CatalogItem`s; nothing here knows which page it is on.+ */++import type { ColorRole } from '../data/schemas';++export type CatalogView = 'yours' | 'discover';++export interface CatalogItem {+ id: string;+ name: string;+ description?: string;+ /** "by Google", "by you". Searched along with the name and description. */+ byline?: string;+ verified?: boolean;+ /** A category key, for the filter chips. */+ category?: string;+ /** One short mono line under the byline. */+ meta?: string;+ /** A brand icon, or tinted initials when there is none. */+ tile: { iconRef?: string | null; tone?: ColorRole };+ state: 'available' | 'busy' | 'added';+ /** The switch in Yours, shown only when the page can toggle items. */+ enabled?: boolean;+}++/** Discover shows this many cards until "Show all". */+export const DISCOVER_LIMIT = 8;++/** Items in `category` ('all' for every one) matching `query`, the first+ * `cap` of them when a cap is given. `total` counts every match. */+export function catalogSlice(+ items: CatalogItem[],+ { category, query, cap }: { category: string; query: string; cap: number | null },+): { shown: CatalogItem[]; total: number } {+ const q = query.trim().toLowerCase();+ const matched = items.filter((item) => {+ if (category !== 'all' && item.category !== category) return false;+ if (!q) return true;+ return [item.name, item.description, item.byline].some((text) => text?.toLowerCase().includes(q));+ });+ return { shown: cap === null ? matched : matched.slice(0, cap), total: matched.length };+}diff --git a/client/src/features/home/settings/stagger.ts b/client/src/features/home/settings/stagger.tsnew file mode 100644index 00000000..96044e70--- /dev/null+++ b/client/src/features/home/settings/stagger.ts@@ -0,0 +1,20 @@+/**+ * Settings blocks rise in, 30ms apart (design handoff "Settings modal"):+ * every `[data-stagger]` under `root`. HomeSettings plays it when the dialog+ * opens or the tab changes; a catalog page plays it again when its view or+ * category changes.+ */++import { stagger } from '@/lib/motion';++export function staggerSettings(root: ParentNode | null | undefined): void {+ if (!root) return;+ stagger(+ root.querySelectorAll('[data-stagger]'),+ [+ { opacity: 0, transform: 'translateY(10px)' },+ { opacity: 1, transform: 'none' },+ ],+ { base: 40, step: 30, cap: 14, duration: 420, easing: 'spring' },+ );+}diff --git a/client/src/features/home/sidebar/HomeSidebar.tsx b/client/src/features/home/sidebar/HomeSidebar.tsxindex 10fb1ffb..9992e964 100644--- a/client/src/features/home/sidebar/HomeSidebar.tsx+++ b/client/src/features/home/sidebar/HomeSidebar.tsx@@ -36,12 +36,12 @@ function EmployeeRow({ employee, selected }: { employee: EmployeeSummary; select{opacity: 0,transform: 'translateY(-24px) scale(.9)',- boxShadow: '0 0 0 2px var(--action-run-border), 0 0 40px var(--status-working-border)',+ boxShadow: 'var(--glow-hire)',},{opacity: 1,transform: 'none',- boxShadow: '0 0 0 2px var(--status-working-border), 0 0 24px var(--status-working-fill)',+ boxShadow: 'var(--glow-hire-settle)',offset: 0.6,},{ opacity: 1, transform: 'none', boxShadow: '0 0 0 0 transparent' },diff --git a/client/src/features/home/state/homeStore.ts b/client/src/features/home/state/homeStore.tsindex f7c6adfb..38371e54 100644--- a/client/src/features/home/state/homeStore.ts+++ b/client/src/features/home/state/homeStore.ts@@ -6,9 +6,10 @@*/import { create } from 'zustand';+import { SPIKE, spikeOrb } from '../orb/orb';export type HomeView = { kind: 'hire' } | { kind: 'employee'; workflowId: string };-export type SettingsTab = 'profile' | 'connectors';+export type SettingsTab = 'profile' | 'billing' | 'skills' | 'connectors' | 'plugins';const SIDEBAR_KEY = 'home_sidebar_open';@@ -25,7 +26,8 @@ interface HomeState {sidebarOpen: boolean;settingsOpen: boolean;settingsTab: SettingsTab;- /** Connectors category to open on ('all' when unset). */+ /** The category a catalog page opens on ('all' when unset). Only the way+ * in: switching tabs clears it, and the page owns its filter after. */settingsCategory: string;/** The sidebar row to glow, and a nonce so repeating it replays. */glow: { workflowId: string; nonce: number } | null;@@ -40,7 +42,6 @@ interface HomeState {openSettings: (tab?: SettingsTab, category?: string) => void;closeSettings: () => void;setSettingsTab: (tab: SettingsTab) => void;- setSettingsCategory: (category: string) => void;glowRow: (workflowId: string) => void;pulseLogo: () => void;/** The composer took the focus it was asked for; a remount must not@@ -48,7 +49,7 @@ interface HomeState {consumeComposerFocus: () => void;}-export const useHomeStore = create<HomeState>((set) => ({+export const useHomeStore = create<HomeState>((set, get) => ({view: { kind: 'hire' },sidebarOpen: loadSidebarOpen(),settingsOpen: false,@@ -74,11 +75,12 @@ export const useHomeStore = create<HomeState>((set) => ({}return { sidebarOpen: next };}),- openSettings: (tab = 'profile', category = 'all') =>- set({ settingsOpen: true, settingsTab: tab, settingsCategory: category }),+ openSettings: (tab = 'profile', category = 'all') => {+ if (!get().settingsOpen) spikeOrb(SPIKE.settings);+ set({ settingsOpen: true, settingsTab: tab, settingsCategory: category });+ },closeSettings: () => set({ settingsOpen: false }),- setSettingsTab: (tab) => set({ settingsTab: tab }),- setSettingsCategory: (category) => set({ settingsCategory: category }),+ setSettingsTab: (tab) => set({ settingsTab: tab, settingsCategory: 'all' }),glowRow: (workflowId) =>set((state) => ({ glow: { workflowId, nonce: (state.glow?.nonce ?? 0) + 1 } })),pulseLogo: () => set((state) => ({ logoPulse: state.logoPulse + 1 })),diff --git a/client/src/features/home/ui/primitives.tsx b/client/src/features/home/ui/primitives.tsxindex 0294e1a5..198c8d03 100644--- a/client/src/features/home/ui/primitives.tsx+++ b/client/src/features/home/ui/primitives.tsx@@ -5,7 +5,9 @@*/import type { ReactNode } from 'react';+import { Search } from 'lucide-react';import { NodeIcon } from '@/assets/icons';+import { Input } from '@/components/ui/input';import { cn } from '@/lib/utils';import { theme } from '@/styles/theme';import {@@ -95,19 +97,23 @@ const MARK_SIZE = {xs: { box: 'size-5', icon: theme.iconSize.xs },sm: { box: 'size-5.5', icon: theme.iconSize.xs },lg: { box: 'size-9.5 rounded-row', icon: theme.iconSize.md },+ xl: { box: 'size-12.5 rounded-card text-sm', icon: theme.iconSize.lg },} as const;/** An app's brand mark (the credential catalogue's icon), in a disc. Falls- * back to the app's first two letters. */+ * back to the app's first two letters, tinted in `tone` when given (a+ * skill or starter tile). */export function AppMark({name,iconRef,size = 'sm',+ tone,className,}: {name: string;iconRef?: string | null;size?: keyof typeof MARK_SIZE;+ tone?: ColorRole;className?: string;}) {const spec = MARK_SIZE[size];@@ -116,7 +122,8 @@ export function AppMark({<spanaria-hiddenclassName={cn(- 'grid shrink-0 place-items-center rounded-full border border-border-default bg-bg-panel font-mono text-2xs font-semibold text-fg-muted',+ 'grid shrink-0 place-items-center rounded-full border font-mono text-2xs font-semibold',+ tone ? AVATAR_CLASS[tone] : 'border-border-default bg-bg-panel text-fg-muted',spec.box,className,)}@@ -125,3 +132,32 @@ export function AppMark({</span>);}++/** A search box on a Home surface (Settings nav, the catalog pages). The+ * placeholder doubles as its accessible name unless `label` says otherwise. */+export function SearchField({+ value,+ onChange,+ placeholder,+ label,+ className,+}: {+ value: string;+ onChange: (value: string) => void;+ placeholder: string;+ label?: string;+ className?: string;+}) {+ return (+ <div className={cn('relative min-w-0', className)}>+ <Search aria-hidden className="pointer-events-none absolute top-1/2 left-3 size-3.75 -translate-y-1/2 text-fg-faint" />+ <Input+ value={value}+ onChange={(event) => onChange(event.target.value)}+ placeholder={placeholder}+ aria-label={label ?? placeholder}+ className="h-9 rounded-row bg-bg-app pl-8.5 text-row font-normal md:text-row dark:bg-bg-app"+ />+ </div>+ );+}diff --git a/client/src/hooks/useCatalogueQuery.ts b/client/src/hooks/useCatalogueQuery.tsindex 0760990e..5547400c 100644--- a/client/src/hooks/useCatalogueQuery.ts+++ b/client/src/hooks/useCatalogueQuery.ts@@ -140,6 +140,10 @@ export interface ServerProviderConfig {consumer_category?: string | null;/** One short line for the Normal-mode Connectors card. */description?: string;+ /** Who makes the app, for the card's "by …" line. */+ publisher?: string;+ /** The card shows a verified mark (every built-in connector). */+ verified?: boolean;/** The provider runs on this computer (Ollama, LM Studio). */runs_locally?: boolean;}diff --git a/client/src/hooks/useFolderSkills.ts b/client/src/hooks/useFolderSkills.tsindex 2777b458..91dd6079 100644--- a/client/src/hooks/useFolderSkills.ts+++ b/client/src/hooks/useFolderSkills.ts@@ -2,18 +2,18 @@* Per-folder skill metadata query.** Wraps the `scan_skill_folder` WebSocket request in TanStack Query so:- * - sibling surfaces (MasterSkillEditor, MiddleSection) reading the- * same folder share one network call+ * - sibling surfaces (MasterSkillEditor, MiddleSection, Home's Settings >+ * Skills) reading the same folder share one network call* - SKILL.md frontmatter (icon / color / description) is the single* source of truth -- the frontend no longer maintains a per-skill* icon override table*- * Cache key matches the in-place query MasterSkillEditor used to- * declare inline, so existing cache hits carry over.+ * Every reader of a folder's key goes through `fetchFolderSkills`, so the+ * cache holds one shape whichever surface loads it first.*/import { useQuery, type UseQueryResult } from '@tanstack/react-query';-import { useWebSocket } from '../contexts/WebSocketContext';+import { useWebSocket, type WebSocketActions } from '../contexts/WebSocketContext';import { STALE_TIME } from '../lib/queryConfig';import { dracula } from '../styles/theme';@@ -24,6 +24,8 @@ export interface AvailableSkill {icon: string;color: string;description: string;+ /** The SKILL.md `metadata` block as served (author, title, summary, …). */+ metadata?: Record<string, unknown>;}export const folderSkillsQueryKey = (folder: string) =>@@ -45,29 +47,40 @@ const titleCase = (slug: string): string =>.map((w) => (w.length ? w[0].toUpperCase() + w.slice(1) : w)).join(' ');-export function useFolderSkills(+export async function fetchFolderSkills(+ sendRequest: WebSocketActions['sendRequest'],+ folder: string,+): Promise<AvailableSkill[]> {+ if (!folder) return [];+ const response = await sendRequest<ScanSkillFolderResponse>('scan_skill_folder', { folder });+ if (!response?.success || !response.skills) return [];+ return response.skills.map((s) => ({+ type: s.name,+ skillName: s.name,+ displayName: titleCase(s.name),+ icon: s.metadata?.icon ?? '',+ color: s.metadata?.color ?? dracula.purple,+ description: s.description ?? '',+ metadata: s.metadata ?? {},+ }));+}++export function useFolderSkillsCore(folder: string | undefined | null,+ sendRequest: WebSocketActions['sendRequest'],+ isReady: boolean,): UseQueryResult<AvailableSkill[], Error> {- const { sendRequest, isReady } = useWebSocket();return useQuery<AvailableSkill[], Error>({queryKey: folderSkillsQueryKey(folder ?? ''),- queryFn: async () => {- if (!folder) return [];- const response = await sendRequest<ScanSkillFolderResponse>(- 'scan_skill_folder',- { folder },- );- if (!response?.success || !response.skills) return [];- return response.skills.map((s) => ({- type: s.name,- skillName: s.name,- displayName: titleCase(s.name),- icon: s.metadata?.icon ?? '',- color: s.metadata?.color ?? dracula.purple,- description: s.description ?? '',- }));- },+ queryFn: () => fetchFolderSkills(sendRequest, folder ?? ''),enabled: !!folder && isReady,staleTime: STALE_TIME.MEDIUM,});}++export function useFolderSkills(+ folder: string | undefined | null,+): UseQueryResult<AvailableSkill[], Error> {+ const { sendRequest, isReady } = useWebSocket();+ return useFolderSkillsCore(folder, sendRequest, isReady);+}diff --git a/client/src/hooks/useUserSkills.ts b/client/src/hooks/useUserSkills.tsnew file mode 100644index 00000000..fbb83281--- /dev/null+++ b/client/src/hooks/useUserSkills.ts@@ -0,0 +1,46 @@+/**+ * The owner's skill library (`get_user_skills`, every row, on or off). The+ * Dev editor's Master Skill panel and Home's Settings > Skills read this one+ * cache; `skill_lifecycle` broadcasts invalidate it (WebSocketContext).+ * `is_active` means "on for new hires" (docs-internal/normal_mode.md).+ */++import { useQuery, type UseQueryResult } from '@tanstack/react-query';+import { useWebSocket, type WebSocketActions } from '../contexts/WebSocketContext';++export interface UserSkill {+ name: string;+ display_name: string;+ description: string;+ instructions: string;+ icon: string;+ color: string;+ category: string;+ is_active: boolean;+ metadata?: Record<string, unknown> | null;+}++export const USER_SKILLS_QUERY_KEY = ['userSkills'] as const;++export async function fetchUserSkills(sendRequest: WebSocketActions['sendRequest']): Promise<UserSkill[]> {+ const response = await sendRequest<{ skills?: UserSkill[] }>('get_user_skills', { active_only: false });+ return response?.skills ?? [];+}++export function useUserSkillsQueryCore(+ sendRequest: WebSocketActions['sendRequest'],+ isReady: boolean,+): UseQueryResult<UserSkill[], Error> {+ return useQuery<UserSkill[], Error>({+ queryKey: USER_SKILLS_QUERY_KEY,+ queryFn: () => fetchUserSkills(sendRequest),+ enabled: isReady,+ staleTime: 60_000,+ });+}++/** For the editor, which already reads the full socket context. */+export function useUserSkillsQuery(): UseQueryResult<UserSkill[], Error> {+ const { sendRequest, isReady } = useWebSocket();+ return useUserSkillsQueryCore(sendRequest, isReady);+}diff --git a/client/src/index.css b/client/src/index.cssindex 5636ee79..86ce014c 100644--- a/client/src/index.css+++ b/client/src/index.css@@ -452,7 +452,7 @@ html {@keyframes home-pip-ring {0% {- box-shadow: 0 0 0 0 color-mix(in srgb, var(--status-working-dot) var(--tint-pip-ring), transparent);+ box-shadow: 0 0 0 0 color-mix(in srgb, var(--status-working-ink) var(--tint-pip-ring), transparent);}100% {box-shadow: 0 0 0 6px transparent;diff --git a/client/src/themes/base.css b/client/src/themes/base.cssindex f3b66300..78f7b768 100644--- a/client/src/themes/base.css+++ b/client/src/themes/base.css@@ -177,12 +177,9 @@--w-employee-card: 620px;--size-orb-hire: min(230px, 26vh);--size-orb-employee: min(150px, 20vh);- --w-settings: 920px;- --h-settings: 680px;- --w-settings-nav: 200px;-- /* Working-status pip ring (the pulsing halo around a working employee). */- --tint-pip-ring: 55%;+ --w-settings: 1040px;+ --h-settings: 760px;+ --w-settings-nav: 224px;/* ── Employee status (Normal mode). The dot is the raw role colour; the* pill tints it (fill 12%, border 45%) and reads in the role's ink, whichdiff --git a/client/src/themes/dark.css b/client/src/themes/dark.cssindex 3790d8c0..d25045c2 100644--- a/client/src/themes/dark.css+++ b/client/src/themes/dark.css@@ -134,6 +134,16 @@--shadow-popover: 0 12px 32px rgb(0 0 0 / 0.5);--shadow-dialog: 0 24px 80px rgb(0 0 0 / 0.6);+ /* Home glows and the working pip's ring, in the neon (light.css has the+ * ink versions for white surfaces). */+ --glow-connect: 0 0 0 1px var(--action-run-border), 0 0 28px var(--status-working-border);+ --glow-hire: 0 0 0 2px var(--action-run-border), 0 0 40px var(--status-working-border);+ --glow-hire-settle: 0 0 0 2px var(--status-working-border), 0 0 24px var(--status-working-fill);+ --glow-refine: 0 0 0 0 var(--node-agent-edge);+ --glow-refine-out: 0 0 0 6px transparent;+ --glow-task: var(--status-working-border);+ --tint-pip-ring: 55%;+color-scheme: dark;}diff --git a/client/src/themes/light.css b/client/src/themes/light.cssindex 2f67c522..0011c35f 100644--- a/client/src/themes/light.css+++ b/client/src/themes/light.css@@ -224,6 +224,21 @@--shadow-popover: 0 12px 32px rgb(15 23 42 / 0.12);--shadow-dialog: 0 24px 80px rgb(15 23 42 / 0.16);+ /* ── Home glows (a connect, a new hire's row, the refine ring, a new+ * task) and the working pip's ring. On white the design swaps each neon+ * for its ink, at .75 of the alpha and .6 of the blur; dark.css restates+ * the neon versions. ───────────────────────────────────────────────── */+ --glow-connect: 0 0 0 1px color-mix(in srgb, var(--status-working-ink) 67.5%, transparent),+ 0 0 17px color-mix(in srgb, var(--status-working-ink) 26%, transparent);+ --glow-hire: 0 0 0 1px color-mix(in srgb, var(--status-working-ink) 67.5%, transparent),+ 0 0 24px color-mix(in srgb, var(--status-working-ink) 30%, transparent);+ --glow-hire-settle: 0 0 0 1px color-mix(in srgb, var(--status-working-ink) 45%, transparent),+ 0 0 14px color-mix(in srgb, var(--status-working-ink) 19%, transparent);+ --glow-refine: 0 0 0 0 color-mix(in srgb, var(--node-agent-ink) 37.5%, transparent);+ --glow-refine-out: 0 0 0 4px transparent;+ --glow-task: color-mix(in srgb, var(--status-working-ink) 41%, transparent);+ --tint-pip-ring: 45%;+/* A paused employee's dot stays the design's mid grey; only its pill* text takes the darker muted ink (base.css). */--status-paused-dot: #9aa1ac;diff --git a/docs-internal/normal_mode.md b/docs-internal/normal_mode.mdindex 6d4b060b..c5b80c36 100644--- a/docs-internal/normal_mode.md+++ b/docs-internal/normal_mode.md@@ -62,7 +62,7 @@ out of git). Where its token values differ from the repo's, the repo wins.| `hire/` | The hero, the composer, starter jobs || `genui/` | The setup draft under the composer (below) || `employee/` | One employee's card: status, the current task, apps, "done today", Start / Pause / Resume, the drafts waiting for the owner |-| `settings/` | Profile and Connectors, and `ConnectDialog` (the editor's credential panel for one provider, in its compact variant) |+| `settings/` | The Settings pages (Profile, Billing, Skills, Connectors, Plugins), the shared catalog page the last three build on, and `ConnectDialog` (the editor's credential panel for one provider, in its compact variant) || `approvals/` | The drafts query, the decide mutation (optimistic), the approval broadcast listener || `data/` | zod-parsed queries for employees, connectors and the profile; `presentation.ts` maps server state to pills and actions without deriving new rules || `orb/` | The 3D orb (below) |@@ -87,9 +87,14 @@ what the engine reads each frame (the slot to fill, an energy target, a spike)and its lifecycle: leaving Home keeps the renderer, the app shell disposes it.`OrbStage` is the canvas host below the header; each view's `OrbSlot` reservesthe square the orb glides into. The composer sets the energy target (focused,-holding text, a setup being written); a hire, a theme or mode switch, a connect-and a task change spike it. Without WebGL, under reduced motion, or after a-lost WebGL context, the slot shows the static mark.+holding text, a setup being written). These spike it: a hire, a theme or mode+switch, a connect, a task change, opening Settings, a setup arriving or+failing, and saving the profile (`SPIKE` in orb.ts). In dark the orb keeps the+logo's colours with white particles and packets; in light it is glossy+piano-black under a white rim light. Its glows and particles blend additively+in dark and normally in light (additive glow vanishes on white), fading through+zero at the midpoint of a theme change. Without WebGL, under reduced motion, or+after a lost WebGL context, the slot shows the static mark.## Hiring@@ -151,8 +156,15 @@ the client's `HIRE_PAYLOAD_KEYS` must match, locked bypure): one trigger (an app event, a schedule on `cronScheduler`, or manualchat), one `aiAgent` whose system message comes from[prompt.py](../server/services/employees/prompt.py), always-on tools (web- search, todos, clock, plus memory when the owner allows it) and the apps'- tools, delivery, and an "Activity log" console node. With "Ask me before+ search, todos, clock, a Canvas, plus memory when the owner allows it) and+ the apps' tools, the owner's skill library, delivery, and an "Activity+ log" console node. The instructions ask the employee to put finished+ work the owner will want to look at later on its Canvas, and to leave+ routine replies off it. The library is every skill that is on in Settings > Skills. It goes+ on one Skills node (`masterSkill`) with each skill's text copied in, so a+ later change to the library never alters an employee already hired. A+ skill named `skill`, or one ending in `-personality`, is left out: it would+ take over the Skill tool, or replace the whole system message. With "Ask me beforesending anything" on, a reply goes through `approvalGate`, and tools thatsend or spend money are left off. Every node type must pass`node_allowlist.is_hire_allowed` ([Node Allowlist](./node_allowlist.md));@@ -195,20 +207,73 @@ Every trigger-spawned run that finishes writes a `workflow_run_records` row`workflow_runs.record_completion` activity, scheduled at the end of`MachinaWorkflow.run` behind the `machina-run-record-v1` patch; in-processfrom `DeploymentManager`. The count starts at local midnight in the owner's-timezone, and rows are pruned after 35 days.+timezone, and rows are pruned after 35 days, which is longer than a month, so+Billing's count of this month's tasks (from the 1st, in the owner's timezone,+across the whole team) is always complete.## Settings+A 1040x760 dialog ([settings/HomeSettings.tsx](../client/src/features/home/settings/HomeSettings.tsx))+with a 224px nav. One `PAGES` list drives the nav and the panels. The pages+are grouped under *Settings* (Profile, Billing) and *Customize* (Skills,+Connectors, Plugins), and the nav's search matches each page's label and+keywords, dropping a group with no match. Opening Settings on a category+(`openSettings('connectors', 'ai')`) only sets where the page starts:+changing page clears it.+- **Profile**: `profile_full_name`, `profile_call_name`, `profile_role`,`profile_preferences`, `profile_timezone` (written from `Intl` on save),`memory_across_chats` and `prefer_local_ai` on `UserSettings`, normalised onsave by [services/settings/profile.py](../server/services/settings/profile.py).Every hire reads them into its instructions.+- **Billing**: usage only. It shows the tasks done this month+ (`get_employee_usage`) and the number of employees in the sidebar. A count+ that can't be read shows a dash, never a zero.+- **Skills**: the owner's library, which is the user-skills table. Each row is+ on (`is_active`) or off for employees hired from now on.+ - *Discover* lists the built-in `server/skills/employee/` folder. These are+ short skills written for AI employees, with no tools to connect, and their+ cards read the SKILL.md `metadata.title` and `metadata.summary`.+ - *Adding* a built-in copies its text into the library under the same name.+ - *Create* writes a new skill in plain words. Its name is the title's slug,+ never a taken, built-in or reserved one.++ The Dev editor's Master Skill panel reads the same library. It no longer+ switches a skill back on when saving it, and it keeps the extra keys a hired+ employee's Skills node carries. `DISCOVER_SKILL_FOLDER` in+ `features/home/data/skills.ts` names the folder.+- **Plugins**: starter bundles, from `features/home/hire/starters.json`, the+ same list the composer's template chips send. A bundle is a job, the apps it+ needs (named in the job, since the job is all the setup model reads), and+ its skills.+ - *Install* adds the bundle's skills to the library, switching on any that+ are off. It then starts a hire from the job on the hire view.+ - A bundle counts as installed when all its skills are in the library;+ nothing else is stored.++ `tests/test_home_catalog_contract.py` holds the bundles and the Discover+ folder to each other and to the app registry.- **Connectors**: the providers in `config/credential_providers.json` that- declare a `consumer_category` (`messages`, `organize`, `business`, `ai`) and a- short `description`. The catalogue adds `connected`, which differs from- `stored` for providers with a `connected_check` (WhatsApp's live pairing, the- IMAP/SMTP account's keys).+ declare a `consumer_category` (`messages`, `organize`, `business`, `ai`), a+ short `description`, a `publisher` (the card's "by …" line) and `verified`.+ They are listed in category order, so apps come before AI models. The+ catalogue adds `connected`, which differs from `stored` for providers with a+ `connected_check` (WhatsApp's live pairing, the IMAP/SMTP account's keys).++**The catalog page** ([settings/CatalogLayout.tsx](../client/src/features/home/settings/CatalogLayout.tsx)).+Skills, Connectors and Plugins are built on a shared page:+- a title with Yours / Discover, search, and a category filter behind a+ button;+- an optional primary action that opens an inline form;+- a grid of cards.++The page supplies both lists, so the layout never needs to know which page it+is on:+- Discover shows eight cards until Show all.+- A card's "+" turns into a check, which removes on hover only when the page+ can remove.+- Yours shows a switch only when the page can toggle.+- A card glows when its item turns added while it is on screen.## Wire contract@@ -217,8 +282,9 @@ WebSocket requests (snake_case; failures come back as `success: false` with an| Type | Payload | Response ||---|---|---|-| `list_employees` | `{}` | `{employees}` |+| `list_employees` | `{}` | `{employees}`; each summary's `canvas_node_id` is its Canvas board: the one it was hired with, else the graph's first Canvas node, else null || `get_employee` | `{workflow_id}` | the summary plus `description`, `job`, `plan`, `rules`, `choices`, `trigger_text`, `last_run`, `latest_report` |+| `get_employee_usage` | `{}` | `{tasks_this_month}` (successful runs since the 1st, owner's timezone, whole team) || `generate_employee_setup` | `{job, refine?, history?, draft_token}` | `{draft_token, reply, provider, model, usage, retried, finish_reason, apps}` || `cancel_employee_setup` | `{draft_token}` | `{cancelled}` || `hire_employee` | `HireEmployeeRequest` | `{employee, started, missing_apps, needs_ai, unsupported_apps, warnings, idempotent}` |@@ -255,5 +321,14 @@ history). Client: `features/home/**/__tests__`, `app/__tests__`,- OAuth sign-in is not opened ahead of the request, so a browser may blockthe popup.- Each waiting draft holds one `triggers-event` worker slot.+- Billing has no plans, payment method or invoices: no billing account sits+ behind OpenCompany. A deleted employee's runs leave the month's count,+ because deleting a workflow deletes its run records.+- Connectors has no custom (MCP) connector.+- Skill library changes reach only new hires: an employee keeps the skills it+ was hired with, and one hired before the library existed has none. The+ library is shared across users in multi-user mode, like the team list.+- An employee hired before Canvas has no Canvas node, so its+ `canvas_node_id` is null. Adding one in Dev mode fills it in.- A manual-chat employee cannot be given work from Home yet; the setup promptsteers towards app and schedule triggers.diff --git a/docs-internal/theme_system.md b/docs-internal/theme_system.mdindex dacdc44e..6dbcdd36 100644--- a/docs-internal/theme_system.md+++ b/docs-internal/theme_system.md@@ -130,12 +130,13 @@ Consumed as `var(--code-*)` in [index.css](../client/src/index.css) (`.code-editNormal mode ([normal_mode.md](./normal_mode.md)) adds its own steps, all in[base.css](../client/src/themes/base.css) unless noted, and bridged in-`index.css` like the rest:+`index.css` where a Tailwind utility needs them (the layout and duration+tokens are used directly, as `w-(--w-home-sidebar)` or `duration-(--dur-slow)`):- **Motion**: `--ease-spring | overshoot | reveal` and the choreographydurations (`--dur-intro`, `--dur-view-swap`, `--dur-panel-in/-out`,`--dur-toast-in/-hold/-out`, `--dur-mode-in/-out`, `--dur-theme-reveal`,- `--dur-glow`, `--dur-pip-loop`, …). Read only through+ `--dur-glow`, `--dur-pip-loop`, …). Web Animations read them through[lib/motion.ts](../client/src/lib/motion.ts), whose fallbacks mirrorbase.css.- **Radii**: `--radius-row | card | panel | draft | composer`, multiples of each@@ -148,8 +149,14 @@ Normal mode ([normal_mode.md](./normal_mode.md)) adds its own steps, all infor the employee pills and dots. The dot is the raw role colour; light.csskeeps the paused dot at the design's mid grey.- **Per family** (light.css / dark.css): `--shadow-float | popover | dialog`,- the logo palette `--lg-*`, and the node-role `-fill / -edge / -hover / -ink`- variants.+ the logo palette `--lg-*`, the node-role `-fill / -edge / -hover / -ink`+ variants, and Home's glows: `--glow-connect | hire | hire-settle | refine |+ refine-out | task` plus the working pip's `--tint-pip-ring`. Dark keeps the+ neon; light swaps each neon for its ink at .75 of the alpha and .6 of the+ blur, the design's rule for white surfaces. The Web Animations that play+ them name the token (`boxShadow: 'var(--glow-hire)'`), so the colour follows+ the theme with no script. dark.css restates each one, because light.css's+ bare `:root` also matches the dark family.Home shows only the two base themes: `ThemeProvider`'s `baseOnly` (set by`app/ShellThemeProvider.tsx` while Home is showing) renders a chosen stylizeddiff --git a/server/config/credential_providers.json b/server/config/credential_providers.jsonindex 275faa03..243df153 100644--- a/server/config/credential_providers.json+++ b/server/config/credential_providers.json@@ -73,6 +73,7 @@"category_label": "AI Providers","kind": "apiKey","consumer_category": "ai",+ "verified": true,"has_defaults": true,"fields": [{@@ -87,6 +88,7 @@"openai": {"extends": "_ai_base","name": "OpenAI",+ "publisher": "OpenAI","description": "GPT models from OpenAI.","color": "dracula.green","icon_ref": "lobehub:openai",@@ -100,6 +102,7 @@"anthropic": {"extends": "_ai_base","name": "Anthropic",+ "publisher": "Anthropic","description": "Claude models from Anthropic.","color": "dracula.orange","icon_ref": "lobehub:claude",@@ -113,6 +116,7 @@"gemini": {"extends": "_ai_base","name": "Gemini",+ "publisher": "Google","description": "Gemini models from Google.","vertex_display_name": "Gemini Vertex","color": "solarized.blue",@@ -128,6 +132,7 @@"groq": {"extends": "_ai_base","name": "Groq",+ "publisher": "Groq","description": "Fast open models served by Groq.","color": "dracula.red","icon_ref": "lobehub:groq",@@ -141,6 +146,7 @@"cerebras": {"extends": "_ai_base","name": "Cerebras",+ "publisher": "Cerebras","description": "Very fast open models served by Cerebras.","color": "dracula.orange","icon_ref": "lobehub:cerebras",@@ -154,6 +160,7 @@"openrouter": {"extends": "_ai_base","name": "OpenRouter",+ "publisher": "OpenRouter","description": "Hundreds of models through one OpenRouter key.","color": "solarized.violet","icon_ref": "lobehub:openrouter",@@ -167,6 +174,7 @@"deepseek": {"extends": "_ai_base","name": "DeepSeek",+ "publisher": "DeepSeek","description": "DeepSeek's chat and reasoning models.","color": "dracula.cyan","icon_ref": "lobehub:deepseek",@@ -180,6 +188,7 @@"kimi": {"extends": "_ai_base","name": "Kimi",+ "publisher": "Moonshot AI","description": "Kimi models from Moonshot AI.","color": "dracula.purple","icon_ref": "lobehub:kimi",@@ -194,6 +203,7 @@"extends": "_ai_base","icon_ref": "lobehub:mistral","name": "Mistral",+ "publisher": "Mistral AI","description": "Mistral's models, made in Europe.","color": "dracula.pink","fields": [@@ -208,6 +218,7 @@"extends": "_ai_base","icon_ref": "/api/schemas/credentials/sarvam/icon","name": "Sarvam AI",+ "publisher": "Sarvam AI","description": "Models tuned for Indian languages, from Sarvam AI.","color": "#6A88E2","fields": [@@ -221,6 +232,8 @@"ollama": {"_description": "Local Ollama server. The single field stores a base URL; the backend's _LocalLLM credential class returns a placeholder api_key, and execute_chat reads `{provider}_proxy` to override base_url via the existing OpenAI-style auth-delegation path. No `extends` — the field shape diverges from the cloud `_ai_base` template.","name": "Ollama",+ "publisher": "Ollama",+ "verified": true,"consumer_category": "ai","description": "Run AI models on this computer with Ollama.","runs_locally": true,@@ -245,6 +258,8 @@"lmstudio": {"_description": "Local LM Studio server (OpenAI-compatible /v1). Same shape as ollama: single base-URL field stored as `lmstudio_proxy`.","name": "LM Studio",+ "publisher": "LM Studio",+ "verified": true,"consumer_category": "ai","description": "Run AI models on this computer with LM Studio.","runs_locally": true,@@ -336,6 +351,8 @@},"whatsapp": {"name": "WhatsApp Personal",+ "publisher": "Meta",+ "verified": true,"consumer_category": "messages","description": "Answer customers and send updates from your WhatsApp.","category": "social",@@ -407,6 +424,8 @@},"whatsapp_business": {"name": "WhatsApp Business",+ "publisher": "Meta",+ "verified": true,"consumer_category": "messages","description": "Message customers from your official WhatsApp Business number.","category": "social",@@ -466,6 +485,8 @@},"discord": {"name": "Discord Bot",+ "publisher": "Discord",+ "verified": true,"consumer_category": "messages","description": "Answer your community through a Discord bot.","category": "social",@@ -555,6 +576,8 @@},"telegram": {"name": "Telegram Bot",+ "publisher": "Telegram",+ "verified": true,"consumer_category": "messages","description": "Reply to people through your Telegram bot.","category": "social",@@ -596,6 +619,8 @@},"google": {"name": "Google Workspace",+ "publisher": "Google",+ "verified": true,"consumer_category": "organize","description": "Gmail, Calendar, Drive and Sheets with one Google sign-in.","category": "productivity",@@ -632,6 +657,8 @@},"microsoft": {"name": "Microsoft Graph",+ "publisher": "Microsoft",+ "verified": true,"consumer_category": "organize","description": "Outlook email and calendar with your Microsoft account.","category": "productivity",@@ -668,6 +695,8 @@},"email_himalaya": {"name": "Email (IMAP/SMTP)",+ "publisher": "OpenCompany",+ "verified": true,"consumer_category": "messages","description": "Read and send email from any account (IMAP and SMTP).","category": "email",@@ -874,6 +903,8 @@},"stripe": {"name": "Stripe",+ "publisher": "Stripe",+ "verified": true,"consumer_category": "business","description": "Look up payments, refunds and invoices.","category": "payments",diff --git a/server/services/employees/builder.py b/server/services/employees/builder.pyindex 174e0bfc..64ffc3ac 100644--- a/server/services/employees/builder.py+++ b/server/services/employees/builder.py@@ -8,9 +8,13 @@ One employee is one workflow:- one agent (aiAgent) labelled with the employee's name, carrying thestanding instructions (prompt.py) and a per-run prompt that points at thetrigger's output;-- tools on the agent: web search, a checklist (writeTodos) and a clock,- always; the apps' tools, minus anything that sends or spends while "ask- me first" is on; Memory when the owner keeps memory across chats;+- tools on the agent: web search, a checklist (writeTodos), a clock and a+ canvas (what the agent puts there shows in Home's Workspace), always; the+ apps' tools, minus anything that sends or spends while "ask me first" is+ on; Memory when the owner keeps memory across chats;+- the owner's skill library (Settings > Skills): every skill that is on, on+ one Skills node (masterSkill), with its text copied in, so a later edit to+ the library never changes an employee already hired;- a Context only for owner-facing triggers (schedule, Chat): a publictrigger talks to many strangers, and one shared conversation would mixthem;@@ -49,6 +53,7 @@ from services.employees.hire_request import HireEmployeeRequest, HireTriggerfrom services.employees.llm import LLMChoicefrom services.approvals.contract import APPROVAL_GATE_TYPE, NO_REPLY, approved_edge_condition, send_conditionfrom services.employees.prompt import OwnerProfile, PromptInputs, build_system_message+from services.skill_runtime import is_personality_skillBUILDER_VERSION = 1@@ -58,10 +63,12 @@ SCHEDULE_TYPE = "cronScheduler"GATE_TYPE = APPROVAL_GATE_TYPECONSOLE_TYPE = "console"CONTEXT_TYPE = "context"+SKILLS_TYPE = "masterSkill"MEMORY_TYPE = "simpleMemory"SEARCH_TYPE = "duckduckgoSearch"TODOS_TYPE = "writeTodos"CLOCK_TYPE = "currentTimeTool"+CANVAS_TYPE = "canvas"#: cronScheduler's allowed times and zones (nodes/scheduler/cron_scheduler).SCHEDULE_TIMES = ("00:00", "02:00", "04:00", "06:00", "08:00", "09:00", "10:00", "12:00", "14:00", "16:00", "18:00", "20:00", "22:00")@@ -98,6 +105,39 @@ class BuildError(ValueError):self.code = code+@dataclass(frozen=True)+class LibrarySkill:+ """A skill from the owner's library that is on for new hires."""++ name: str+ description: str+ instructions: str+++#: The Skill tool's own entry on an assistant Skills node (MasterSkillParams).+_SKILL_TOOL_ENTRY: Dict[str, Any] = {"enabled": True, "instructions": "", "isCustomized": False, "required": True}+++def _skills_config(skills: Sequence[LibrarySkill], warnings: List[str]) -> Optional[Dict[str, Any]]:+ """The Skills node's ``skills_config``: the Skill tool's entry, then each+ library skill with its text. None when no skill qualifies (no node).++ A skill named ``skill`` would take over the Skill tool's own entry, and a+ ``*-personality`` skill would replace the whole system message (and with+ it the rules prompt.py writes), so neither is given to a hire.+ """+ config: Dict[str, Any] = {"skill": dict(_SKILL_TOOL_ENTRY)}+ for skill in skills:+ name = skill.name.strip()+ if not name or not skill.instructions.strip():+ continue+ if name in config or is_personality_skill(name):+ warnings.append(f"The skill {name!r} can't be given to a hired employee")+ continue+ config[name] = {"enabled": True, "instructions": skill.instructions, "isCustomized": False, "description": skill.description}+ return config if len(config) > 1 else None++@dataclassclass BuildInputs:workflow_id: str@@ -113,6 +153,8 @@ class BuildInputs:timezone: str = "UTC"llm: Optional[LLMChoice] = Nonememory: bool = True+ #: Settings > Skills: the library skills that are on.+ skills: Sequence[LibrarySkill] = ()#: Hire allowlist (services.node_allowlist.is_hire_allowed).allowed: Callable[[str], bool] = lambda _node_type: Truenow: Optional[datetime] = None@@ -529,6 +571,7 @@ def build_employee_graph(inputs: BuildInputs) -> BuiltEmployee:delivery_app=delivery.app.name if delivery is not None else None,unsupported_apps=list(inputs.unsupported_apps),has_memory=inputs.memory,+ has_canvas=True,))if trigger.kind == "schedule" and request.trigger is not None and request.trigger.every == "weekday":@@ -573,6 +616,7 @@ def build_employee_graph(inputs: BuildInputs) -> BuiltEmployee:add_tool(CLOCK_TYPE, "Clock", {"timezone": inputs.timezone or "UTC"})if inputs.memory:add_tool(MEMORY_TYPE, "Memory", {}, role="memory")+ add_tool(CANVAS_TYPE, "Canvas", {}, role="canvas")for app in inputs.apps:for tool in app.tools:if request.rules.ask_first and not allowed_when_asking_first(tool.side_effects):@@ -593,6 +637,14 @@ def build_employee_graph(inputs: BuildInputs) -> BuiltEmployee:)graph.connect(roles["context"], "output-context", roles["agent"], "input-context")+ # Skills from the owner's library.+ skills_config = _skills_config(inputs.skills, warnings)+ if skills_config is not None:+ roles["skills"] = graph.add(+ SKILLS_TYPE, labels.take("Skills"), {"skill_folder": "assistant", "skills_config": skills_config}, (-60, 440)+ )+ graph.connect(roles["skills"], "output-tool", roles["agent"], "input-skill")+# Delivery.if delivery is not None:upstream, condition = roles["agent"], SEND_CONDITION@@ -639,6 +691,7 @@ __all__ = ["BuildError","BuildInputs","BuiltEmployee",+ "LibrarySkill","SEND_CONDITION","build_employee_graph","label_key",diff --git a/server/services/employees/graph_index.py b/server/services/employees/graph_index.pyindex 5ac4a1a7..b9d266f6 100644--- a/server/services/employees/graph_index.py+++ b/server/services/employees/graph_index.py@@ -4,8 +4,9 @@ Normal mode lists every workflow as an employee. A hired one has a row in``employees`` that names its parts (``node_roles``); one built in theeditor does not, so its summary is read off the graph: which nodes areagents (whose activity the card follows live), which are triggers (what-starts it), which apps its nodes belong to, and whether it waits for the-owner's approval before sending.+starts it), which apps its nodes belong to, whether it waits for the+owner's approval before sending, and which canvas board the Workspace+shows."""from __future__ import annotations@@ -17,6 +18,7 @@ from constants import AI_AGENT_TYPES, WORKFLOW_TRIGGER_TYPESfrom services.employees.apps import AppSpec, app_for_node_typeTODO_NODE_TYPE = "writeTodos"+CANVAS_NODE_TYPE = "canvas"APPROVAL_GATE_TYPE = "approvalGate"SCHEDULE_TRIGGER_TYPE = "cronScheduler"CHAT_TRIGGER_TYPE = "chatTrigger"@@ -31,6 +33,7 @@ class GraphIndex:agent_ids: Tuple[str, ...] = ()trigger_ids: Tuple[str, ...] = ()todo_ids: Tuple[str, ...] = ()+ canvas_ids: Tuple[str, ...] = ()gate_ids: Tuple[str, ...] = ()#: Apps the graph's nodes belong to, in first-seen order.app_ids: Tuple[str, ...] = ()@@ -60,6 +63,7 @@ def index_graph(graph: Optional[Mapping[str, Any]]) -> GraphIndex:agents: List[str] = []triggers: List[str] = []todos: List[str] = []+ canvases: List[str] = []gates: List[str] = []app_ids: List[str] = []for node in nodes:@@ -82,6 +86,8 @@ def index_graph(graph: Optional[Mapping[str, Any]]) -> GraphIndex:triggers.append(node_id)if node_type == TODO_NODE_TYPE:todos.append(node_id)+ if node_type == CANVAS_NODE_TYPE:+ canvases.append(node_id)if node_type == APPROVAL_GATE_TYPE:gates.append(node_id)app = app_for_node_type(node_type)@@ -93,6 +99,7 @@ def index_graph(graph: Optional[Mapping[str, Any]]) -> GraphIndex:agent_ids=tuple(agents),trigger_ids=tuple(triggers),todo_ids=tuple(todos),+ canvas_ids=tuple(canvases),gate_ids=tuple(gates),app_ids=tuple(app_ids),)@@ -100,6 +107,7 @@ def index_graph(graph: Optional[Mapping[str, Any]]) -> GraphIndex:__all__ = ["APPROVAL_GATE_TYPE",+ "CANVAS_NODE_TYPE","CHAT_TRIGGER_TYPE","GraphIndex","SCHEDULE_TRIGGER_TYPE",diff --git a/server/services/employees/handlers.py b/server/services/employees/handlers.pyindex 5567b4db..4f9356e9 100644--- a/server/services/employees/handlers.py+++ b/server/services/employees/handlers.py@@ -2,8 +2,9 @@``list_employees`` -> ``{employees: EmployeeSummary[]}``: the whole team forthe Home sidebar. ``get_employee {workflow_id}`` -> ``{employee}``: one-summary plus what the employee card and its setup screen show. Shapes are-documented in services/employees/summaries.py.+summary plus what the employee card and its setup screen show.+``get_employee_usage {}`` -> ``{tasks_this_month}``: Settings > Billing.+Shapes are documented in services/employees/summaries.py."""from __future__ import annotations@@ -12,7 +13,7 @@ from typing import Any, Dictfrom fastapi import WebSocket-from services.employees.summaries import get_employee_detail, list_employee_summaries+from services.employees.summaries import employee_usage, get_employee_detail, list_employee_summariesfrom services.plugin.base import NodeUserErrorfrom services.plugin.ws import ws_response@@ -38,15 +39,23 @@ async def handle_get_employee(data: Dict[str, Any], websocket: WebSocket) -> Dicreturn {"success": True, "employee": employee}+@ws_response+async def handle_get_employee_usage(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ from core.container import container++ return {"success": True, **await employee_usage(container.database())}++from services.employees.hire import handle_hire_employee # noqa: E402from services.employees.start import handle_start_employee # noqa: E402WS_HANDLERS: Dict[str, Any] = {"list_employees": handle_list_employees,"get_employee": handle_get_employee,+ "get_employee_usage": handle_get_employee_usage,"hire_employee": handle_hire_employee,"start_employee": handle_start_employee,}-__all__ = ["WS_HANDLERS", "handle_get_employee", "handle_list_employees"]+__all__ = ["WS_HANDLERS", "handle_get_employee", "handle_get_employee_usage", "handle_list_employees"]diff --git a/server/services/employees/hire.py b/server/services/employees/hire.pyindex 6e64bdfb..da34b51c 100644--- a/server/services/employees/hire.py+++ b/server/services/employees/hire.py@@ -6,7 +6,8 @@response); the same key with a different payload is refused.3. Resolve the named apps against the registry (unknown ones are kept asunsupported, never blocking), pick the AI model, look up the owner's- own addresses for reports, and build the graph (builder.py).+ own addresses for reports and the skills that are on in their library,+ and build the graph (builder.py).4. Validate it exactly as a Start would (errors refuse the hire), save itas a new workflow, attach it to the row, and announce the hire.5. Start it in the background when nothing is missing (every app it uses@@ -32,7 +33,7 @@ from core.logging import get_loggerfrom services.authz.ws_surface import execution_principalfrom services.employees import storefrom services.employees.apps import AppSpec, resolve_app-from services.employees.builder import BUILDER_VERSION, BuildError, BuildInputs, build_employee_graph+from services.employees.builder import BUILDER_VERSION, BuildError, BuildInputs, LibrarySkill, build_employee_graphfrom services.employees.connections import Connectionsfrom services.employees.context import SETTINGS_USER_IDfrom services.employees.events import broadcast_employee_event@@ -97,6 +98,19 @@ async def _owner_values(connections: Connections, auth_service: Any) -> Dict[strreturn values+async def _library_skills(database: Any) -> List[LibrarySkill]:+ """Settings > Skills: the skills that are on, which every new hire gets."""+ rows = await database.get_all_user_skills(active_only=True)+ return [+ LibrarySkill(+ name=str(row.get("name") or ""),+ description=str(row.get("description") or ""),+ instructions=str(row.get("instructions") or ""),+ )+ for row in rows+ ]++def _owner_profile(settings: Dict[str, Any]) -> OwnerProfile:call = str(settings.get("profile_call_name") or "").strip()full = str(settings.get("profile_full_name") or "").strip()@@ -216,6 +230,7 @@ async def handle_hire_employee(data: Dict[str, Any], websocket: WebSocket) -> Ditimezone=str(settings.get("profile_timezone") or "UTC"),llm=llm,memory=settings.get("memory_across_chats") is not False,+ skills=await _library_skills(database),allowed=is_hire_allowed,))diff --git a/server/services/employees/prompt.py b/server/services/employees/prompt.pyindex dc305566..377edf43 100644--- a/server/services/employees/prompt.py+++ b/server/services/employees/prompt.py@@ -54,6 +54,8 @@ class PromptInputs:unsupported_apps: Sequence[str] = ()has_memory: bool = Falsehas_todos: bool = True+ #: The canvas tool, whose board the owner sees in Home's Workspace.+ has_canvas: bool = Falsedef _clean(text: str) -> str:@@ -138,6 +140,11 @@ def _rules(inputs: PromptInputs, owner: str) -> List[str]:"- For work with more than one step, keep a short checklist with the write_todos tool: add the steps ""first, then mark each one done as you finish it. The owner watches it to see what you are doing.")+ if inputs.has_canvas:+ out.append(+ f"- When you finish something {owner} may want to look at later (a report, a list, a file you made), "+ "also put it on your canvas with the canvas tool. Don't put routine replies there."+ )if inputs.has_memory:out.append(f"- Check your memory before answering anything about {owner} or the people you talk to, and remember "diff --git a/server/services/employees/runs.py b/server/services/employees/runs.pyindex 8395e676..9164d592 100644--- a/server/services/employees/runs.py+++ b/server/services/employees/runs.py@@ -1,7 +1,8 @@"""Run records: one row per finished run of a deployed workflow.The employee card's "N done today" counts successful runs since the start-of the owner's day (``profile_timezone``, UTC when unset). Records are+of the owner's day (``profile_timezone``, UTC when unset), and Settings >+Billing counts them since the start of the owner's month. Records arewritten once per run (``run_id`` is unique, so an activity retry or bothruntimes seeing the same run changes nothing) and pruned after``RETENTION_DAYS``. A new record refreshes the employee's summary through@@ -24,6 +25,7 @@ from models.employees import WorkflowRunRecordlogger = get_logger(__name__)+#: Longer than any month, so this month's count is always complete.RETENTION_DAYS = 35RUN_STATUSES = ("success", "failed")RUNTIMES = ("temporal", "local")@@ -51,6 +53,13 @@ def start_of_day(now: datetime, zone: ZoneInfo) -> datetime:return midnight.astimezone(timezone.utc)+def start_of_month(now: datetime, zone: ZoneInfo) -> datetime:+ """Midnight on the 1st of this month in ``zone``, as a UTC instant."""+ local = now.astimezone(zone)+ first = local.replace(day=1, hour=0, minute=0, second=0, microsecond=0)+ return first.astimezone(timezone.utc)++async def record_run(database: Any,*,@@ -110,6 +119,18 @@ async def done_today(return {workflow_id: int(count) for workflow_id, count in result.all()}+async def done_this_month(database: Any, *, zone: ZoneInfo, now: Optional[datetime] = None) -> int:+ """Successful runs since the 1st of the month in the owner's zone, across every workflow."""+ since = start_of_month(now or _utcnow(), zone)+ async with database.get_session() as session:+ result = await session.execute(+ select(func.count())+ .select_from(WorkflowRunRecord)+ .where(WorkflowRunRecord.status == "success", WorkflowRunRecord.finished_at >= since)+ )+ return int(result.scalar_one() or 0)++async def latest_run(database: Any, workflow_id: str) -> Optional[Dict[str, Any]]:async with database.get_session() as session:result = await session.execute(@@ -161,10 +182,12 @@ def reset_for_tests() -> None:__all__ = ["RETENTION_DAYS","delete_runs_for_workflow",+ "done_this_month","done_today","latest_run","owner_zone","prune_run_records","record_run","start_of_day",+ "start_of_month",]diff --git a/server/services/employees/summaries.py b/server/services/employees/summaries.pyindex 9cfc7483..50150b0d 100644--- a/server/services/employees/summaries.py+++ b/server/services/employees/summaries.py@@ -19,6 +19,7 @@ from __future__ import annotationsfrom datetime import datetime, timezonefrom typing import Any, Dict, Iterable, List, Mapping, Optional+from zoneinfo import ZoneInfofrom core.logging import get_loggerfrom services.deployment.control import serialize_control@@ -201,6 +202,10 @@ async def _summary(watch = [roles[key] for key in ("agent", "todos") if roles.get(key)] if roles else []if not watch:watch = list(graph.agent_ids) + list(graph.todo_ids)+ # The board Home's Workspace shows: the one the hire made, while it is+ # still in the graph, else the first canvas the owner added.+ canvas = roles.get("canvas") if roles else None+ canvas_node_id = canvas if canvas in graph.canvas_ids else next(iter(graph.canvas_ids), None)return {"workflow_id": workflow.id,"name": workflow.name,@@ -217,6 +222,7 @@ async def _summary("needs_ai": needs_ai,"control": control,"watch_node_ids": watch,+ "canvas_node_id": canvas_node_id,"revision": _millis(getattr(workflow, "updated_at", None),getattr(employee, "updated_at", None),@@ -237,19 +243,35 @@ async def _pending_counts(database: Any, workflow_ids: Iterable[str]) -> Dict[streturn {}-async def _done_today(database: Any, workflow_ids: Iterable[str]) -> Dict[str, int]:- """Successful runs since the start of the owner's day, per workflow."""+async def _owner_zone(database: Any) -> ZoneInfo:+ """The owner's time zone (Settings > Profile), UTC when unset or unreadable."""try:settings = await database.get_user_settings(SETTINGS_USER_ID) or {}except Exception:settings = {}+ return runs.owner_zone(settings.get("profile_timezone"))+++async def _done_today(database: Any, workflow_ids: Iterable[str]) -> Dict[str, int]:+ """Successful runs since the start of the owner's day, per workflow."""+ zone = await _owner_zone(database)try:- return await runs.done_today(database, workflow_ids, zone=runs.owner_zone(settings.get("profile_timezone")))+ return await runs.done_today(database, workflow_ids, zone=zone)except Exception:logger.warning("Could not count today's runs", exc_info=True)return {}+async def employee_usage(database: Any) -> Dict[str, int]:+ """Settings > Billing: the team's successful runs so far this month.++ Errors propagate, so the page shows that the count is unavailable+ rather than a zero.+ """+ zone = await _owner_zone(database)+ return {"tasks_this_month": await runs.done_this_month(database, zone=zone)}++async def _latest_run(database: Any, workflow_id: str) -> Optional[Dict[str, Any]]:"""The most recent finished run."""try:@@ -335,6 +357,7 @@ async def get_employee_detail(database: Any, workflow_id: str, *, auth_service:__all__ = [+ "employee_usage","get_employee_detail","get_employee_summary","list_employee_summaries",diff --git a/server/services/skill_runtime.py b/server/services/skill_runtime.pyindex 367a43af..26d9382f 100644--- a/server/services/skill_runtime.py+++ b/server/services/skill_runtime.py@@ -44,9 +44,15 @@ def validate_connected_skills(skills: Iterable[Dict[str, Any]]) -> None:)+def is_personality_skill(name: Any) -> bool:+ """A personality skill defines the agent itself: its full text replaces+ the agent's system message instead of joining the Skill tool."""+ return str(name or "").endswith("-personality")++def standard_skill_descriptors(skills: Iterable[Dict[str, Any]]) -> List[Dict[str, Any]]:validate_connected_skills(skills)- return [item for item in skills if not str(item.get("skill_name") or "").endswith("-personality")]+ return [item for item in skills if not is_personality_skill(item.get("skill_name"))]def skill_tool_info(skills: Iterable[Dict[str, Any]], agent_node_id: str) -> Dict[str, Any] | None:diff --git a/server/skills/GUIDE.md b/server/skills/GUIDE.mdindex 588fb926..03401831 100644--- a/server/skills/GUIDE.md+++ b/server/skills/GUIDE.md@@ -162,6 +162,26 @@ To create a new skill group (appears as a new option in the folder dropdown):3. The folder will automatically appear in the Master Skill node dropdown.+## The `employee` folder (Normal mode)++`server/skills/employee/` is what Home's Settings > Skills offers under+Discover: skills an owner can add to their library, which every employee+hired afterwards gets. They differ from the other folders in three ways:++- **No `allowed-tools`.** A hired employee may not have the tool a skill+ would teach, so these are plain instructions. With no node to take visuals+ from, each sets `icon` (a `lucide:` reference) and `color` in `metadata`.+- **Owner-facing card copy.** `metadata.title` and `metadata.summary` are what+ the card shows. `description` stays written for the model: it says when to+ load the skill.+- **Unique, non-reserved names.** The name must not appear in another+ folder, and must not be `skill` or end in `-personality`.++`server/tests/test_home_catalog_contract.py` holds the folder to these rules,+and holds the starter bundles (`client/src/features/home/hire/starters.json`)+to the skills in it. Adding a skill here needs no code change: it appears in+Discover.+## How Skills Are Used1. **Master Skill Node**: Select a folder from the dropdown. Enable/disable individual skills with checkboxes. Edit instructions inline.diff --git a/server/skills/employee/ask-for-reviews/SKILL.md b/server/skills/employee/ask-for-reviews/SKILL.mdnew file mode 100644index 00000000..7ccdd4a3--- /dev/null+++ b/server/skills/employee/ask-for-reviews/SKILL.md@@ -0,0 +1,22 @@+---+name: ask-for-reviews+description: Use after a customer has had a good experience (a finished booking, a thank-you message). Asks for a review once, politely, with a link if the owner gave one.+metadata:+ author: opencompany+ version: "1.0"+ category: customers+ icon: "lucide:Star"+ color: "#f1fa8c"+ title: Ask for reviews+ summary: Asks happy customers for a review, politely and only once.+---++# Ask for reviews++Ask for a review only when a customer is clearly happy: they said thanks, they praised the service, or a visit went well.++- Ask once per customer. If you asked before, don't ask again.+- Keep it to two sentences: thank them, then ask. For example: "Thanks so much, Priya! If you have a minute, a short review would really help us."+- Add the review link if the owner gave one. Don't invent one.+- Never offer anything in return for a review, and never ask for a good review specifically.+- If a customer is unhappy, don't ask. Apologise, and tell the owner in your report.diff --git a/server/skills/employee/book-appointments/SKILL.md b/server/skills/employee/book-appointments/SKILL.mdnew file mode 100644index 00000000..045f048c--- /dev/null+++ b/server/skills/employee/book-appointments/SKILL.md@@ -0,0 +1,33 @@+---+name: book-appointments+description: Use when someone wants to book, move or cancel an appointment. Offers real free times, confirms the details, and never double-books.+metadata:+ author: opencompany+ version: "1.0"+ category: scheduling+ icon: "lucide:CalendarCheck"+ color: "#50fa7b"+ title: Book appointments+ summary: Offers free times, confirms the details, and never double-books.+---++# Book appointments++## Booking++1. Find out what they want and roughly when: the service, the day, morning or afternoon.+2. Check the calendar before offering anything. Offer two or three free times that fit, nearest first.+3. When they pick one, repeat it back in one line: the service, the day and date, the time, and the place.+4. Book it only after they confirm. Then say it is booked and what to bring or know.++## Moving or cancelling++- Find the existing booking first, by name and date. If you can't find it, ask for the date they booked.+- Offer new times the same way as a new booking. Remove the old slot only once the new one is confirmed.+- For a cancellation, confirm which booking, cancel it, and say it is done.++## Rules++- Never offer a time you haven't checked, and never book two people into one slot.+- Keep to the opening hours the owner set. Outside them, say when you are open.+- If a request needs the owner (a discount, a special case, anything unusual), say you will check and get back to them. Then put it in your report.diff --git a/server/skills/employee/chase-late-payments/SKILL.md b/server/skills/employee/chase-late-payments/SKILL.mdnew file mode 100644index 00000000..67d067e1--- /dev/null+++ b/server/skills/employee/chase-late-payments/SKILL.md@@ -0,0 +1,28 @@+---+name: chase-late-payments+description: Use when an invoice is past its due date. Sends polite, firm reminders that get firmer over time, and hands anything disputed to the owner.+metadata:+ author: opencompany+ version: "1.0"+ category: money+ icon: "lucide:Receipt"+ color: "#ffb86c"+ title: Chase late payments+ summary: Polite, firm reminders for overdue invoices, then hands off to you.+---++# Chase late payments++## The reminders++1. **A few days late**: a friendly nudge. Name the invoice, the amount and the due date, and include how to pay.+2. **About two weeks late**: firmer. Say the payment is now overdue, and ask when they expect to pay.+3. **A month late**: stop. Don't send a third reminder; tell the owner instead.++## Rules++- Always include the invoice number, the amount with its currency, and the original due date.+- Stay polite even when you are firm. Never threaten, and never mention late fees the owner has not set.+- If the customer says they already paid, or disputes the amount, don't argue. Thank them, say you will check, and report it to the owner straight away.+- Never change an invoice, cancel one, or promise a discount yourself.+- In your report, list what you sent to whom, and who has not answered.diff --git a/server/skills/employee/reply-in-their-language/SKILL.md b/server/skills/employee/reply-in-their-language/SKILL.mdnew file mode 100644index 00000000..151a2732--- /dev/null+++ b/server/skills/employee/reply-in-their-language/SKILL.md@@ -0,0 +1,22 @@+---+name: reply-in-their-language+description: Use when a message arrives in a language other than the one you usually write in, or mixes languages. Replies in the sender's language.+metadata:+ author: opencompany+ version: "1.0"+ category: writing+ icon: "lucide:Languages"+ color: "#8be9fd"+ title: Reply in their language+ summary: Answers each customer in the language they wrote in.+---++# Reply in their language++Answer each person in the language they wrote to you in.++- Look at the whole message, not just the first word. If it mixes languages, use the one most of the message is in.+- Keep names, prices, dates, addresses and booking codes exactly as they are. Write dates the way people in that language usually do.+- Keep the same tone you would use in your usual language: polite, short and clear.+- If you can't tell which language it is, reply briefly in your usual language and ask which they prefer.+- Reports to the owner stay in the owner's language, even when you quote a customer. Add a one-line translation after the quote.diff --git a/server/skills/employee/short-reports/SKILL.md b/server/skills/employee/short-reports/SKILL.mdnew file mode 100644index 00000000..9db4ecc3--- /dev/null+++ b/server/skills/employee/short-reports/SKILL.md@@ -0,0 +1,27 @@+---+name: short-reports+description: Use when writing a report or summary for the owner. Leads with what needs them, then what got done, in a few short lines.+metadata:+ author: opencompany+ version: "1.0"+ category: reporting+ icon: "lucide:FileText"+ color: "#8be9fd"+ title: Short reports+ summary: "Reports you can read in ten seconds, with what needs you first."+---++# Short reports++The owner should understand your report in about ten seconds.++1. **First line**: what needs them, if anything. For example: "2 things need you: a refund request from Tom, and a double booking on Friday."+2. **Then what you did**, one short line per item, with numbers: "Answered 12 messages, booked 3 appointments."+3. **Then anything worth knowing** that doesn't need them now. Leave it out if there is nothing.++## Rules++- No greetings, no sign-off, no headings.+- Use names and numbers rather than "several" or "some".+- If nothing happened and nothing needs them, say so in one line.+- Don't repeat what you reported last time unless it is still waiting for them.diff --git a/server/skills/employee/social-posts/SKILL.md b/server/skills/employee/social-posts/SKILL.mdnew file mode 100644index 00000000..1f1e3ae4--- /dev/null+++ b/server/skills/employee/social-posts/SKILL.md@@ -0,0 +1,28 @@+---+name: social-posts+description: Use when drafting a social media post for the business. Writes short posts in the business's own voice, with one clear point and a call to action.+metadata:+ author: opencompany+ version: "1.0"+ category: marketing+ icon: "lucide:Megaphone"+ color: "#ff79c6"+ title: Social posts+ summary: Short posts in your business's voice, one clear point each.+---++# Social posts++## Each post++- Make one point: a new service, an opening, a tip, a customer story. Don't cram in two.+- Open with the interesting part; the first line is all most people read.+- End with one clear next step: "Book through the link", "Drop by on Saturday".+- Keep it short: two to four sentences. Use at most two hashtags, and only ones people actually search for.+- Write in the business's voice: look at its earlier posts, or the owner's notes, and match them.++## Rules++- Never post something you haven't been asked to post. Draft it for the owner unless they told you to publish.+- Don't make claims you can't back up ("the best in town"), and don't mention prices or offers the owner hasn't given you.+- Only use a customer's name, photo or words if the owner says they agreed.diff --git a/server/skills/employee/write-like-a-person/SKILL.md b/server/skills/employee/write-like-a-person/SKILL.mdnew file mode 100644index 00000000..e00b2d1e--- /dev/null+++ b/server/skills/employee/write-like-a-person/SKILL.md@@ -0,0 +1,35 @@+---+name: write-like-a-person+description: Use when writing anything a customer or the owner will read. Makes messages sound like a warm, capable person instead of a bot.+metadata:+ author: opencompany+ version: "1.0"+ category: writing+ icon: "lucide:PenLine"+ color: "#bd93f9"+ title: Write like a person+ summary: Warm, plain messages that sound like a real person, not a bot.+---++# Write like a person++Every message you send should read as if a friendly, capable person on the team wrote it.++## Do++- Use short sentences and everyday words. Say "we can do 3pm" rather than "an appointment slot at 15:00 is available".+- Answer the question first, then add only what helps.+- Use the person's name when you know it, once.+- Match their tone: brief when they are brief, warmer when they are chatty.+- Say plainly what happens next and when.++## Don't++- Don't open with "Certainly!", "Great question!" or "I hope this message finds you well".+- Don't use headings, bullet lists or bold text in a chat message. Keep lists for email, and only when there are three or more items.+- Don't mention that you are an AI unless someone asks. If they ask, say so honestly.+- Don't promise anything the owner has not agreed to (prices, refunds, dates).++## Before sending++Read the message once as the customer would. If a sentence could be cut without losing anything, cut it.diff --git a/server/tests/services/employees/test_graph_builder.py b/server/tests/services/employees/test_graph_builder.pyindex fe7d5fd8..3168e453 100644--- a/server/tests/services/employees/test_graph_builder.py+++ b/server/tests/services/employees/test_graph_builder.py@@ -16,6 +16,7 @@ from services.employees.builder import (SEND_CONDITION,BuildError,BuildInputs,+ LibrarySkill,build_employee_graph,label_key,schedule_params,@@ -202,3 +203,91 @@ def test_schedule_mapping():# Sydney matches nothing listed: expressed in UTC (09:00 AEST = 23:00 UTC the day before).sydney = schedule_params(HireTrigger(kind="schedule", every="day", at="09:00"), "Australia/Sydney", NOW)assert sydney == {"frequency": "days", "daily_time": "22:00", "timezone": "UTC"}+++# ----- the owner's skill library -----++LIBRARY = (+ LibrarySkill(name="book-appointments", description="Offers free times.", instructions="# Book\nOffer real times."),+ LibrarySkill(name="my-tone", description="How I write.", instructions="Write warmly."),+)+++async def test_library_skills_ride_one_skills_node():+ built = build_employee_graph(inputs(hire(), "whatsapp", connected={"whatsapp"}, skills=LIBRARY))+ skills = node(built, "skills")+ assert skills["type"] == "masterSkill"+ params = built.parameters[skills["id"]]+ assert params["skill_folder"] == "assistant"+ config = params["skills_config"]+ assert list(config) == ["skill", "book-appointments", "my-tone"]+ assert config["skill"] == {"enabled": True, "instructions": "", "isCustomized": False, "required": True}+ # The text is copied in: the agent reads a library skill only from here.+ assert config["book-appointments"] == {+ "enabled": True,+ "instructions": "# Book\nOffer real times.",+ "isCustomized": False,+ "description": "Offers free times.",+ }+ [edge] = edges_between(built, "skills", "agent")+ assert (edge["sourceHandle"], edge["targetHandle"]) == ("output-tool", "input-skill")+ await assert_valid(built)+++async def test_the_skills_node_expands_into_the_skill_tool():+ from nodes.skill._expander import expand_master_skill+ from services.skill_runtime import skill_tool_info++ built = build_employee_graph(inputs(hire(), "whatsapp", connected={"whatsapp"}, skills=LIBRARY))+ config = built.parameters[built.node_roles["skills"]]["skills_config"]+ entries = await expand_master_skill(built.node_roles["skills"], config)+ catalogue = skill_tool_info(entries, built.node_roles["agent"])["parameters"]["tool_description"]+ assert "- book-appointments: Offers free times." in catalogue+ assert "- my-tone: How I write." in catalogue+++def test_an_empty_library_adds_no_skills_node():+ built = build_employee_graph(inputs(hire(), "whatsapp", connected={"whatsapp"}))+ assert "skills" not in built.node_roles+ assert not any(n["type"] == "masterSkill" for n in built.nodes)+ blank = (LibrarySkill(name="blank", description="Nothing", instructions=" "),)+ assert "skills" not in build_employee_graph(inputs(hire(), "whatsapp", connected={"whatsapp"}, skills=blank)).node_roles+++def test_reserved_skill_names_never_reach_a_hire():+ skills = (+ LibrarySkill(name="skill", description="Takes over the Skill tool", instructions="x"),+ LibrarySkill(name="pirate-personality", description="Replaces the system message", instructions="x"),+ LibrarySkill(name="ok-skill", description="Fine", instructions="y"),+ )+ built = build_employee_graph(inputs(hire(), "whatsapp", connected={"whatsapp"}, skills=skills))+ config = built.parameters[built.node_roles["skills"]]["skills_config"]+ assert set(config) == {"skill", "ok-skill"}+ assert config["skill"]["instructions"] == ""+ assert sum("can't be given" in warning for warning in built.warnings) == 2+++def test_the_skills_node_needs_the_allowlist():+ with pytest.raises(BuildError) as raised:+ build_employee_graph(+ inputs(hire(), "whatsapp", connected={"whatsapp"}, skills=LIBRARY, allowed=lambda node_type: node_type != "masterSkill")+ )+ assert raised.value.code == "not_allowed"+++# ----- the canvas the Workspace shows -----+++async def test_every_hire_gets_a_canvas():+ built = build_employee_graph(inputs(hire(), "whatsapp", connected={"whatsapp"}))+ assert node(built, "canvas")["type"] == "canvas"+ [edge] = edges_between(built, "canvas", "agent")+ assert (edge["sourceHandle"], edge["targetHandle"]) == ("output-tool", "input-tools")+ assert "canvas tool" in built.parameters[built.node_roles["agent"]]["system_message"]+ await assert_valid(built)+++def test_the_canvas_needs_the_allowlist():+ with pytest.raises(BuildError) as raised:+ build_employee_graph(inputs(hire(), "whatsapp", connected={"whatsapp"}, allowed=lambda node_type: node_type != "canvas"))+ assert raised.value.code == "not_allowed"diff --git a/server/tests/services/employees/test_handlers.py b/server/tests/services/employees/test_handlers.pyindex 223bd116..f5b72981 100644--- a/server/tests/services/employees/test_handlers.py+++ b/server/tests/services/employees/test_handlers.py@@ -36,7 +36,7 @@ def container(monkeypatch, real_database):def test_handlers_are_registered_and_not_internal():registered = get_ws_handlers()- for name in ("list_employees", "get_employee"):+ for name in ("list_employees", "get_employee", "get_employee_usage"):assert name in registeredassert name not in INTERNAL_SOCKET_HANDLERS@@ -55,6 +55,20 @@ async def test_list_and_get(container, real_database):assert "trigger_text" in got["employee"]+async def test_usage_counts_this_months_successes(container, real_database, monkeypatch):+ from services.employees import events, runs++ monkeypatch.setattr(events, "employee_changed", lambda _workflow_id: None)++ async def no_prune(_database):+ return None++ monkeypatch.setattr(runs, "_maybe_prune", no_prune)+ await runs.record_run(real_database, workflow_id="1", run_id="r1", status="success", runtime="local")+ await runs.record_run(real_database, workflow_id="1", run_id="r2", status="failed", runtime="local")+ assert await handlers.handle_get_employee_usage({}, None) == {"success": True, "tasks_this_month": 1}++async def test_get_errors(container):missing = await handlers.handle_get_employee({"workflow_id": "nope"}, None)assert missing == {"success": False, "error": "not_found", "workflow_id": "nope"}diff --git a/server/tests/services/employees/test_hire_handler.py b/server/tests/services/employees/test_hire_handler.pyindex 881973a0..8e51059b 100644--- a/server/tests/services/employees/test_hire_handler.py+++ b/server/tests/services/employees/test_hire_handler.py@@ -110,10 +110,11 @@ async def test_a_hire_saves_a_valid_workflow_and_starts_it(harness):workflow = await harness.database.get_workflow(workflow_id)types = {node["type"] for node in workflow.data["nodes"]}- assert {"chatTrigger", "aiAgent", "context", "console", "writeTodos"} <= types+ assert {"chatTrigger", "aiAgent", "context", "console", "writeTodos", "canvas"} <= typesassert workflow.data["owner_id"] == "owner"row = await store.get_by_workflow(harness.database, workflow_id)assert row.hire_state == "ready" and row.node_roles["agent"].startswith(f"{workflow_id}:aiAgent:")+ assert employee["canvas_node_id"] == row.node_roles["canvas"]agent_params = await harness.database.get_node_parameters(row.node_roles["agent"])assert agent_params["provider"] == "openai" and "You are Ada" in agent_params["system_message"]kinds = [frame.get("stage") or frame["data"]["type"] for frame in harness.frames]@@ -154,3 +155,27 @@ async def test_bad_requests_are_refused(harness):assert (await hire.handle_hire_employee(payload(name=""), SOCKET))["error"] == "invalid_request"assert (await hire.handle_hire_employee(payload(steps=[]), SOCKET))["error"] == "invalid_request"assert (await hire.handle_hire_employee(payload(job="x" * 40000), SOCKET))["error"] == "too_large"+++async def test_new_hires_get_the_library_skills_that_are_on(harness):+ database = harness.database+ await database.create_user_skill(name="short-reports", display_name="Short reports", description="Short reports.", instructions="Keep it short.")+ await database.create_user_skill(name="old-habit", display_name="Old habit", description="Switched off.", instructions="Nope.")+ await database.update_user_skill(name="old-habit", is_active=False)++ result = await hire.handle_hire_employee(payload(idempotency_key="hire-skills"), SOCKET)+ assert result["success"] is True, result+ row = await store.get_by_workflow(database, result["employee"]["workflow_id"])+ params = await database.get_node_parameters(row.node_roles["skills"])+ assert set(params["skills_config"]) == {"skill", "short-reports"}++ # A later edit to the library leaves this employee as it was hired.+ await database.update_user_skill(name="short-reports", instructions="Changed.")+ params = await database.get_node_parameters(row.node_roles["skills"])+ assert params["skills_config"]["short-reports"]["instructions"] == "Keep it short."+++async def test_an_empty_library_gives_no_skills_node(harness):+ result = await hire.handle_hire_employee(payload(idempotency_key="hire-no-skills"), SOCKET)+ row = await store.get_by_workflow(harness.database, result["employee"]["workflow_id"])+ assert "skills" not in row.node_rolesdiff --git a/server/tests/services/employees/test_list_employees.py b/server/tests/services/employees/test_list_employees.pyindex ed68d391..db0da33a 100644--- a/server/tests/services/employees/test_list_employees.py+++ b/server/tests/services/employees/test_list_employees.py@@ -233,3 +233,42 @@ async def test_deleting_the_workflow_removes_the_employee(real_database, monkeypassert result["success"] is Trueassert await store.get_by_workflow(real_database, "9") is Noneassert ("removed", "9") in frames+++async def _hired(database, workflow_id, node_roles):+ row, _ = await store.reserve(database, owner_id="owner", idempotency_key=f"k{workflow_id}", payload_hash="h", fields={"role": "Receptionist"})+ await store.mark_ready(database, row.id, workflow_id=workflow_id, node_roles=node_roles)+++async def test_the_workspace_board_is_the_hires_canvas(real_database):+ await save(+ real_database,+ "5",+ "Maya",+ graph(node("5:aiAgent:1", "aiAgent", "Maya"), node("5:canvas:1", "canvas", "Board"), node("5:canvas:2", "canvas", "Canvas")),+ )+ await _hired(real_database, "5", {"agent": "5:aiAgent:1", "canvas": "5:canvas:2"})+ summary = await get_employee_summary(real_database, "5", auth_service=FakeAuth(keys={"openai"}))+ assert summary["canvas_node_id"] == "5:canvas:2"+ assert "5:canvas:2" not in summary["watch_node_ids"]+++async def test_a_removed_canvas_falls_back_to_one_the_owner_added(real_database):+ await save(+ real_database,+ "6",+ "Maya",+ graph(node("6:aiAgent:1", "aiAgent", "Maya"), node("6:canvas:9", "canvas", "Off", disabled=True), node("6:canvas:3", "canvas", "Canvas")),+ )+ # The hire's canvas was deleted in the editor; a disabled one is skipped.+ await _hired(real_database, "6", {"agent": "6:aiAgent:1", "canvas": "6:canvas:1"})+ summary = await get_employee_summary(real_database, "6", auth_service=FakeAuth(keys={"openai"}))+ assert summary["canvas_node_id"] == "6:canvas:3"+++async def test_an_editor_workflow_shows_its_canvas_and_none_means_no_board(real_database):+ await save(real_database, "7", "Support bot", graph(node("7:aiAgent:1", "aiAgent", "Support"), node("7:canvas:1", "canvas")))+ await save(real_database, "8", "Plain bot", graph(node("8:aiAgent:1", "aiAgent", "Plain")))+ summaries = {s["workflow_id"]: s for s in await list_employee_summaries(real_database, auth_service=FakeAuth(keys={"openai"}))}+ assert summaries["7"]["canvas_node_id"] == "7:canvas:1"+ assert summaries["8"]["canvas_node_id"] is Nonediff --git a/server/tests/services/employees/test_run_records.py b/server/tests/services/employees/test_run_records.pyindex 62726594..c600db73 100644--- a/server/tests/services/employees/test_run_records.py+++ b/server/tests/services/employees/test_run_records.py@@ -63,3 +63,25 @@ def test_midnight_is_computed_in_the_zone():now = datetime(2026, 9, 25, 3, 0, tzinfo=timezone.utc)assert runs.start_of_day(now, ZoneInfo("America/New_York")) == datetime(2026, 9, 24, 4, 0, tzinfo=timezone.utc)assert runs.owner_zone("Not/AZone").key == "UTC"+++async def test_done_this_month_counts_successes_across_the_team(real_database):+ zone = ZoneInfo("Asia/Kolkata") # UTC+5:30+ now = datetime(2026, 9, 25, 3, 0, tzinfo=timezone.utc)+ month_start = datetime(2026, 8, 31, 18, 30, tzinfo=timezone.utc) # 1 September, 00:00 in Kolkata+ rows = [+ ("w", "before", month_start - timedelta(minutes=1), "success"),+ ("w", "after", month_start + timedelta(minutes=1), "success"),+ ("other", "o1", now - timedelta(days=2), "success"),+ ("w", "broken", now - timedelta(hours=1), "failed"),+ ]+ for workflow_id, run_id, finished, status in rows:+ await runs.record_run(real_database, workflow_id=workflow_id, run_id=run_id, status=status, runtime="temporal", finished_at=finished)+ assert await runs.done_this_month(real_database, zone=zone, now=now) == 2+++def test_the_month_starts_in_the_owner_zone():+ now = datetime(2026, 9, 1, 2, 0, tzinfo=timezone.utc) # still 31 August in New York+ assert runs.start_of_month(now, ZoneInfo("America/New_York")) == datetime(2026, 8, 1, 4, 0, tzinfo=timezone.utc)+ # The month's count reads run records, so they must outlive a month.+ assert runs.RETENTION_DAYS > 31diff --git a/server/tests/test_credential_catalogue_consumer_fields.py b/server/tests/test_credential_catalogue_consumer_fields.pyindex ef6ce519..a29c22c6 100644--- a/server/tests/test_credential_catalogue_consumer_fields.py+++ b/server/tests/test_credential_catalogue_consumer_fields.py@@ -2,7 +2,8 @@state (``services.credential_registry.provider_connection_state``).Normal mode's Connectors grid lists only providers that declare a-``consumer_category`` and shows their short ``description``. ``connected``+``consumer_category`` and shows their short ``description``, a "by+{publisher}" line and a verified mark. ``connected``answers "is this app usable right now": the same as ``stored`` unless aprovider declares a ``connected_check`` (WhatsApp's live pairing, theIMAP/SMTP account's keys).@@ -66,6 +67,9 @@ class TestCatalogueFields:assert provider["consumer_category"] in known, provider["id"]description = provider.get("description")assert isinstance(description, str) and 0 < len(description) <= MAX_DESCRIPTION, provider["id"]+ publisher = provider.get("publisher")+ assert isinstance(publisher, str) and publisher.strip(), provider["id"]+ assert isinstance(provider.get("verified"), bool), provider["id"]def test_llm_providers_inherit_the_ai_category_and_deepl_opts_out(self, registry):assert registry.get_provider("openai")["consumer_category"] == "ai"diff --git a/server/tests/test_home_catalog_contract.py b/server/tests/test_home_catalog_contract.pynew file mode 100644index 00000000..8d58179e--- /dev/null+++ b/server/tests/test_home_catalog_contract.py@@ -0,0 +1,105 @@+"""Settings > Skills and Settings > Plugins read server content from the+client, so the two are held to each other here, reading the client files+off disk:++- the Discover folder the client names (``DISCOVER_SKILL_FOLDER`` in+ client/src/features/home/data/skills.ts) exists, is not disabled, and+ holds skills an AI employee can use as they are: owner-facing+ ``metadata.title`` and ``metadata.summary``, no tools to connect, no+ reserved name (``skill`` is the Skill tool's own entry, a+ ``*-personality`` skill replaces the whole system message), and a name no+ other folder uses;+- every starter bundle (client/src/features/home/hire/starters.json) uses+ only those skills, names apps the hire's app registry resolves, says so in+ its job (the job text is all the setup model reads), and fits the hire's+ job limit.+"""++from __future__ import annotations++import json+import re+from pathlib import Path++import pytest+import yaml++from services.employees.apps import normalize_name, resolve_app+from services.employees.hire_request import JOB_MAX++REPO_ROOT = Path(__file__).resolve().parents[2]+HOME = REPO_ROOT / "client" / "src" / "features" / "home"+SKILLS_TS = HOME / "data" / "skills.ts"+STARTERS_JSON = HOME / "hire" / "starters.json"+SKILLS_DIR = REPO_ROOT / "server" / "skills"+ALLOWLIST = REPO_ROOT / "server" / "config" / "node_allowlist.json"+++def _client(path: Path) -> str:+ if not path.exists():+ pytest.skip(f"client source not present: {path}")+ return path.read_text(encoding="utf-8")+++def _frontmatter(skill_md: Path) -> dict:+ match = re.match(r"^---\s*\n(.*?)\n---\s*\n", skill_md.read_text(encoding="utf-8"), re.DOTALL)+ assert match, f"{skill_md} has no frontmatter"+ return yaml.safe_load(match.group(1))++[email protected](scope="module")+def folder() -> str:+ match = re.search(r"export const DISCOVER_SKILL_FOLDER = '([^']+)';", _client(SKILLS_TS))+ assert match, "could not find DISCOVER_SKILL_FOLDER in skills.ts"+ return match.group(1)++[email protected](scope="module")+def discover_skills(folder) -> dict:+ return {path.parent.name: _frontmatter(path) for path in sorted((SKILLS_DIR / folder).glob("*/SKILL.md"))}++[email protected](scope="module")+def starters() -> list:+ return json.loads(_client(STARTERS_JSON))+++def test_the_discover_folder_exists_and_is_not_disabled(folder, discover_skills):+ assert (SKILLS_DIR / folder).is_dir()+ assert discover_skills, f"no skills in server/skills/{folder}"+ disabled = json.loads(ALLOWLIST.read_text(encoding="utf-8")).get("disabled_skill_folders", [])+ assert folder not in disabled+++def test_discover_skills_are_ready_for_an_employee(folder, discover_skills):+ elsewhere = {+ path.parent.name+ for path in SKILLS_DIR.glob("*/*/SKILL.md")+ if path.parent.parent.name != folder+ }+ for directory, frontmatter in discover_skills.items():+ name = frontmatter["name"]+ assert name == directory+ metadata = frontmatter.get("metadata") or {}+ assert str(metadata.get("title") or "").strip(), f"{name} has no metadata.title"+ assert str(metadata.get("summary") or "").strip(), f"{name} has no metadata.summary"+ assert "allowed-tools" not in frontmatter, f"{name} needs tools a hire may not have"+ assert name != "skill" and not name.endswith("-personality"), f"{name} is a reserved name"+ assert name not in elsewhere, f"{name} is also a skill in another folder"+++def test_starters_use_discover_skills_and_name_their_apps(starters, discover_skills):+ assert starters+ ids = [starter["id"] for starter in starters]+ assert len(ids) == len(set(ids))+ for starter in starters:+ assert starter["skills"], f"{starter['id']} has no skills"+ for skill in starter["skills"]:+ assert skill in discover_skills, f"{starter['id']} uses {skill!r}, which Discover does not offer"+ assert 0 < len(starter["job"]) <= JOB_MAX+ job = normalize_name(starter["job"])+ for app_name in starter["apps"]:+ app = resolve_app(app_name, [])+ assert app is not None, f"{starter['id']}: the app registry does not know {app_name!r}"+ words = [normalize_name(word) for word in (app.name, *app.aliases)]+ assert any(word and word in job for word in words), f"{starter['id']}'s job never mentions {app.name}"diff --git a/server/tests/test_node_allowlist_hire.py b/server/tests/test_node_allowlist_hire.pyindex a6adce3f..6407ff0f 100644--- a/server/tests/test_node_allowlist_hire.py+++ b/server/tests/test_node_allowlist_hire.py@@ -59,6 +59,8 @@ def test_the_shipped_config_allows_the_v1_employee_building_blocks():"cronScheduler","console","context",+ "canvas",+ "masterSkill","simpleMemory","writeTodos","currentTimeTool",