From 7b9ae96f17d9c7e0aae903facd9f27a84b9636a9 Mon Sep 17 00:00:00 2001 From: WooBin Date: Fri, 20 Nov 2026 19:19:15 -0800 Subject: [PATCH] @hanzo/app 0.3.111: pick your role, get its recommended skills, add them in one click hanzo-inc/app#323. A new customer says what they do (Director, Marketing, Education, Creative, Founder, Developer, Sales and support, Research and data, or Something else, or Skip). Hanzo then lists the catalogue skills recommended for that role. The customer unticks any they don't want and adds the rest in one click: a single activation for the org, the same write Customize and the + menu make. - roles.ts: the one role-to-skills map, as data. Every name is a brand catalogue skill (49, checked against the live index). - RolePicker.tsx: the picker, RoleDialog, and RoleCard. The card asks an account made in the last two weeks that hasn't answered. It sits in the sidebar column in either Developer mode. - Sidebar: Customize gets a "Skills for your role" row. - connect.ts: install(names), one PUT /v1/tools/activation. - The answer is kept on the account (hanzo.onboarding.role via usePref, /v1/pref). Co-Authored-By: Claude Opus 5.5 --- LLM.md | 11 + pkg/app/package.json | 2 +- pkg/app/src/RolePicker.test.tsx | 214 ++++++++++++++++++ pkg/app/src/RolePicker.tsx | 390 ++++++++++++++++++++++++++++++++ pkg/app/src/Sidebar.test.ts | 7 + pkg/app/src/Sidebar.tsx | 17 +- pkg/app/src/connect.test.ts | 34 +++ pkg/app/src/connect.ts | 14 ++ pkg/app/src/roles.test.ts | 95 ++++++++ pkg/app/src/roles.ts | 201 ++++++++++++++++ 10 files changed, 982 insertions(+), 3 deletions(-) create mode 100644 pkg/app/src/RolePicker.test.tsx create mode 100644 pkg/app/src/RolePicker.tsx create mode 100644 pkg/app/src/connect.test.ts create mode 100644 pkg/app/src/roles.test.ts create mode 100644 pkg/app/src/roles.ts diff --git a/LLM.md b/LLM.md index c1fea83..d70039e 100644 --- a/LLM.md +++ b/LLM.md @@ -176,6 +176,17 @@ repository or a site from any surface. Customize row and Settings' Plugins and Skills rows lead there (`app()`), and Directory lists only Works with and Channels. A list is the registry's answer or a plain line saying why there is none — never rows standing in for it. +- Skills for a person's role are one map, `roles.ts` (`ROLES`, `ELSE`, `SKILLS`): + each role names brand-catalogue skills (`/.well-known/agent-skills/index.json`, + `service_thing`), and nothing else lists them. `RolePicker.tsx` draws it: a + role (or Something else, or Skip), its skills to untick, and one click that + switches the rest on for the org (connect.ts `install`, one + `PUT /v1/tools/activation`, an org admin's). The answer is the person's, + `hanzo.onboarding.role` through `usePref`. A new account (made in the last two + weeks) that has not answered meets `RoleCard` in the sidebar's column, in + either Developer mode; anyone reaches the picker later from Customize's row + "Skills for your role" or the host's Settings (`RoleDialog`). Never an + interstitial: the owner retired the onboarding page (2026-10-29). - The apps and models in beta are one list, `lib/betas.ts` (`BETAS`, `GROUPS`): every app or model no one has yet on hanzo.ai or platform.hanzo.ai, with its id, name, line, group and where it opens. The Creative group is the six creative diff --git a/pkg/app/package.json b/pkg/app/package.json index 6687844..17ac1d0 100644 --- a/pkg/app/package.json +++ b/pkg/app/package.json @@ -1,6 +1,6 @@ { "name": "@hanzo/app", - "version": "0.3.110", + "version": "0.3.111", "description": "Hanzo's app: the shell and its apps (Home, Chat, Inbox, Contacts, Meet, Calendar, Drive, Board, Work, Bots), once, for every Hanzo surface.", "type": "module", "main": "./dist/index.js", diff --git a/pkg/app/src/RolePicker.test.tsx b/pkg/app/src/RolePicker.test.tsx new file mode 100644 index 0000000..be73567 --- /dev/null +++ b/pkg/app/src/RolePicker.test.tsx @@ -0,0 +1,214 @@ +// @vitest-environment happy-dom +// The picker as a person uses it (hanzo-inc/app issue 323): a role, the skills +// recommended for it, one unticked, one click to add the rest. The kit's parts +// draw as plain elements; the tool plane, the account and the write are stubs. +import { act, createElement as h, type ReactNode } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' + +;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true + +const { state, install } = vi.hoisted(() => ({ + install: vi.fn(async (names: readonly string[]) => names.map((n) => `skill_${n}`)), + state: { + prefs: new Map(), + joined: '' as string | undefined, + role: 'owner' as string | null, + rows: null as { name: string; description: string; activated: boolean }[] | null, + }, +})) + +vi.mock('@hanzo/ui', async () => { + const { createElement } = await import('react') + type Part = { children?: ReactNode; render?: unknown; onClick?: () => void; [k: string]: unknown } + const part = (p: Part) => { + const keep: Record = { onClick: p.onClick } + for (const [k, v] of Object.entries(p)) if (k.startsWith('data-') || k.startsWith('aria-') || k === 'role' || k === 'id') keep[k] = v + return createElement(typeof p.render === 'string' ? p.render : 'div', keep, p.children) + } + return { + Button: ({ children, onClick, disabled, ...rest }: { children?: ReactNode; onClick?: () => void; disabled?: boolean; [k: string]: unknown }) => + createElement('button', { type: 'button', onClick, disabled, 'data-slot': rest['data-slot'] }, children), + Checkbox: ({ checked, disabled, onCheckedChange, id, 'aria-label': label }: { checked?: boolean; disabled?: boolean; onCheckedChange?: (v: boolean) => void; id?: string; 'aria-label'?: string }) => + createElement('input', { type: 'checkbox', id, checked, disabled, 'aria-label': label, onChange: (e: { target: { checked: boolean } }) => onCheckedChange?.(e.target.checked) }), + Dialog: ({ children, open }: { children?: ReactNode; open?: boolean }) => (open ? createElement('div', { 'data-slot': 'dialog' }, children) : null), + DialogContent: part, + DialogTitle: part, + Text: part, + XStack: part, + YStack: part, + } +}) +vi.mock('lucide-react', () => ({ Check: () => null, Sparkles: () => null })) +vi.mock('@hanzo/i18n/react', () => ({ + useI18n: () => ({ t: (s: string, v?: Record) => (v ? s.replace(/{(\w+)}/g, (_, k) => String(v[k] ?? '')) : s) }), +})) +vi.mock('@hanzo/iam/react', () => ({ useIam: () => ({ isAuthenticated: true, accessToken: 'token' }) })) +vi.mock('./pref', () => ({ + usePref: (key: string, initial: unknown) => [state.prefs.has(key) ? state.prefs.get(key) : initial, (v: unknown) => state.prefs.set(key, v), true], +})) +vi.mock('./tools', () => ({ useSkills: () => ({ rows: state.rows, trouble: null }) })) +vi.mock('./connect', () => ({ install })) +vi.mock('./lib/account', () => ({ useAccount: () => ({ user: state.joined === undefined ? null : { joinedDate: state.joined } }) })) +vi.mock('./lib/session', () => ({ org: () => 'acme', role: () => state.role, superAdmin: () => false })) +vi.mock('./lib/host', () => ({ app: (p: string) => `/dev/${p.replace(/^-\//, '')}` })) +vi.mock('./where', () => ({ site: (p: string) => p })) + +const { RoleCard, RolePicker, detail } = await import('./RolePicker') +const { ROLE_KEY, SKIP, role } = await import('./roles') + +let host: HTMLDivElement +let root: Root + +const mount = async (el: ReturnType) => { + await act(async () => root.render(el)) +} +const press = async (slot: string, at: ParentNode = host) => { + const el = at.querySelector(`[data-slot="${slot}"]`) + expect(el, slot).toBeTruthy() + await act(async () => el!.click()) +} +const pick = (id: string) => host.querySelector(`[data-slot="role"][data-role="${id}"]`) +const skills = () => [...host.querySelectorAll('[data-slot="role-skill"]')].map((el) => el.dataset.skill) + +beforeEach(() => { + state.prefs.clear() + state.joined = new Date().toISOString() + state.role = 'owner' + state.rows = null + install.mockClear() + host = document.createElement('div') + document.body.appendChild(host) + root = createRoot(host) +}) + +afterEach(async () => { + await act(async () => root.unmount()) + host.remove() +}) + +describe('choosing a role (hanzo-inc/app issue 323)', () => { + test('offers every role, Something else and Skip', async () => { + await mount(h(RolePicker, {})) + for (const id of ['director', 'marketing', 'education', 'creative', 'founder', 'developer', 'sales', 'research', 'else']) expect(pick(id), id).toBeTruthy() + expect(host.textContent).toContain('Something else') + expect(host.querySelector('[data-slot="role-skip"]')).toBeTruthy() + }) + + test('Skip answers for the account and closes', async () => { + const onClose = vi.fn() + await mount(h(RolePicker, { onClose })) + await press('role-skip') + expect(state.prefs.get(ROLE_KEY)).toBe(SKIP) + expect(onClose).toHaveBeenCalledOnce() + expect(install).not.toHaveBeenCalled() + }) + + test('a role is kept on the account and shows its recommended skills, all ticked', async () => { + await mount(h(RolePicker, {})) + await act(async () => pick('marketing')!.click()) + expect(state.prefs.get(ROLE_KEY)).toBe('marketing') + expect(skills()).toEqual([...role('marketing')!.skills]) + const boxes = [...host.querySelectorAll('input[type="checkbox"]')] + expect(boxes.every((b) => b.checked)).toBe(true) + expect(host.querySelector('[data-slot="roles-add"]')?.textContent).toBe(`Add ${role('marketing')!.skills.length} skills`) + }) + + test('Something else offers the starting set', async () => { + await mount(h(RolePicker, {})) + await act(async () => pick('else')!.click()) + expect(skills()).toEqual([...role('else')!.skills]) + }) +}) + +describe('adding the set in one click', () => { + test('adds every ticked skill in one write, less the one unticked', async () => { + await mount(h(RolePicker, {})) + await act(async () => pick('education')!.click()) + const box = host.querySelector('input[aria-label="Video rooms"]')! + await act(async () => box.click()) + expect(box.checked).toBe(false) + const want = role('education')!.skills.filter((n) => n !== 'meet_session') + expect(host.querySelector('[data-slot="roles-add"]')?.textContent).toBe(`Add ${want.length} skills`) + await press('roles-add') + expect(install).toHaveBeenCalledOnce() + expect(install).toHaveBeenCalledWith(want) + expect(host.querySelector('[data-slot="roles-done"]')?.textContent).toContain(`Added ${want.length} skills`) + }) + + test('leaves out what the org has on already, and what the catalogue no longer lists', async () => { + const director = role('director')! + state.rows = director.skills + .filter((n) => n !== 'books_pnl') + .map((n) => ({ name: `skill_${n}`, description: `Read ${n}: Returns it, newest first. More.`, activated: n === 'task_projects' })) + await mount(h(RolePicker, {})) + await act(async () => pick('director')!.click()) + expect(skills()).toEqual(director.skills.filter((n) => n !== 'books_pnl')) + expect(host.querySelector('[data-skill="task_projects"]')?.textContent).toContain('Added') + expect(host.querySelector('[data-skill="team_docs"]')?.textContent).toContain('Returns it, newest first') + await press('roles-add') + expect(install).toHaveBeenCalledWith(director.skills.filter((n) => n !== 'books_pnl' && n !== 'task_projects')) + }) + + test('a tool plane that lists none of the catalogue (its skills app away) still offers the whole set', async () => { + state.rows = [{ name: 'skill_our-own', description: 'Ours: a skill the org wrote.', activated: true }] + await mount(h(RolePicker, {})) + await act(async () => pick('marketing')!.click()) + expect(skills()).toEqual([...role('marketing')!.skills]) + }) + + test('a member is told only an admin can add them, and cannot press Add', async () => { + state.role = 'member' + await mount(h(RolePicker, {})) + await act(async () => pick('marketing')!.click()) + expect(host.querySelector('[data-slot="roles-admin"]')).toBeTruthy() + expect(host.querySelector('[data-slot="roles-add"]')!.disabled).toBe(true) + }) + + test('a refusal is said, and nothing reads as added', async () => { + install.mockRejectedValueOnce(Object.assign(new Error('403'), { status: 403 })) + await mount(h(RolePicker, {})) + await act(async () => pick('creative')!.click()) + await press('roles-add') + expect(host.querySelector('[data-slot="roles-wrong"]')?.textContent).toContain('Only an organization admin can add skills') + expect(host.querySelector('[data-slot="roles-done"]')).toBeNull() + }) + + test('the catalogue’s words lose their API title and keep one sentence', () => { + expect(detail('Read marketing campaigns: Returns the org’s campaigns, newest first. Paged.')).toBe('Returns the org’s campaigns, newest first') + expect(detail('Read graph graphql: Read the graph’s GraphQL schema..')).toBe('Read the graph’s GraphQL schema') + expect(detail('No title here')).toBe('No title here') + }) +}) + +describe('the new customer’s card', () => { + test('asks an account made in the last two weeks that has not answered', async () => { + await mount(h(RoleCard, {})) + expect(host.querySelector('[data-slot="role-card"]')).toBeTruthy() + await press('role-card-choose') + expect(host.querySelector('[data-slot="dialog"] [data-slot="roles-pick"]')).toBeTruthy() + }) + + test('Skip puts it away for good', async () => { + await mount(h(RoleCard, {})) + await press('role-card-skip') + expect(state.prefs.get(ROLE_KEY)).toBe(SKIP) + await mount(h(RoleCard, { key: 'again' })) + expect(host.querySelector('[data-slot="role-card"]')).toBeNull() + }) + + test('asks nobody who answered, or an account older than two weeks, or one whose age is unknown', async () => { + state.prefs.set(ROLE_KEY, 'director') + await mount(h(RoleCard, {})) + expect(host.querySelector('[data-slot="role-card"]')).toBeNull() + + state.prefs.clear() + state.joined = '2025-01-01T00:00:00Z' + await mount(h(RoleCard, { key: 'old' })) + expect(host.querySelector('[data-slot="role-card"]')).toBeNull() + + state.joined = undefined + await mount(h(RoleCard, { key: 'unknown' })) + expect(host.querySelector('[data-slot="role-card"]')).toBeNull() + }) +}) diff --git a/pkg/app/src/RolePicker.tsx b/pkg/app/src/RolePicker.tsx new file mode 100644 index 0000000..6ab97ef --- /dev/null +++ b/pkg/app/src/RolePicker.tsx @@ -0,0 +1,390 @@ +'use client' + +// The role picker and its recommended skills (roles.ts, hanzo-inc/app issue 323). +// +// Three ways in, one picker: +// - `RoleCard`, the new customer's ask: drawn in the sidebar's column for an +// account made in the last two weeks that has not answered, in place of +// an interstitial (the owner retired /onboarding's page, 2026-10-29). +// - Customize's sidebar row "Skills for your role" (Sidebar.tsx). +// - Settings › General's row beside "Occupation or work role" (hanzo.app's +// own page, which renders `RoleDialog`). +// +// Choosing a role answers the question (kept on the account, `ROLE_KEY`); the +// skills are only added when the person presses Add, after unticking any they +// don't want. Adding is one activation for the org (connect.ts `install`), +// the write Customize makes, so an org admin's to make. + +import { useMemo, useState } from 'react' +import { useI18n } from '@hanzo/i18n/react' +import { useIam } from '@hanzo/iam/react' +import { Button, Checkbox, Dialog, DialogContent, DialogTitle, Text, XStack, YStack } from '@hanzo/ui' +import { Check, Sparkles } from 'lucide-react' +import { install } from './connect' +import { usePref } from './pref' +import { useSkills } from './tools' +import { useAccount } from './lib/account' +import { app } from './lib/host' +import { org, role as roleIn, superAdmin } from './lib/session' +import { site } from './where' +import { BAD } from './lib/mix' +import { ELSE, ROLE_KEY, ROLES, SKILLS, SKIP, answered, fresh, listed, nameOf, picked, recommended, role as roleOf, type Role } from './roles' + +/** Customize's skills tab, where every added skill can be read, switched off or more added. */ +const SKILLS_TAB = '-/customize/skills' +const FOCUS_RING = { outlineWidth: 2, outlineStyle: 'solid', outlineColor: 'var(--ring)' } as const + +/** The person's answer and the way to change it, shared by whoever draws the picker (usePref). */ +export type Answer = readonly [string, (next: string) => void] + +type Step = { at: 'pick' } | { at: 'list'; role: Role } | { at: 'done'; role: Role; added: number } + +/** The catalogue's own words for a skill, after its "Read …:" title: the detail line under its label. */ +export function detail(description: string): string { + const said = description.includes(':') ? description.slice(description.indexOf(':') + 1) : description + // The catalogue joins an operation's sentences with ".," and may end on "..". + const first = said.trim().replace(/\.+$/, '').split(/\.(?:\s|,)/)[0] ?? '' + return first.trim() +} + +/** Whether the reader may switch skills for the org in scope: an owner or admin there, or a SuperAdmin. Unknown is left to the server. */ +function mayAdd(): boolean { + if (superAdmin()) return true + const r = roleIn(org()) + return r === null || r === 'owner' || r === 'admin' +} + +/** + * The picker itself: roles first, then the chosen role's skills to untick and + * add in one click. `onClose` ends it (Skip, Not now, Done); `go` moves the app + * to Customize where the host reads paths, else the page loads there. + */ +export function RolePicker({ onClose, go, answer }: { onClose?: () => void; go?: (address: string) => void; answer?: Answer }) { + const { t } = useI18n() + // The card hands in its own copy of the answer, so it hides the moment one is given. + const own = usePref(ROLE_KEY, '') + const [saved, save] = answer ?? own + const [step, setStep] = useState({ at: 'pick' }) + const [off, setOff] = useState>(new Set()) + const [busy, setBusy] = useState(false) + const [wrong, setWrong] = useState(null) + // Skills switched on here, so the list reads them as on before the tool plane is read again. + const [lit, setLit] = useState>(new Set()) + const plane = useSkills() + + // What the tool plane lists, and which of it is on, by the skill's own name. + const { known, on, about } = useMemo(() => { + if (!plane.rows) return { known: null, on: lit, about: new Map() } + const known = new Set() + const on = new Set(lit) + const about = new Map() + for (const row of plane.rows) { + const name = nameOf(row.name) || row.name + known.add(name) + if (row.activated) on.add(name) + if (row.description) about.set(name, detail(row.description)) + } + // A plane that lists none of the map's skills has not read the brand's catalogue (its skills + // app was cold or away), which is no reason to offer nothing: it reads as not yet known. + const catalogue = recommended().some((n) => known.has(n)) + return { known: catalogue ? known : null, on, about } + }, [plane.rows, lit]) + + const may = mayAdd() + const choose = (r: Role) => { + save(r.id) + setOff(new Set()) + setWrong(null) + setStep({ at: 'list', role: r }) + } + const skip = () => { + if (!answered(saved)) save(SKIP) + onClose?.() + } + const customize = () => { + onClose?.() + if (go) go(app(SKILLS_TAB)) + else if (typeof window !== 'undefined') window.location.assign(site(app(SKILLS_TAB))) + } + + if (step.at === 'done') { + return ( + + + + + {step.added === 1 ? t('Added 1 skill') : t('Added {n} skills', { n: step.added })} + + + + {t('Every run in your organization can use them now. You can switch any of them off in Customize.')} + + + + + + + ) + } + + if (step.at === 'list') { + const r = step.role + const shown = listed(r, known) + const adding = picked(shown, off, on) + const allOn = shown.length > 0 && shown.every((n) => on.has(n)) + const toggle = (name: string, next: boolean) => + setOff((was) => { + const now = new Set(was) + if (next) now.delete(name) + else now.add(name) + return now + }) + const add = async () => { + if (!adding.length || busy) return + setBusy(true) + setWrong(null) + try { + await install(adding) + setLit((was) => new Set([...was, ...adding])) + setStep({ at: 'done', role: r, added: adding.length }) + } catch (e) { + const code = (e as { status?: unknown } | null)?.status + setWrong( + code === 403 + ? t('Only an organization admin can add skills. Ask one to add these, or find them in Customize.') + : t('The skills could not be added. Try again in a moment.'), + ) + } finally { + setBusy(false) + } + } + return ( + + + {t('Each skill lets Hanzo read that part of your organization’s work when a task needs it. Untick any you don’t want.')} + + {shown.length === 0 ? ( + + {t('None of these skills is offered to your organization right now. Browse every skill in Customize.')} + + ) : ( + + {shown.map((name) => { + const already = on.has(name) + const ticked = already || !off.has(name) + const id = `role-skill-${name}` + return ( + + toggle(name, next === true)} + aria-label={t(SKILLS[name] ?? name)} + /> + } cursor={already ? 'default' : 'pointer'}> + + {t(SKILLS[name] ?? name)} + + {about.get(name) ? ( + + {about.get(name)} + + ) : null} + + {already ? ( + + {t('Added')} + + ) : null} + + ) + })} + + )} + {!may ? ( + + {t('Only an organization admin can add skills. Ask one to add these, or find them in Customize.')} + + ) : null} + {wrong ? ( + + {wrong} + + ) : null} + + + + + {allOn ? ( + + ) : ( + + )} + + + + ) + } + + const current = roleOf(saved) + return ( + + + {t('Pick the one closest to your work and Hanzo recommends skills for it. You can change it any time in Settings.')} + + + {[...ROLES, ELSE].map((r) => { + const chosen = current?.id === r.id + return ( + choose(r)} + flexBasis="calc(50% - 4px)" + grow={1} + $max-sm={{ flexBasis: '100%' }} + minW={0} + minH={56} + gap="$0.5" + px="$3" + py="$2" + rounded="$4" + borderWidth={1} + borderColor={chosen ? 'var(--primary)' : '$borderColor'} + bg="$raised" + items="flex-start" + cursor="pointer" + hoverStyle={{ bg: '$hover' }} + focusVisibleStyle={FOCUS_RING} + > + + {t(r.label)} + + + {t(r.line)} + + + ) + })} + + + + + + ) +} + +/** The picker in a dialog: what the card, Customize's row and Settings open. */ +export function RoleDialog({ open, onOpenChange, go, answer }: { open: boolean; onOpenChange: (open: boolean) => void; go?: (address: string) => void; answer?: Answer }) { + const { t } = useI18n() + return ( + + + + + + + {t('Skills for your role')} + + + + {/* Mounted only while open, so each opening starts at the roles. */} + {open ? onOpenChange(false)} /> : null} + + + ) +} + +/** + * The new customer's ask, in the sidebar's column: shown to an account made in + * the last two weeks (`fresh`) until it picks a role or skips, on every machine + * (the answer is the account's). Nothing for anyone else. + */ +export function RoleCard({ go, mt }: { go?: (address: string) => void; mt?: '$2' }) { + const { t } = useI18n() + const { isAuthenticated, accessToken } = useIam() + const { user } = useAccount() + const [saved, save, ready] = usePref(ROLE_KEY, '') + const [open, setOpen] = useState(false) + + const signed = isAuthenticated && Boolean(accessToken) + if (!signed || !ready || !fresh(user?.joinedDate) || (answered(saved) && !open)) return null + + return ( + <> + + + + + {t('What do you do?')} + + + + {t('Pick your role and Hanzo recommends skills for it.')} + + + + + + + + + ) +} diff --git a/pkg/app/src/Sidebar.test.ts b/pkg/app/src/Sidebar.test.ts index 49d1fbb..33130ca 100644 --- a/pkg/app/src/Sidebar.test.ts +++ b/pkg/app/src/Sidebar.test.ts @@ -92,6 +92,8 @@ vi.mock('./Recents', () => ({ Recents: ({ mode, host }: { mode: string; host: { name?: string } }) => createElement('div', { 'data-slot': 'recents', 'data-mode': mode, 'data-host': host.name ?? '' }), })) vi.mock('./Setup', () => ({ Setup: () => createElement('div', { 'data-slot': 'setup-card' }) })) +// The role picker (issue 323) is its own test's; here it is where it is drawn. +vi.mock('./RolePicker', () => ({ RoleCard: () => createElement('div', { 'data-slot': 'role-card' }), RoleDialog: () => null })) vi.mock('./span', () => ({ useSpan: () => ({ ref: null, style: {}, span: 256, move: () => {}, keep: () => {} }) })) vi.mock('./lib/dev-mode', () => ({ useDevMode: () => [devState.on, () => {}], rememberSettingsReturn: () => {} })) @@ -233,11 +235,14 @@ describe('the unified desktop sidebar', () => { expect(simpleHtml).not.toContain('data-slot="setup-card"') expect(simpleHtml).toContain('data-slot="sidebar-account"') expect(simpleHtml).toContain('data-slot="me"') + // The role card asks a new customer in either mode (issue 323); it draws nothing for anyone else. + expect(simpleHtml).toContain('data-slot="role-card"') devState.on = true const devHtml = column('chat') expect(devHtml).not.toContain('data-slot="column-settings"') expect(devHtml).toContain('data-slot="setup-card"') + expect(at(devHtml, 'data-slot="role-card"')).toBeLessThan(at(devHtml, 'data-slot="setup-card"')) }) test('carries one fold button, Activity bell, Search, primary New action, Pinned products, Recents, the More row under it, and Account', () => { @@ -378,6 +383,8 @@ describe('the unified desktop sidebar', () => { expect(at(customize, '>Customize<')).toBeLessThan(at(customize, 'Agents')) expect(at(customize, 'Agents')).toBeLessThan(at(customize, 'Bots')) expect(at(customize, 'Bots')).toBeLessThan(at(customize, 'Skills')) + // Skills for your role (issue 323) follows Customize's own tabs. + expect(at(customize, 'Plugins')).toBeLessThan(at(customize, 'Skills for your role')) const library = column('dev', '-/artifacts') expect(at(library, '>Library<')).toBeLessThan(at(library, 'Upload')) expect(at(library, 'Upload')).toBeLessThan(at(library, 'Images')) diff --git a/pkg/app/src/Sidebar.tsx b/pkg/app/src/Sidebar.tsx index 68e639c..01c8f09 100644 --- a/pkg/app/src/Sidebar.tsx +++ b/pkg/app/src/Sidebar.tsx @@ -59,6 +59,7 @@ import { Recents } from './Recents' import { DEFAULT_NAV, fullNavUrl, raised, useNavEntries, type NavEntry, type Pins, type Raised } from './Rail' import { MoreMenu } from './MoreMenu' import { Setup } from './Setup' +import { RoleCard, RoleDialog } from './RolePicker' import { ago, PINNED, UNTITLED_RUN, type Recent } from './recent' import { empty } from './open' import { useSpan } from './span' @@ -931,6 +932,8 @@ export function Sidebar({ const account = !anon && typeof host.token === 'function' ? host : null const names = useDeviceNames(account) const [renaming, setRenaming] = useState(null) + // Customize's row "Skills for your role" opens the role picker (RolePicker.tsx, issue 323). + const [roles, setRoles] = useState(false) const tabsGroups = useTabsGroups(t, mode === 'tabs', devMode, names, setRenaming) const { open: betaOpen } = useBetas() const hostedGroups = useMemo(() => { @@ -959,7 +962,12 @@ export function Sidebar({ (mode === 'tabs' ? tabsGroups : at === 'customize' - ? tabs(host, dev, t) + ? [ + ...tabs(host, dev, t), + ...(anon + ? [] + : [{ id: 'roles', label: '', links: [{ id: 'roles', label: t('Skills for your role'), icon: , onPress: () => setRoles(true) }] }]), + ] : at === 'library' ? library(host, dev, t) : at === 'scheduled' @@ -1706,10 +1714,14 @@ export function Sidebar({ ) : at || mode === 'beta' || mode === 'hosted' ? null : devMode ? ( + ) : ( - + <> + + + )} @@ -1770,6 +1782,7 @@ export function Sidebar({ label={t('Resize sidebar')} /> )} + !o && setRenaming(null)} diff --git a/pkg/app/src/connect.test.ts b/pkg/app/src/connect.test.ts new file mode 100644 index 0000000..dbe67f1 --- /dev/null +++ b/pkg/app/src/connect.test.ts @@ -0,0 +1,34 @@ +import { afterEach, describe, expect, test, vi } from 'vitest' + +vi.mock('./lib/session', () => ({ bearer: () => 'token', scope: () => ({ Authorization: 'Bearer token', 'X-Org-Id': 'acme' }) })) +vi.mock('./lib/api', () => ({ api: () => 'https://api.example' })) + +const { install } = await import('./connect') + +afterEach(() => vi.unstubAllGlobals()) + +describe('install: a role’s skills in one write (hanzo-inc/app issue 323)', () => { + test('switches every named skill on in one PUT, as its tool, with the session and the org', async () => { + const fetch = vi.fn(async () => new Response(JSON.stringify({ enabled: ['skill_a_b', 'skill_c_d', 'cloud_get_ping'] }), { status: 200 })) + vi.stubGlobal('fetch', fetch) + await expect(install(['a_b', 'c_d'])).resolves.toEqual(['skill_a_b', 'skill_c_d', 'cloud_get_ping']) + expect(fetch).toHaveBeenCalledOnce() + const [url, init] = fetch.mock.calls[0] as unknown as [string, RequestInit] + expect(url).toBe('https://api.example/v1/tools/activation') + expect(init.method).toBe('PUT') + expect(init.headers).toMatchObject({ Authorization: 'Bearer token', 'X-Org-Id': 'acme' }) + expect(JSON.parse(String(init.body))).toEqual({ activate: ['skill_a_b', 'skill_c_d'] }) + }) + + test('asks nothing when nothing is ticked', async () => { + const fetch = vi.fn() + vi.stubGlobal('fetch', fetch) + await expect(install([])).resolves.toEqual([]) + expect(fetch).not.toHaveBeenCalled() + }) + + test('a refusal carries its status, for the picker to say who may add skills', async () => { + vi.stubGlobal('fetch', vi.fn(async () => new Response('{}', { status: 403 }))) + await expect(install(['a_b'])).rejects.toMatchObject({ status: 403 }) + }) +}) diff --git a/pkg/app/src/connect.ts b/pkg/app/src/connect.ts index 96fe454..c548b37 100644 --- a/pkg/app/src/connect.ts +++ b/pkg/app/src/connect.ts @@ -52,6 +52,20 @@ export async function activate(name: string, on: boolean): Promise { return done.enabled ?? [] } +/** + * Switches several skills on at once, by their catalogue names (`marketing_campaigns`), + * and answers with the whole resulting set: the same write as {@link activate}, + * in one request, so a role's set is added in one click (roles.ts). The handler + * checks every name, and the caller's right to switch them, before it switches + * any: switching a skill takes an admin of the org, and a member is refused 403 + * with nothing switched, which the caller says in words. + */ +export async function install(names: readonly string[]): Promise { + if (!names.length) return [] + const done = await ask<{ enabled?: string[] }>('/v1/tools/activation', { activate: names.map((n) => `skill_${n}`) }) + return done.enabled ?? [] +} + /** What a device sign-in needs from the reader. */ export interface Device { /** The short code they type at {@link Device.verifyUrl}. */ diff --git a/pkg/app/src/roles.test.ts b/pkg/app/src/roles.test.ts new file mode 100644 index 0000000..4415aa3 --- /dev/null +++ b/pkg/app/src/roles.test.ts @@ -0,0 +1,95 @@ +import { describe, expect, test } from 'vitest' +import { ELSE, NEW_FOR, ROLES, SKILLS, SKIP, answered, fresh, listed, nameOf, picked, recommended, role, tool } from './roles' + +// The catalogue's name rule (cloud apps/tools NAME, @hanzo/build api/skills NAME). +const NAME = /^[a-z0-9][a-z0-9_-]{0,63}$/ + +describe('the role → skills map (hanzo-inc/app issue 323)', () => { + test('offers Director, Marketing and Education among its roles, then Something else', () => { + const ids = ROLES.map((r) => r.id) + expect(ids).toEqual(expect.arrayContaining(['director', 'marketing', 'education'])) + expect(new Set([...ids, ELSE.id]).size).toBe(ids.length + 1) + expect(ids).not.toContain(SKIP) + expect(ELSE.label).toBe('Something else') + }) + + test('every role recommends a handful of skills, each named once, each with a label', () => { + for (const r of [...ROLES, ELSE]) { + expect(r.label, r.id).toBeTruthy() + expect(r.line, r.id).toBeTruthy() + expect(r.skills.length, r.id).toBeGreaterThanOrEqual(4) + expect(r.skills.length, r.id).toBeLessThanOrEqual(10) + expect(new Set(r.skills).size, r.id).toBe(r.skills.length) + for (const n of r.skills) expect(SKILLS[n], `${r.id}: ${n}`).toBeTruthy() + } + }) + + test('names catalogue skills: a service and a thing, by the catalogue’s own rule, never a built-in or the + shelf’s list', () => { + for (const n of recommended()) { + expect(n).toMatch(NAME) + expect(n, n).toMatch(/^[a-z0-9]+_[a-z0-9_]+$/) + } + // Every label is for a skill a role recommends: no orphans to keep in step. + expect(Object.keys(SKILLS).sort()).toEqual(recommended().sort()) + }) + + test('reads an answer back: a role, Something else, Skip, or none', () => { + expect(role('marketing')?.id).toBe('marketing') + expect(role('else')).toBe(ELSE) + expect(role(SKIP)).toBeNull() + expect(role('')).toBeNull() + expect(role('astronaut')).toBeNull() + expect(role(undefined)).toBeNull() + expect(answered('director')).toBe(true) + expect(answered('else')).toBe(true) + expect(answered(SKIP)).toBe(true) + expect(answered('')).toBe(false) + expect(answered('retired-role')).toBe(false) + }) + + test('a skill is switched on by its tool, skill_', () => { + expect(tool('marketing_campaigns')).toBe('skill_marketing_campaigns') + expect(nameOf('skill_marketing_campaigns')).toBe('marketing_campaigns') + expect(nameOf('cloud_get_ping')).toBe('') + }) +}) + +describe('what one click adds', () => { + const marketing = role('marketing')! + + test('lists every recommended skill until the tool plane answers, then only the ones it lists', () => { + expect(listed(marketing, null)).toEqual([...marketing.skills]) + const plane = new Set(marketing.skills.filter((n) => n !== 'email_stats')) + expect(listed(marketing, plane)).toEqual(marketing.skills.filter((n) => n !== 'email_stats')) + expect(listed(marketing, new Set())).toEqual([]) + }) + + test('adds what is shown, less what the person unticked and what is already on', () => { + const shown = listed(marketing, null) + expect(picked(shown, new Set())).toEqual(shown) + expect(picked(shown, new Set(['social_posts', 'ad_summary']))).toEqual(shown.filter((n) => n !== 'social_posts')) + expect(picked(shown, new Set(['social_posts']), new Set(['marketing_campaigns']))).toEqual( + shown.filter((n) => n !== 'social_posts' && n !== 'marketing_campaigns'), + ) + expect(picked(shown, new Set(shown))).toEqual([]) + }) +}) + +describe('who the card asks', () => { + const now = Date.parse('2026-11-21T00:00:00Z') + + test('an account made in the last two weeks', () => { + expect(fresh('2026-11-20T23:00:00Z', now)).toBe(true) + expect(fresh(new Date(now - NEW_FOR + 60_000).toISOString(), now)).toBe(true) + // A clock a little ahead of IAM's still reads a new account as new. + expect(fresh('2026-11-21T00:02:00Z', now)).toBe(true) + }) + + test('never an older account, or one whose age is unknown', () => { + expect(fresh(new Date(now - NEW_FOR - 60_000).toISOString(), now)).toBe(false) + expect(fresh('2025-01-01T00:00:00Z', now)).toBe(false) + expect(fresh(undefined, now)).toBe(false) + expect(fresh('', now)).toBe(false) + expect(fresh('not a date', now)).toBe(false) + }) +}) diff --git a/pkg/app/src/roles.ts b/pkg/app/src/roles.ts new file mode 100644 index 0000000..093a0fa --- /dev/null +++ b/pkg/app/src/roles.ts @@ -0,0 +1,201 @@ +// SKILLS FOR A PERSON'S ROLE (hanzo-inc/app issue 323). +// +// A new customer says what they do (Director, Marketing, Education, …, or +// Something else, or skips), and Hanzo recommends a set of skills for that +// role. They untick any they don't want and add the rest in one click. +// +// THIS FILE IS THE ONE MAP. Each role's skills are names in the brand's +// catalogue (`GET /.well-known/agent-skills/index.json`, cloud +// apps/skills/catalog/hanzo), the skills Customize's Browse offers. Adding one +// switches on its tool `skill_` for the org (`install` in connect.ts), +// the same write Customize and the `+` menu make. A name the catalogue stops +// carrying is left off the list where the tool plane is read (`listed`), so a +// stale entry here never offers a skill that cannot be added. To change a +// recommendation, edit the lists below; `SKILLS` gives each name the short +// label it is drawn with. +// +// The answer is the person's own, kept on their account (`ROLE_KEY` through +// usePref, `GET/PATCH /v1/pref`), so the card stops asking on every machine. + +import { phrase } from '@hanzo/i18n' + +/** Where the person's answer is kept: a role's id, `SKIP`, or '' while unanswered. */ +export const ROLE_KEY = 'hanzo.onboarding.role' + +/** The answer of a person who said no thanks. */ +export const SKIP = 'skip' + +/** How long an account counts as new, so the card asks it once and never an account that has been here for months. */ +export const NEW_FOR = 14 * 24 * 60 * 60 * 1000 + +export interface Role { + id: string + /** Its name, marked for translation (`phrase`): drawn through `t`. */ + label: string + /** One line under the name: what someone in this role does. */ + line: string + /** The catalogue skills recommended for it, in the order they are listed. */ + skills: readonly string[] +} + +/** Each recommended skill's label, in words a person reads: the catalogue's own names are API names (`marketing_campaigns`). */ +export const SKILLS: Readonly> = { + // Running a team or a company + task_projects: phrase('Work boards'), + task_issues: phrase('Issues across projects'), + team_docs: phrase('Team documents'), + guide_analytics: phrase('Growth funnel and advice'), + guide_guide: phrase('Launch journey'), + guide_suggest: phrase('Next steps for your business'), + books_metrics: phrase('Revenue metrics'), + books_pnl: phrase('Profit and loss'), + company_company: phrase('Company formation'), + captable_summary: phrase('Cap table'), + legal_documents: phrase('Legal documents'), + esign_documents: phrase('Documents to sign'), + // Marketing + marketing_campaigns: phrase('Marketing campaigns'), + marketing_audiences: phrase('Audiences'), + marketing_calendar: phrase('Marketing calendar'), + marketing_lists: phrase('Contact lists'), + campaign_metrics: phrase('Campaign results'), + content_board: phrase('Content queue'), + social_posts: phrase('Social posts'), + post_analytics: phrase('Post engagement'), + email_stats: phrase('Email results'), + email_email: phrase('Sent email'), + // Teaching, research and knowledge + knowledge_files: phrase('Your files and notes'), + knowledge_graph: phrase('Knowledge map'), + research_projects: phrase('Research projects'), + research_papers: phrase('Papers'), + research_experiments: phrase('Experiments'), + dataset_dataset: phrase('Datasets'), + form_forms: phrase('Forms and quizzes'), + meet_session: phrase('Video rooms'), + websearch_search: phrase('Web search'), + library_library: phrase('Library'), + // Design and video + studio_brands: phrase('Brand kits'), + studio_documents: phrase('Documents and decks'), + studio_templates: phrase('Design templates'), + studio_flows: phrase('Creative flows'), + studio_runs: phrase('Renders'), + videos_videos: phrase('Video jobs'), + // Building software + project_project: phrase('Projects and sites'), + project_deployments: phrase('Deploys'), + git_repos: phrase('Repositories'), + git_runs: phrase('Build runs'), + code_search: phrase('Code search'), + sandbox_sandbox: phrase('Sandboxes'), + metrics_logs: phrase('Logs'), + // Selling and support + tel_calls: phrase('Calls'), + tel_messages: phrase('Text messages'), + commerce_product: phrase('Products'), + help_articles: phrase('Help center articles'), +} + +/** The roles offered, in the order they are drawn. */ +export const ROLES: readonly Role[] = [ + { + id: 'director', + label: phrase('Director'), + line: phrase('Lead a team, a department or a company'), + skills: ['task_projects', 'task_issues', 'team_docs', 'guide_analytics', 'books_metrics', 'books_pnl'], + }, + { + id: 'marketing', + label: phrase('Marketing'), + line: phrase('Campaigns, content, social and email'), + skills: ['marketing_campaigns', 'marketing_audiences', 'marketing_calendar', 'campaign_metrics', 'content_board', 'social_posts', 'post_analytics', 'email_stats'], + }, + { + id: 'education', + label: phrase('Education'), + line: phrase('Teach, train or study'), + skills: ['knowledge_files', 'knowledge_graph', 'research_papers', 'studio_documents', 'form_forms', 'meet_session', 'websearch_search'], + }, + { + id: 'creative', + label: phrase('Creative'), + line: phrase('Design, video and brand'), + skills: ['studio_brands', 'studio_documents', 'studio_templates', 'studio_flows', 'studio_runs', 'videos_videos', 'library_library'], + }, + { + id: 'founder', + label: phrase('Founder'), + line: phrase('Start, fund and run a company'), + skills: ['company_company', 'guide_guide', 'guide_suggest', 'captable_summary', 'books_pnl', 'legal_documents', 'esign_documents'], + }, + { + id: 'developer', + label: phrase('Developer'), + line: phrase('Build and ship software'), + skills: ['project_project', 'project_deployments', 'git_repos', 'git_runs', 'code_search', 'sandbox_sandbox', 'metrics_logs'], + }, + { + id: 'sales', + label: phrase('Sales and support'), + line: phrase('Customers, orders, calls and email'), + skills: ['marketing_lists', 'email_email', 'tel_calls', 'tel_messages', 'commerce_product', 'help_articles'], + }, + { + id: 'research', + label: phrase('Research and data'), + line: phrase('Studies, datasets and sources'), + skills: ['research_projects', 'research_papers', 'research_experiments', 'dataset_dataset', 'knowledge_files', 'websearch_search'], + }, +] + +/** "Something else": a starting set that suits most work, for a role not listed. */ +export const ELSE: Role = { + id: 'else', + label: phrase('Something else'), + line: phrase('A starting set for any kind of work'), + skills: ['websearch_search', 'library_library', 'knowledge_files', 'task_projects', 'team_docs'], +} + +/** A role by its id, `ELSE` included; null for `SKIP`, '' or an id no longer offered. */ +export function role(id: unknown): Role | null { + if (typeof id !== 'string' || !id) return null + if (id === ELSE.id) return ELSE + return ROLES.find((r) => r.id === id) ?? null +} + +/** Whether the person has answered (a role, Something else, or Skip). */ +export const answered = (value: unknown): boolean => value === SKIP || role(value) !== null + +/** The tool a skill is switched on by. */ +export const tool = (name: string): string => `skill_${name}` + +/** The skill a tool name switches, or '' when it is not a skill's. */ +export const nameOf = (tool: string): string => (tool.startsWith('skill_') ? tool.slice('skill_'.length) : '') + +/** + * `r`'s skills the org can add: all of them until the tool plane has answered + * (`plane` null), then only the ones it lists. A skill the catalogue no longer + * carries is left out rather than offered and refused. + */ +export function listed(r: Role, plane: ReadonlySet | null): string[] { + return plane ? r.skills.filter((n) => plane.has(n)) : [...r.skills] +} + +/** + * What one click adds: the skills shown (`shown`), less the ones the person + * unticked (`off`) and the ones already on for the org (`on`). Empty when + * nothing is left to add. + */ +export function picked(shown: readonly string[], off: ReadonlySet, on: ReadonlySet = new Set()): string[] { + return shown.filter((n) => !off.has(n) && !on.has(n)) +} + +/** Whether an account made at `joined` (IAM's createdTime) is new enough to be asked, at `now`. Unknown is not new; a time a skewed clock puts ahead is. */ +export function fresh(joined: string | undefined, now: number = Date.now()): boolean { + const at = joined ? Date.parse(joined) : Number.NaN + return Number.isFinite(at) && now - at <= NEW_FOR +} + +/** Every skill name the map recommends, once: what a check against the catalogue reads. */ +export const recommended = (): string[] => [...new Set([...ROLES, ELSE].flatMap((r) => r.skills))]