diff --git a/package.json b/package.json index cee2051..0bb4565 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@hanzo/build", - "version": "0.2.126", + "version": "0.2.127", "type": "module", "license": "Apache-2.0 OR MIT", "description": "Hanzo Build — say what you want, watch it built, deployed and running. The builder as a component, mounted by the Hanzo app at hanzo.ai.", @@ -68,6 +68,16 @@ "import": "./lib/mind.js", "default": "./lib/mind.js" }, + "./handoff": { + "types": "./lib/handoff.d.ts", + "import": "./lib/handoff.js", + "default": "./lib/handoff.js" + }, + "./dev-mode": { + "types": "./lib/dev-mode.d.ts", + "import": "./lib/dev-mode.js", + "default": "./lib/dev-mode.js" + }, "./package.json": "./package.json" }, "files": [ diff --git a/src/api/devices.test.ts b/src/api/devices.test.ts new file mode 100644 index 0000000..32c3177 --- /dev/null +++ b/src/api/devices.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from 'vitest' + +import { displayMachine, machine } from './machines.ts' +import { displayPlace, SANDBOX } from './places.ts' + +describe('device names a person reads', () => { + it('keeps a laptop\u2019s own name in Simple mode, with its hardware as the detail', () => { + const m = machine({ + id: 'tgt_1', + label: 'MacBook-Pro.local', + kind: 'laptop', + host: 'MacBook-Pro.local', + status: 'online', + metricsAt: '2026-10-04T06:00:00Z', + spec: { os: 'darwin', arch: 'arm64', cpus: 16, memory: 64 * 1024 * 1024 * 1024, gpus: [{ model: 'Apple M2' }] }, + }) + expect(displayMachine(m, { devMode: false })).toEqual({ title: 'MacBook-Pro', detail: 'Apple M2 · 64 GB · MacBook-Pro.local' }) + expect(displayMachine(m, { devMode: true }).title).toBe('MacBook-Pro.local') + }) + + it('names the cloud workspace Auto (Cloud), or Cloud for a developer', () => { + expect(displayPlace(SANDBOX, { devMode: false })).toEqual({ + title: 'Auto (Cloud)', + detail: 'Runs automatically in your Hanzo cloud workspace', + }) + expect(displayPlace(SANDBOX, { devMode: true }).title).toBe('Cloud') + }) +}) diff --git a/src/api/machines.ts b/src/api/machines.ts index a7ab5a7..0aa1a1f 100644 --- a/src/api/machines.ts +++ b/src/api/machines.ts @@ -14,7 +14,9 @@ * hostname and keeps it online while it runs. */ import { phrase } from '@hanzo/i18n' +import type { Say } from '@hanzo/i18n/react' +import { formatDeviceLabel } from '../dev-mode.ts' import { call, Refusal, seg, type Target } from './call.ts' export const KINDS = ['laptop', 'gpu', 'cloud', 'cluster', 'machine'] as const @@ -119,17 +121,29 @@ export function formatRelative(isoDate?: string): string { export function specSummary(m: Machine): string { if (m.spec) { const parts: string[] = [] - if (m.spec.cpus) parts.push(`${m.spec.cpus} vCPU`) - if (m.spec.memory) parts.push(formatBytes(m.spec.memory)) if (m.spec.gpus && m.spec.gpus.length > 0) { - const g = m.spec.gpus[0] - parts.push(`${m.spec.gpus.length}× ${g.model || g.vendor || 'GPU'}${g.memory ? ` (${formatBytes(g.memory)})` : ''}`) + const g = m.spec.gpus[0]! + const gpuLabel = g.model || g.vendor || 'GPU' + parts.push(m.spec.gpus.length > 1 ? `${m.spec.gpus.length}× ${gpuLabel}` : gpuLabel) + } else if (m.spec.cpus) { + parts.push(`${m.spec.cpus} vCPU`) } + if (m.spec.memory) parts.push(formatBytes(m.spec.memory)) if (parts.length > 0) return parts.join(' · ') } return m.capacity || '' } +function hardwareSummary(m: Machine): string { + const hw = specSummary(m) + const host = m.host && m.host !== hw ? m.host : '' + return [hw, host].filter(Boolean).join(' · ') +} + +export function displayMachine(m: Machine, opts?: { devMode?: boolean; say?: Say }): { title: string; detail?: string } { + return formatDeviceLabel(m.label, { hardware: hardwareSummary(m), host: m.host, devMode: opts?.devMode, say: opts?.say }) +} + export function machine(raw: unknown): Machine { const o = (raw && typeof raw === 'object' ? raw : {}) as Record const specObj = obj(o.spec) diff --git a/src/api/places.ts b/src/api/places.ts index dc9e0da..7b1fdcf 100644 --- a/src/api/places.ts +++ b/src/api/places.ts @@ -1,30 +1,34 @@ /** - * Where a run can run: the platform's sandbox, or one of the org's machines. + * Where a run can run: the platform's cloud workspace, or one of the org's machines. * * GET /v1/agent/targets → {targets: [...]}, newest first (machines.ts) * - * The sandbox is not a row the platform lists — it is what a run gets when it + * The cloud workspace is not a row the platform lists — it is what a run gets when it * names no target — so it is the first place here and carries no id. A machine * can take a run only while it is online. */ import { phrase } from '@hanzo/i18n' +import type { Say } from '@hanzo/i18n/react' + +import { formatDeviceLabel } from '../dev-mode.ts' +import { english } from '../say.ts' import type { Target } from './call.ts' import { machines, state } from './machines.ts' export interface Place { - /** `tgt_…`, or '' for the sandbox. */ + /** `tgt_…`, or '' for the cloud workspace. */ id: string label: string - /** laptop | gpu | cloud | … as the platform names it; 'sandbox' for the sandbox. */ + /** laptop | gpu | cloud | … as the platform names it; 'sandbox' for the cloud workspace. */ kind: string - /** online | offline | draining | not seen yet, as machines.ts `state` reads it; the sandbox is always online. */ + /** online | offline | draining | not seen yet, as machines.ts `state` reads it; the cloud workspace is always online. */ status: string /** "10 vCPU / 122G / 1× GB10", when the machine reported one. */ capacity: string } -/** The sandbox, named in English and marked (`phrase`): a screen draws its label through `t`. */ +/** The cloud workspace, named in English and marked (`phrase`): a screen draws its label through `t`. */ export const SANDBOX: Place = { id: '', label: phrase('Hanzo sandbox'), kind: 'sandbox', status: 'online', capacity: '' } export async function places(t: Target): Promise { @@ -32,5 +36,11 @@ export async function places(t: Target): Promise { return [SANDBOX, ...list.map((m) => ({ id: m.id, label: m.label, kind: m.kind, status: state(m), capacity: m.capacity }))] } +export function displayPlace(p: Place, opts?: { devMode?: boolean; say?: Say }): { title: string; detail?: string } { + const say = opts?.say ?? english + if (!p.id) return opts?.devMode ? { title: 'Cloud' } : { title: say('Auto (Cloud)'), detail: say('Runs automatically in your Hanzo cloud workspace') } + return formatDeviceLabel(p.label, { hardware: p.capacity, devMode: opts?.devMode, say }) +} + /** Whether a run sent here now would be taken. */ export const ready = (p: Place): boolean => p.status === 'online' diff --git a/src/automations.tsx b/src/automations.tsx index 1f3c5ae..65f8e8d 100644 --- a/src/automations.tsx +++ b/src/automations.tsx @@ -14,17 +14,18 @@ * instructions, a run's summary and post and the platform's refusals are drawn * as given. */ -import { SizableText, XStack, YStack } from '@hanzo/gui' -import { ChevronLeft } from '@hanzogui/lucide-icons-2' +import { SizableText, useMedia, XStack, YStack } from '@hanzo/gui' +import { ChevronDown, ChevronLeft, ChevronRight, ExternalLink, Play, RotateCcw, SlidersHorizontal, Trash2 } from '@hanzogui/lucide-icons-2' import { phrase } from '@hanzo/i18n' import { useI18n } from '@hanzo/i18n/react' -import { Button, Input, Switch, Textarea } from '@hanzo/ui' +import { Button, Input, Skeleton, Switch, Textarea, toast } from '@hanzo/ui' import { StatusDot, type SessionStatus } from '@hanzo/ui/chat' import { ModelPicker } from '@hanzo/ui/models' import { ChipSelect } from '@hanzo/ui/product' import { useLimits } from '@hanzo/ui/product/useLimits' import { useEffect, useMemo, useRef, useState } from 'react' +import { RING, RING_INSET } from './pane.ts' import { automation, changes, create, remove, review, runs, save, start, starters, words, type Automation, type Draft, type Kind, type Run, type Schedule, type Starter } from './api/auto.ts' import { current, subscriptions, type Subscription } from './api/billing.ts' import { SOCIAL } from './api/provider.ts' @@ -32,7 +33,7 @@ import { Out } from './out.tsx' import { useSocial } from './settings/integrations.tsx' import { Refusal, told } from './api/call.ts' import { ENSO, limits as readLimits, models } from './api/models.ts' -import { Choice, Confirm, Field, Line, Sheet } from './customize/ui.tsx' +import { Choice, Confirm, Field, Sheet } from './customize/ui.tsx' import { useRead } from './data.ts' import { useHost, useTarget } from './host.tsx' import { SOURCE } from './api/library.ts' @@ -219,6 +220,7 @@ export function Editor({ id }: { id: string }) { const host = useHost() const { t } = useI18n() const target = useTarget() + const desktop = Boolean(useMedia().sm) const signed = Boolean(host.person) const fresh = id === 'new' // `tick` reads the automation again; `beat` reads its runs again. @@ -234,10 +236,14 @@ export function Editor({ id }: { id: string }) { const [ready, setReady] = useState(fresh) const [busy, setBusy] = useState('') const [note, setNote] = useState('') + const [noteError, setNoteError] = useState(false) const [asking, setAsking] = useState(false) // Where a move away from unsaved work was headed, while it asks first; '' for nowhere. const [leaving, setLeaving] = useState('') const [upgrade, setUpgrade] = useState(false) + const [moreStarters, setMoreStarters] = useState(false) + const [optionsOpen, setOptionsOpen] = useState(null) + const [allRuns, setAllRuns] = useState(false) const social = useSocial(signed, SOCIAL.filter((p) => p.posts).map((p) => p.id)) const subs = useRead(signed ? () => subscriptions(target) : null, [] as Subscription[], [target, signed]) // Free is what the platform says when it names no live subscription; a read that failed says nothing. @@ -285,6 +291,7 @@ export function Editor({ id }: { id: string }) { // An edit answers what the last line asked for, so the line goes with it. const set = (p: Partial) => { setNote('') + setNoteError(false) setUpgrade(false) setD((x) => ({ ...x, ...p })) } @@ -299,6 +306,7 @@ export function Editor({ id }: { id: string }) { const act = async (what: string, work: () => Promise) => { setBusy(what) setNote('') + setNoteError(false) setUpgrade(false) try { await work() @@ -306,6 +314,7 @@ export function Editor({ id }: { id: string }) { // Wanting a plan is said in these words only where a run was asked for. const run = what === 'run' && unplanned(e) setNote(run ? t(PLAN) : told(e, t)) + setNoteError(true) setUpgrade(run) } finally { setBusy('') @@ -317,11 +326,13 @@ export function Editor({ id }: { id: string }) { const ask = !d.name.trim() ? ([t('Name it first.'), nameRef] as const) : !d.instructions.trim() ? ([t('Add instructions first.'), asksRef] as const) : null if (ask) { setNote(ask[0]) + setNoteError(true) ask[1].current?.focus() return false } if (wrong) { setNote(wrong) + setNoteError(true) return false } return true @@ -343,6 +354,7 @@ export function Editor({ id }: { id: string }) { setBase(drafted(now)) setD((cur) => rebase(cur, snap, drafted(now))) setTick((n) => n + 1) + setNoteError(false) setNote(t('Saved.')) }) @@ -351,6 +363,7 @@ export function Editor({ id }: { id: string }) { void act('switch', async () => { await save(target, id, { enabled: on }) setTick((n) => n + 1) + toast.success(on ? t('Automation turned on') : t('Automation paused')) }) } @@ -358,7 +371,12 @@ export function Editor({ id }: { id: string }) { act('run', async () => { const run = await start(target, id) setBeat((n) => n + 1) - if (run.status === 'skipped') setNote(t('Not started: the previous run is still going.')) + if (run.status === 'skipped') { + setNote(t('Not started: the previous run is still going.')) + setNoteError(true) + } else { + toast.success(t('Run started')) + } }) const leave = (how?: { replace?: boolean }) => host.go(path({ kind: 'screen', screen: 'automations' }), how) @@ -382,8 +400,8 @@ export function Editor({ id }: { id: string }) { } if (!signed) return leave()} says={t("Sign in to see this organization's automations.")} /> - if (!fresh && saved.error && !a) return leave()} says={told(saved.error, t)} /> - if (!ready) return leave()} says={t('Reading the automation…')} /> + if (!fresh && saved.error && !a) return leave()} says={told(saved.error, t)} error onRetry={() => setTick((n) => n + 1)} /> + if (!ready) return leave()} says={t('Reading the automation…')} loading /> const s = d.schedule // An automation that posts speaks for the organization: only an admin changes it. @@ -394,56 +412,85 @@ export function Editor({ id }: { id: string }) { const says = switchesAlone ? (on ? t('On') : t('Off')) : !can ? t('Add instructions first') : on ? t('On when saved') : t('Off when saved') const state = fresh ? t('Not created yet') : dirty ? t('Unsaved changes') : '' const sayId = `${id}-switch` + const starterCap = 4 + const starterOverflow = offered.value.length > starterCap + const visibleStarters = !moreStarters && starterOverflow ? offered.value.slice(0, starterCap) : offered.value + const showOptions = optionsOpen ?? (desktop || Boolean(d.postTo.length)) + const modelLabel = d.model ? (catalog.value.find((m) => m.id === d.model)?.name ?? d.model) : 'Enso' + const permLabel = d.permissions === 'auto' ? t('Act on its own') : t('Ask first') + const optionsSummary = [ + modelLabel, + permLabel, + d.postTo.length ? t('Posts to {n}', { n: d.postTo.length }) : '', + d.notify ? t('Email on') : '', + ] + .filter(Boolean) + .join(' · ') + const runsCap = 8 + const runsOverflow = history.value.length > runsCap + const visibleHistory = !allRuns && runsOverflow ? history.value.slice(0, runsCap) : history.value + return ( - - - - - {state} - - + + - - {says} - - - - {a && !a.draft ? ( - - ) : null} - {a && dirty ? ( - + ) : null} + {a && dirty ? ( + + ) : null} + - ) : null} - + {note ? ( - - {note} + + + {note} + {upgrade ? ( ))} + {starterOverflow ? ( + setMoreStarters((v) => !v)} + px="$2.5" + py="$1" + minH={32} + items="center" + focusVisibleStyle={RING} + > + + {moreStarters ? t('Show less') : t('+{n} more', { n: offered.value.length - visibleStarters.length })} + + + ) : null} ) : null} @@ -526,175 +589,270 @@ export function Editor({ id }: { id: string }) { set({ schedule: next })} disabled={locked} /> - - - set({ model: id === ENSO ? null : id })} - loading={catalog.loading} - error={catalog.error ? told(catalog.error, t) : null} - /> + + + setOptionsOpen(!showOptions)} + items="center" + gap="$2.5" + px="$4" + py="$3" + minH={44} + width="100%" + $platform-web={{ textAlign: 'start' }} + focusVisibleStyle={RING_INSET} + > + + + + {t('Options & delivery')} + + + {optionsSummary} + + + {showOptions ? : } - - - ({ ...p, label: t(p.label) }))} onChange={(p) => set({ permissions: p })} /> - - - - {SOCIAL.filter((p) => p.posts).map((p, i) => { - const c = social.value[p.id] - const on = d.postTo.includes(p.id) - return ( - - - - {p.name} - - - {social.error - ? told(social.error, t) - : !c - ? t('Reading…') - : c.connected - ? c.account - ? t('Connected as {account}', { account: c.account }) - : t('Connected') - : `${c.available ? t('Not connected: an org admin connects it in Settings → Integrations.') : t(p.needs)} ${ - on || d.permissions === 'ask' - ? t('Runs hold the post for you to read; posting it fails until it is connected.') - : t('Acting on its own, it posts only to a connected account.') - }`} - - - set({ postTo: v ? [...d.postTo, p.id].sort() : d.postTo.filter((x) => x !== p.id) })} - aria-label={t('Post to {name}', { name: p.name })} - /> + {showOptions ? ( + + + + + + set({ model: id === ENSO ? null : id })} + loading={catalog.loading} + error={catalog.error ? told(catalog.error, t) : null} + /> + + + + + + ({ ...p, label: t(p.label) }))} onChange={(p) => set({ permissions: p })} /> + + + + + + + {SOCIAL.filter((p) => p.posts).map((p, i) => { + const c = social.value[p.id] + const on = d.postTo.includes(p.id) + return ( + + + + {p.name} + + + {social.error + ? told(social.error, t) + : !c + ? t('Reading…') + : c.connected + ? c.account + ? t('Connected as {account}', { account: c.account }) + : t('Connected') + : `${c.available ? t('Not connected: an org admin connects it in Settings → Integrations.') : t(p.needs)} ${ + on || d.permissions === 'ask' + ? t('Runs hold the post for you to read; posting it fails until it is connected.') + : t('Acting on its own, it posts only to a connected account.') + }`} + + + set({ postTo: v ? [...d.postTo, p.id].sort() : d.postTo.filter((x) => x !== p.id) })} + aria-label={t('Post to {name}', { name: p.name })} + /> + + ) + })} + + + - ) - })} - - - - - - - - - {t('Email me when a run ends')} - - - {t('One line on how it went, with a link to the run.')} - - - set({ notify: v })} aria-label={t('Email me when a run ends')} /> - + + + + + + {t('Email me when a run ends')} + + + {t('One line on how it went, with a link to the run.')} + + + set({ notify: v })} aria-label={t('Email me when a run ends')} /> + + + ) : null} + - {dirty && wrong && note !== wrong ? {wrong} : null} + {dirty && wrong && note !== wrong ? ( + + {wrong} + + ) : null} {a ? ( - - ) : null} {a ? ( - - + + {t('Runs')} {history.error && !history.value.length ? ( - {told(history.error, t)} + + + {told(history.error, t)} + + + + ) : history.loading && !history.value.length ? ( + + + {t('Reading its runs…')} + + + {[0, 1, 2].map((i) => ( + + + + + + + + ))} + + ) : !history.value.length ? ( - - {history.loading ? t('Reading its runs…') : a.draft ? t('It runs once its instructions are saved.') : t('No runs yet. Run now starts one.')} - + + + {a.draft ? t('It runs once its instructions are saved.') : t('No runs yet. Run now starts one.')} + + ) : ( - - {history.value.map((r, i) => ( - - - - - - - {`${WORD[r.status] ? t(WORD[r.status]) : r.status} · ${local(r.at)}`} - - - {r.summary || (live(r.status) ? t('Working…') : '')} - - {r.draft ? ( - - - {r.draft} - - - ) : null} - {r.outputs.length ? : null} - {r.posts.map((x) => ( - - - {NAME[x.to] ?? x.to} - - {x.url ? ( - - - {t('Posted · open')} - - - ) : ( - - {x.error} - - )} - - ))} - {r.status === 'review' && host.admin && !answered.has(r.id) ? ( - - - - - ) : r.status === 'review' && !host.admin ? ( - - {t('An org admin posts or discards it.')} + + + {visibleHistory.map((r, i) => ( + + + + + + + {`${WORD[r.status] ? t(WORD[r.status]) : r.status} · ${local(r.at)}`} + + {r.summary || (live(r.status) ? t('Working…') : '')} + + {r.draft ? ( + + + {r.draft} + + + ) : null} + {r.outputs.length ? : null} + {r.posts.map((x) => ( + + + {NAME[x.to] ?? x.to} + + {x.url ? ( + + + {t('Posted · open')} + + + + ) : ( + + {x.error} + + )} + + ))} + {r.status === 'review' && host.admin && !answered.has(r.id) ? ( + + + + + ) : r.status === 'review' && !host.admin ? ( + + {t('An org admin posts or discards it.')} + + ) : null} + + {r.session ? ( + ) : null} - - {r.session ? ( - - ) : null} + + ))} + + {runsOverflow ? ( + + setAllRuns((v) => !v)} + px="$2.5" + py="$1.5" + minH={32} + items="center" + focusVisibleStyle={RING} + > + + {allRuns ? t('Show fewer runs') : t('Show all {n} runs', { n: history.value.length })} + + - ))} + ) : null} )} @@ -707,7 +865,9 @@ export function Editor({ id }: { id: string }) { open={asking} onOpenChange={setAsking} onYes={async () => { + const name = a.name await remove(target, a.id) + toast.success(t('{name} deleted', { name })) leave({ replace: true }) }} /> @@ -731,7 +891,7 @@ export function Editor({ id }: { id: string }) { } /** A page with nothing to edit yet: its title and what it says come already said. */ -function Page({ title, says, onBack }: { title: string; says: string; onBack: () => void }) { +function Page({ title, says, onBack, loading = false, error = false, onRetry }: { title: string; says: string; onBack: () => void; loading?: boolean; error?: boolean; onRetry?: () => void }) { const { t } = useI18n() return ( @@ -748,6 +908,20 @@ function Page({ title, says, onBack }: { title: string; says: string; onBack: () {says} + {loading ? ( + + + + + + ) : null} + {error && onRetry ? ( + + + + ) : null} ) diff --git a/src/awake.test.tsx b/src/awake.test.tsx new file mode 100644 index 0000000..109357b --- /dev/null +++ b/src/awake.test.tsx @@ -0,0 +1,61 @@ +import { renderToStaticMarkup } from 'react-dom/server' +import { createElement as h } from 'react' +import { describe, expect, it, vi } from 'vitest' + +const { seen, box } = vi.hoisted(() => { + const seen: Record> = {} + const box = (name: string) => (p: Record) => { + seen[name] = p + return { $$typeof: Symbol.for('react.transitional.element'), type: 'div', key: null, ref: null, props: { children: p.children }, _owner: null, _store: {} } + } + return { seen, box } +}) +vi.mock('@hanzo/gui', () => ({ SizableText: box('text'), YStack: box('ystack') })) +vi.mock('@hanzo/ui', () => ({ DropdownMenuCheckboxItem: box('item') })) + +const { grant, hold, KeepAwake } = await import('./awake.tsx') + +const lock = () => { + const l = { released: 0, release: async () => void l.released++ } + return l +} + +describe('Keep computer awake', () => { + it('is one checkbox row that reports its new state once', () => { + const calls: boolean[] = [] + renderToStaticMarkup(h(KeepAwake, { on: false, onToggle: (on: boolean) => calls.push(on) })) + expect(seen.item).toMatchObject({ checked: false }) + ;(seen.item!.onCheckedChange as (on: boolean) => void)(true) + expect(calls).toEqual([true]) + }) + + it('is on only once the browser grants the lock', async () => { + const l = lock() + expect(await hold({ wakeLock: { request: async () => l } }, null, true)).toBe(l) + expect(await hold({ wakeLock: { request: async () => Promise.reject(new Error('denied')) } }, null, true)).toBeNull() + expect(await hold({}, null, true)).toBeNull() + }) + + it('lets the lock go when switched off, and asks for no second one while it is held', async () => { + const l = lock() + expect(await hold({ wakeLock: { request: async () => lock() } }, l, true)).toBe(l) + expect(await hold({}, l, false)).toBeNull() + expect(l.released).toBe(1) + }) + + it('lets go of a lock that is granted after the run view has closed', async () => { + const l = lock() + expect(await grant({ wakeLock: { request: async () => l } }, null, true, () => true, () => {})).toBeNull() + expect(l.released).toBe(1) + }) + + it('reports it when the browser takes the lock back', async () => { + let fire = () => {} + const l = { ...lock(), addEventListener: (_: 'release', f: () => void) => void (fire = f) } + const dropped: unknown[] = [] + expect(await grant({ wakeLock: { request: async () => l } }, null, true, () => false, (x) => dropped.push(x))).toBe(l) + expect(dropped).toEqual([]) + fire() + expect(dropped).toEqual([l]) + }) +}) diff --git a/src/awake.tsx b/src/awake.tsx new file mode 100644 index 0000000..303ad77 --- /dev/null +++ b/src/awake.tsx @@ -0,0 +1,91 @@ +/** + * The run menu's "Keep computer awake": a checkbox row (so a screen reader hears + * on or off) over the browser's screen wake lock. It reads "on" only once the + * lock is granted, and the lock is let go when the run view closes. + */ +import { SizableText, YStack } from '@hanzo/gui' +import { useI18n } from '@hanzo/i18n/react' +import { DropdownMenuCheckboxItem } from '@hanzo/ui' +import { useEffect, useRef, useState } from 'react' + +export interface Lock { + release: () => Promise + /** The browser fires `release` when it takes the lock back (a hidden tab, low power). */ + addEventListener?: (type: 'release', listener: () => void) => void +} +type Wake = { wakeLock?: { request: (type: 'screen') => Promise } } + +/** The lock held after asking for `on`: a new one when it is granted, none when it is refused, unsupported or let go. */ +export async function hold(nav: Wake, held: Lock | null, on: boolean): Promise { + if (!on) { + await held?.release().catch(() => undefined) + return null + } + if (held) return held + try { + return (await nav.wakeLock?.request('screen')) ?? null + } catch { + return null + } +} + +/** + * Ask for the lock and see it through: a lock granted after the view has closed + * is let go at once, and one the browser later takes back is reported to `dropped`. + */ +export async function grant(nav: Wake, held: Lock | null, on: boolean, closed: () => boolean, dropped: (lock: Lock) => void): Promise { + const next = await hold(nav, held, on) + if (!next || next === held) return next + if (closed()) { + await next.release().catch(() => undefined) + return null + } + next.addEventListener?.('release', () => dropped(next)) + return next +} + +/** [on, set]: `on` follows the lock itself, and the lock goes when the view does. */ +export function useKeepAwake(): [boolean, (on: boolean) => Promise] { + const [on, setOn] = useState(false) + const lock = useRef(null) + const closed = useRef(false) + useEffect(() => { + closed.current = false + return () => { + closed.current = true + void lock.current?.release().catch(() => undefined) + } + }, []) + const set = async (want: boolean) => { + lock.current = await grant( + navigator as unknown as Wake, + lock.current, + want, + () => closed.current, + (l) => { + if (lock.current === l) { + lock.current = null + setOn(false) + } + }, + ) + if (!closed.current) setOn(lock.current !== null) + } + return [on, set] +} + +export function KeepAwake({ on, onToggle }: { on: boolean; onToggle: (on: boolean) => void }) { + const { t } = useI18n() + return ( + + + + {t('Keep computer awake')} + + + {t('Only for this session')} + + + + ) +} diff --git a/src/clipboard.test.ts b/src/clipboard.test.ts new file mode 100644 index 0000000..457c43c --- /dev/null +++ b/src/clipboard.test.ts @@ -0,0 +1,21 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { copy } from './clipboard.ts' + +afterEach(() => vi.unstubAllGlobals()) + +describe('copying to the clipboard', () => { + it('says it copied', async () => { + const wrote: string[] = [] + vi.stubGlobal('navigator', { clipboard: { writeText: async (t: string) => void wrote.push(t) } }) + await expect(copy('abc')).resolves.toBe(true) + expect(wrote).toEqual(['abc']) + }) + + it('says it did not, with nothing thrown, when the browser refuses or has no clipboard', async () => { + vi.stubGlobal('navigator', { clipboard: { writeText: () => Promise.reject(new Error('denied')) } }) + await expect(copy('abc')).resolves.toBe(false) + vi.stubGlobal('navigator', {}) + await expect(copy('abc')).resolves.toBe(false) + }) +}) diff --git a/src/clipboard.ts b/src/clipboard.ts new file mode 100644 index 0000000..9d549c7 --- /dev/null +++ b/src/clipboard.ts @@ -0,0 +1,9 @@ +/** Copy text; true once it is on the clipboard, false where the browser has none or refuses it (nothing is thrown). */ +export const copy = async (text: string): Promise => { + try { + await navigator.clipboard.writeText(text) + return true + } catch { + return false + } +} diff --git a/src/customize/agents.tsx b/src/customize/agents.tsx index 35790f3..2cf2dc2 100644 --- a/src/customize/agents.tsx +++ b/src/customize/agents.tsx @@ -21,11 +21,12 @@ import { SizableText, XStack, YStack } from '@hanzo/gui' import { phrase } from '@hanzo/i18n' import { useI18n, type Say } from '@hanzo/i18n/react' -import { ArrowLeft, Upload } from '@hanzogui/lucide-icons-2' +import { ArrowLeft, Upload, X } from '@hanzogui/lucide-icons-2' import { Button, Input, Switch, Textarea } from '@hanzo/ui' import { ModelPicker } from '@hanzo/ui/models' -import { useEffect, useMemo, useRef, useState } from 'react' +import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react' +import { RING } from '../pane.ts' import { agents, ALL, CAST_CAP, CAST_TASK, create, draft, EMPTY, one, PERIODS, person, profile, remove, SCHEDULES, TRIGGERS, update, use, type Agent, type Cast, type Draft, type Period, type Run, type Trigger } from '../api/agents.ts' import { models, type Model } from '../api/models.ts' import { tools, type Tool } from '../api/tools.ts' @@ -37,12 +38,46 @@ import { Inventory, Traits } from './inventory.tsx' import { useLoad } from './load.ts' import { keep, kept, nature, score, type Answers, type Form } from './ocean.ts' import { say } from './say.ts' -import { Add, Choice, Confirm, Empty, Failed, Field, Grid, Line, Mark, matches, mono, Part, Sheet, Soft, Tile, useCount, Visitor, type Pane } from './ui.tsx' +import { Add, Choice, Confirm, Empty, Failed, Field, FilterPills, Grid, Line, Mark, matches, Part, Sheet, Soft, useCount, Visitor, type Pane } from './ui.tsx' /** How many cards Browse draws at a time. */ -const PAGE = 36 +const PAGE = 24 const ANY = phrase('All') +type AgentDomain = 'all' | 'team' | 'engineering' | 'business' | 'creative' | 'thinking' +type AgentSort = 'recommended' | 'az' + +const DOMAIN_DEFS: ReadonlyArray<{ id: AgentDomain; label: string }> = [ + { id: 'all', label: phrase('All') }, + { id: 'team', label: phrase('Core team') }, + { id: 'engineering', label: phrase('Engineering & science') }, + { id: 'business', label: phrase('Business & strategy') }, + { id: 'creative', label: phrase('Design & creative') }, + { id: 'thinking', label: phrase('Writing & thinking') }, +] + +const ENGINEERING_CATS = new Set([ + 'engineer', 'programmer', 'tech leader', 'cryptographer', 'scientist', + 'mathematician', 'physicist', 'innovator', 'logician', 'architect', +]) +const BUSINESS_CATS = new Set([ + 'executive', 'leader', 'investor', 'economist', 'management', + 'accountant', 'merchant', 'advertiser', 'jurist', 'diplomat', 'statesman', +]) +const CREATIVE_CATS = new Set([ + 'designer', 'artist', 'filmmaker', 'musician', 'composer', + 'photographer', 'sculptor', 'choreographer', 'singer', 'comedian', +]) + +function domainOf(c: Cast, isTeam: boolean): Exclude { + if (isTeam || c.category.toLowerCase() === 'team') return 'team' + const cat = c.category.toLowerCase() + if (ENGINEERING_CATS.has(cat)) return 'engineering' + if (BUSINESS_CATS.has(cat)) return 'business' + if (CREATIVE_CATS.has(cat)) return 'creative' + return 'thinking' +} + const TRIGGER_LABELS: Record = { webhook: { title: phrase('Webhook & API events'), detail: phrase('Wake immediately when an inbound webhook or API event fires.') }, git: { title: phrase('Git, PR & CI events'), detail: phrase('React proactively to pushes, pull requests, and build failures.') }, @@ -109,6 +144,119 @@ const SO_FAR: Record = { const EACH: Record = { day: phrase('Each day, USD'), week: phrase('Each week, USD'), month: phrase('Each month, USD') } const PERIOD: Record = { day: phrase('Day'), week: phrase('Week'), month: phrase('Month') } +const CARD = { rounded: '$4', borderWidth: 1, borderColor: '$borderColor', bg: '$panel' } as const +const CARD_HOVER = { borderColor: 'var(--border-strong)', bg: '$hover' } as const + +/** + * Agent card: top row is [Avatar] [Name + short Role] [flex={1}] [+ Use], and + * the 2-line description spans full card width underneath so copy never crushes. + */ +function AgentCard({ + title, + role, + detail, + meta, + mark, + action, + onOpen, +}: { + title: string + role?: string + detail?: string + meta?: string + mark?: ReactNode + action?: ReactNode + onOpen?: () => void +}) { + const identity = ( + <> + {mark} + + + {title} + + {role ? ( + + {role} + + ) : null} + + + ) + const footer = + detail || meta ? ( + + {detail ? ( + + {detail} + + ) : null} + {meta ? ( + + {meta} + + ) : null} + + ) : null + + if (onOpen && !action) { + return ( + + + + {identity} + + {footer} + + + ) + } + + return ( + + + {onOpen ? ( + + {identity} + + ) : ( + + {identity} + + )} + {action} + + {footer} + + ) +} + export function Agents({ view, q, adding, onAdding, onView, onCount, mode = 'agents' }: Pane & { mode?: 'agents' | 'bots' }) { const { t } = useI18n() const host = useHost() @@ -124,12 +272,21 @@ export function Agents({ view, q, adding, onAdding, onView, onCount, mode = 'age ) useCount(yoursList.length, onCount) const [note, setNote] = useState('') - const [kind, setKind] = useState(ANY) + const [domain, setDomain] = useState('all') + const [sortBy, setSortBy] = useState('recommended') + const [showSpecialists, setShowSpecialists] = useState(false) const [more, setMore] = useState(PAGE) const [using, setUsing] = useState(null) + const [scratch, setScratch] = useState(false) const [making, setMaking] = useState<'self' | 'person' | null>(null) const [electing, setElecting] = useState(null) - useEffect(() => setMore(PAGE), [q, kind, botsMode]) + useEffect(() => setMore(PAGE), [q, domain, sortBy, botsMode]) + + const allCast = host.cast ?? [] + const isBotCast = (c: Cast) => c.category === 'Bot' || c.executionMode === 'long-running' + const first: readonly Cast[] = botsMode + ? allCast.map(asBot) + : allCast.map((c): Cast => (isBotCast(c) ? { ...c, category: 'Team', executionMode: undefined, schedule: undefined, triggers: undefined } : c)) const opened = (a: Agent) => host.go(path({ kind: 'agent', name: a.name })) const take = async (c: Cast) => { @@ -157,112 +314,339 @@ export function Agents({ view, q, adding, onAdding, onView, onCount, mode = 'age } } - const editor = adding ? ( - onAdding(false)} - onSaved={(a) => { - onAdding(false) - onView('yours') - mine.reload() - setNote(t('{name} is saved', { name: a.name })) - }} - /> - ) : null + // Toggleable creation panel opened by `+ New agent` / `+ New bot` — closed by default when browsing so the grid starts immediately. + const creator = + adding && signed ? ( + + + + {botsMode ? t('Create a new bot') : t('Create a new agent')} + + onAdding(false)} + width={32} + height={32} + items="center" + justify="center" + shrink={0} + focusVisibleStyle={RING} + > + + + + {botsMode ? ( + <> + + {t('Build a persistent 24/7 bot from scratch, or elect a preset to run on a schedule and event triggers.')} + + + + {allCast.length ? ( + + ) : null} + + + ) : ( + <> + + + + {t('Or start another way')} + + + + + + + )} + + ) : null + + const modals = ( + <> + {scratch ? ( + setScratch(false)} + onSaved={(a) => { + setScratch(false) + onAdding(false) + onView('yours') + mine.reload() + setNote(t('{name} is saved', { name: a.name })) + }} + /> + ) : null} + {making ? setMaking(null)} onMade={opened} /> : null} + {electing ? setElecting(null)} onElected={opened} /> : null} + + ) if (browsing) { - const allCast = host.cast ?? [] - const isBotCast = (c: Cast) => c.category === 'Bot' || c.executionMode === 'long-running' - const first: readonly Cast[] = botsMode - ? allCast.map(asBot) - : allCast.map((c): Cast => (isBotCast(c) ? { ...c, category: 'Team', executionMode: undefined, schedule: undefined, triggers: undefined } : c)) const rest = botsMode ? ([] as readonly Cast[]) : figures.value.filter((c) => !isBotCast(c)) - const all = [...first, ...rest] - const shown = all.filter((c) => (botsMode || kind === ANY || c.category === kind) && matches(q, c.title, c.name, c.description, c.category, ...(c.after ?? []))) - const card = (c: Cast) => ( - } - onOpen={signed && botsMode ? () => setElecting(c) : undefined} - action={ - signed ? ( - - {botsMode ? ( - - - - ) : null} - void take(c)} /> - - ) : undefined - } - /> + const teamSet = new Set(first.map((c) => `${c.name}/${c.title}`)) + const sortList = (list: readonly Cast[]) => + sortBy === 'az' ? [...list].sort((a, b) => a.title.localeCompare(b.title)) : [...list] + + const queryText = q.trim() + const matchCast = (c: Cast) => + matches(q, c.title, c.name, c.description, c.category, ...(c.after ?? [])) + + const teamFiltered = sortList(first.filter((c) => (botsMode || domain === 'all' || domain === 'team') && matchCast(c))) + const specialistsFiltered = sortList( + rest.filter( + (c) => + !botsMode && + (domain === 'all' || domainOf(c, teamSet.has(`${c.name}/${c.title}`)) === domain) && + matchCast(c), + ), ) + + const card = (c: Cast, inCoreTeam = false) => { + const cat = botsMode ? t('Bot') : category(c.category, t) + const hideTeamLabel = inCoreTeam && !botsMode && c.category.toLowerCase() === 'team' + const role = hideTeamLabel + ? c.after?.length + ? t('after {names}', { names: c.after.join(', ') }) + : undefined + : cat || undefined + const detail = + [ + c.description === c.title || c.description === c.category ? '' : c.description, + !hideTeamLabel && c.after?.length ? t('after {names}', { names: c.after.join(', ') }) : '', + ] + .filter(Boolean) + .join(' · ') || undefined + const meta = botsMode + ? [c.executionMode === 'long-running' ? t('24/7 · proactive · event-driven') : '', c.schedule].filter(Boolean).join(' · ') || undefined + : undefined + return ( + } + onOpen={signed && botsMode ? () => setElecting(c) : undefined} + action={ + signed ? ( + + {botsMode ? ( + + + + ) : null} + void take(c)} /> + + ) : undefined + } + /> + ) + } + + const domainCounts: Record = { + all: first.length + rest.length, + team: first.length, + engineering: rest.filter((c) => domainOf(c, false) === 'engineering').length, + business: rest.filter((c) => domainOf(c, false) === 'business').length, + creative: rest.filter((c) => domainOf(c, false) === 'creative').length, + thinking: rest.filter((c) => domainOf(c, false) === 'thinking').length, + } + + const domainOptions = DOMAIN_DEFS.filter((d) => d.id === 'all' || d.id === 'team' || domainCounts[d.id] > 0).map((d) => ({ + id: d.id, + label: d.id === 'all' ? t(d.label) : `${t(d.label)}`, + })) + + const hasAnyMatch = teamFiltered.length > 0 || specialistsFiltered.length > 0 + const showGroupedAll = !botsMode && domain === 'all' && !queryText + const specialistsVisible = showGroupedAll ? showSpecialists : true + return ( - - {signed && !botsMode ? : null} - {signed ? ( - - - {botsMode ? ( - allCast.length ? ( - - ) : null - ) : ( - <> - - - - )} - - ) : null} - {!botsMode ? ( - - ({ id, label: category(id, t) }))} onChange={setKind} /> + + {creator} + {!botsMode && domainOptions.length > 1 ? ( + + + setDomain(next as AgentDomain)} + maxVisibleDesktop={6} + mobileLimit={4} + /> + + + {( + [ + { id: 'recommended', label: t('Recommended') }, + { id: 'az', label: t('A–Z') }, + ] as const + ).map((opt) => { + const active = sortBy === opt.id + return ( + setSortBy(opt.id)} + px="$2.5" + py="$1" + minH={28} + focusVisibleStyle={RING} + items="center" + justify="center" + > + + {opt.label} + + + ) + })} + ) : null} {note} - {shown.length ? ( - - {shown.slice(0, more).map(card)} - - ) : figures.loading ? null : q.trim() ? ( - {t(botsMode ? 'No bot matches “{q}”.' : 'No agent matches “{q}”.', { q: q.trim() })} - ) : botsMode ? ( - {t('Create a persistent 24/7 bot from scratch or elect any preset.')} + + {!hasAnyMatch ? ( + figures.loading ? null : queryText ? ( + {t(botsMode ? 'No bot matches “{q}”.' : 'No agent matches “{q}”.', { q: queryText })} + ) : botsMode ? ( + {t('Create a persistent 24/7 bot from scratch or elect any preset.')} + ) : ( + {t('No agent matches “{q}”.', { q: queryText })} + ) ) : ( - {t('No agent matches “{q}”.', { q: q.trim() })} + + {teamFiltered.length > 0 ? ( + + {!botsMode ? ( + + + {t('Core team')} + + + {t('{n} ready-to-use specialists', { n: teamFiltered.length })} + + + ) : null} + + {teamFiltered.map((c) => card(c, !botsMode))} + + + ) : null} + + {specialistsFiltered.length > 0 ? ( + 0 ? '$5' : 0} + borderTopWidth={teamFiltered.length > 0 ? 1 : 0} + > + + + + {domain === 'all' ? t('Domain thinkers & personas') : t(DOMAIN_DEFS.find((d) => d.id === domain)?.label ?? 'Personas')} + + + {t('{n} curated personas across science, strategy, design, and writing', { n: specialistsFiltered.length })} + + + {showGroupedAll ? ( + + ) : null} + + {specialistsVisible ? ( + <> + + {specialistsFiltered.slice(0, more).map((c) => card(c, false))} + + {specialistsFiltered.length > more ? ( + + + + ) : null} + + ) : null} + + ) : null} + )} - {shown.length > more ? ( - - - - ) : null} + {figures.error ? : figures.loading ? {t('Loading…')} : null} - {editor} - {making ? setMaking(null)} onMade={opened} /> : null} - {electing ? setElecting(null)} onElected={opened} /> : null} + {modals} ) } @@ -273,13 +657,17 @@ export function Agents({ view, q, adding, onAdding, onView, onCount, mode = 'age const shown = yoursList.filter((a) => matches(q, a.name, a.description, a.model)) return ( + {creator} {note} {mine.error && !yoursList.length ? ( ) : mine.loading && !yoursList.length ? ( {t(botsMode ? 'Loading your bots…' : 'Loading your agents…')} ) : !yoursList.length ? ( - + @@ -292,12 +680,12 @@ export function Agents({ view, q, adding, onAdding, onView, onCount, mode = 'age ) : ( {shown.map((a) => ( - - + + {all.map((c) => { const active = c.name === picked.name && c.category === picked.category return ( - ) @@ -413,11 +807,20 @@ function Elect({ - {SCHEDULES.map((s) => ( - - ))} + {SCHEDULES.map((s) => { + const active = schedule.trim() === s.cron + return ( + + ) + })} @@ -470,8 +873,8 @@ function Elect({ - @@ -648,7 +1051,7 @@ export function Profile({ name }: { name: string }) { {a.instructions ? ( - - + + {a.instructions} @@ -847,7 +1250,7 @@ function Editor({ shownTools.map((x, i) => ( - + {x.name} @@ -866,7 +1269,7 @@ function Editor({ - {t('Autonomous & Event-Driven (24/7)')} + {t('Autonomous and event-driven (24/7)')} {d.executionMode === 'long-running' @@ -892,11 +1295,20 @@ function Editor({ {t('Proactive schedule (5-field cron)')} - {SCHEDULES.map((s) => ( - - ))} + {SCHEDULES.map((s) => { + const active = (d.schedule ?? '').trim() === s.cron + return ( + + ) + })} set({ schedule: v })} placeholder="*/15 * * * *" aria-label={t('Proactive schedule')} /> @@ -909,7 +1321,8 @@ function Editor({ - - ) : null} + {!list.length ? ( + setFilter('all')}> + {t('Show all connectors')} + + ) : undefined + } + > + {text + ? t('No connector matches “{q}”.', { q: text }) + : filter !== 'all' + ? t('No connectors in this view on the loaded page.') + : t('There are no connectors to add yet.')} + + ) : ( + <> + {hero ? ( + } + onOpen={() => onOpen(hero)} + action={action(hero)} + /> + ) : null} + + {filter !== 'all' + ? t('{shown} matching in {loaded} loaded', { shown: list.length, loaded: loaded.length }) + : loaded.length < page.total + ? t('{shown} of {n} connectors', { shown: loaded.length, n: page.total }) + : t('{n} connectors', { n: page.total })} + + + {rest.map((l) => ( + } onOpen={() => onOpen(l)} action={action(l)} /> + ))} + + {note ? : null} + {loaded.length < page.total ? ( + + + + ) : null} + + )} )} @@ -303,8 +407,11 @@ function Natives({ q }: { q: string }) { const [asked, setAsked] = useState(r.kind === 'screen' && r.screen === 'mcp') const list = useLoad(asked ? () => natives(target) : null, [] as Native[], [target, asked]) const [open, setOpen] = useState(null) + const [showAll, setShowAll] = useState(false) const shown = list.value.filter((s) => matches(q, s.name, s.description, ...s.ops)) const ops = shown.reduce((n, s) => n + s.ops.length, 0) + const searching = Boolean(q.trim()) + const visible = searching || showAll ? shown : shown.slice(0, BUILTIN_INITIAL) return ( {!asked ? null : list.loading && !list.value.length ? ( - {t('Loading built-in servers…')} + ) : list.error && !list.value.length ? ( ) : !shown.length ? ( {list.value.length ? t('No built-in server matches “{q}”.', { q: q.trim() }) : t('No built-in servers are listed.')} ) : ( - - + + {t('{servers} servers · {ops} operations', { servers: shown.length, ops })} - {shown.map((s) => { + {visible.map((s) => { const on = open === s.name return ( - - setOpen(on ? null : s.name)}> - + + setOpen(on ? null : s.name)} + > + + {s.name} @@ -343,16 +464,16 @@ function Natives({ q }: { q: string }) { ) : null} - + {s.ops.length} - + {on ? : } {on ? ( {s.ops.length ? ( s.ops.map((op) => ( - + {op} )) @@ -366,6 +487,13 @@ function Natives({ q }: { q: string }) { ) })} + {!searching && shown.length > BUILTIN_INITIAL ? ( + + + + ) : null} )} @@ -384,7 +512,7 @@ function About({ listing, added, signed, onAdd, onClose }: { listing: Listing; a - + {l.name} @@ -400,7 +528,7 @@ function About({ listing, added, signed, onAdd, onClose }: { listing: Listing; a {l.remotes.length ? ( {l.remotes.map((r) => ( - + {r.url} · {r.transport} ))} @@ -409,7 +537,7 @@ function About({ listing, added, signed, onAdd, onClose }: { listing: Listing; a {l.packages.length ? ( {l.packages.map((p) => ( - + {[p.registry, p.identifier, p.version, p.runtime].filter(Boolean).join(' · ')} ))} @@ -422,12 +550,12 @@ function About({ listing, added, signed, onAdd, onClose }: { listing: Listing; a {where(u)} - + ))} ) : null} - {full.error ? {t('Showing what Browse listed. {reason}', { reason: say(full.error, t) })} : null} + {full.error ? : null} {signed && ready(l) ? ( - @@ -521,19 +651,24 @@ function Detail({ server, may, onClose, onDeleted }: { server: Server; may: bool const target = useTarget() const list = useLoad(() => tools(target, { source: 'mcp' }), [] as Tool[], [target, server.id]) const its = useMemo(() => list.value.filter((x) => owns(server, x.name)), [list.value, server]) + const [toolQuery, setToolQuery] = useState('') const [busy, setBusy] = useState(false) - const [note, setNote] = useState('') + const [error, setError] = useState('') const [asking, setAsking] = useState(false) const off = its.filter((x) => !x.activated).map((x) => x.name) + const filteredTools = useMemo( + () => (toolQuery.trim() ? its.filter((x) => matches(toolQuery, x.name.slice(server.id.length + 1), x.description)) : its), + [its, server.id, toolQuery], + ) const flip = async (on: string[], offNames: string[]) => { setBusy(true) - setNote('') + setError('') try { await toggle(target, on, offNames) list.reload() } catch (e) { - setNote(say(e, t)) + setError(say(e, t)) } finally { setBusy(false) } @@ -541,13 +676,13 @@ function Detail({ server, may, onClose, onDeleted }: { server: Server; may: bool return ( !o && onClose()}> - - + + {server.url} - {server.secret ? : } - + {server.secret ? : } + {server.secret ? server.header ? t('A secret is sealed in KMS and sent in {header}.', { header: server.header }) @@ -557,8 +692,8 @@ function Detail({ server, may, onClose, onDeleted }: { server: Server; may: bool - - {t('Tools')} + + {its.length ? t('Tools ({n})', { n: its.length }) : t('Tools')} {its.length && may ? ( ) : null} + {its.length > 8 ? ( + } + endAdornment={ + toolQuery ? ( + setToolQuery('')} + minW={24} + minH={24} + items="center" + justify="center" + focusVisibleStyle={RING} + > + + + ) : undefined + } + onKeyDown={(e: { key?: string }) => { + if (e.key === 'Escape' && toolQuery) setToolQuery('') + }} + /> + ) : null} {list.loading && !list.value.length ? ( - {t('Loading its tools…')} + ) : list.error && !list.value.length ? ( ) : !its.length ? ( {t('No tools listed yet. A server that does not answer shows its tools once it does.')} + ) : !filteredTools.length ? ( + {t('No tool matches “{q}”.', { q: toolQuery.trim() })} ) : ( - - {its.map((x, i) => { + + {filteredTools.map((x, i) => { const short = x.name.slice(server.id.length + 1) return ( - + {short} {x.description ? ( @@ -600,11 +765,17 @@ function Detail({ server, may, onClose, onDeleted }: { server: Server; may: bool })} )} - {note || (may ? '' : t('Only an org admin can switch or remove connectors.'))} + {error ? ( + + ) : !may ? ( + + {t('Only an org admin can switch or remove connectors.')} + + ) : null} {may ? ( - ) : null} diff --git a/src/customize/drafted.test.tsx b/src/customize/drafted.test.tsx new file mode 100644 index 0000000..dcbf6ce --- /dev/null +++ b/src/customize/drafted.test.tsx @@ -0,0 +1,30 @@ +import { createElement as h } from 'react' +import { renderToStaticMarkup } from 'react-dom/server' +import { describe, expect, it, vi } from 'vitest' + +// Each piece keeps the props it is drawn with, so the test sees how the "Make with AI" row is cut. +const { seen, piece, none } = vi.hoisted(() => { + const seen: Record[]> = {} + const piece = (name: string) => (p: Record) => { + ;(seen[name] ??= []).push(p) + return { $$typeof: Symbol.for('react.transitional.element'), type: 'div', key: null, ref: null, props: { children: p.children }, _owner: null, _store: {} } + } + return { seen, piece, none: () => null } +}) +vi.mock('@hanzo/gui', () => ({ SizableText: piece('text'), XStack: piece('xstack'), YStack: piece('ystack') })) +vi.mock('@hanzo/ui', () => ({ Button: piece('button'), Input: piece('input'), Skeleton: piece('skeleton'), Textarea: piece('textarea') })) +vi.mock('@hanzogui/lucide-icons-2', () => ({ AlertCircle: none, Sparkles: none, X: none })) +vi.mock('../host.tsx', () => ({ useTarget: () => ({}) })) +vi.mock('./ui.tsx', () => ({ Field: piece('field'), Mark: none, Sheet: piece('sheet') })) + +const { Drafted } = await import('./drafted.tsx') + +describe('the Make with AI row', () => { + it('can shrink inside a narrow panel and stacks on a phone, so it never overflows', () => { + renderToStaticMarkup(h(Drafted, { onMade: () => {} })) + const row = seen.xstack!.find((p) => p['$max-sm'] && (p['$max-sm'] as Record).flexDirection === 'column') + expect(row).toMatchObject({ width: '100%', minW: 0 }) + expect(seen.input![0]).toMatchObject({ minW: 0, flex: 1 }) + expect(seen.button![0]!['$max-sm']).toMatchObject({ width: '100%' }) + }) +}) diff --git a/src/customize/drafted.tsx b/src/customize/drafted.tsx index f3f5be1..77240c3 100644 --- a/src/customize/drafted.tsx +++ b/src/customize/drafted.tsx @@ -8,57 +8,136 @@ */ import { SizableText, XStack, YStack } from '@hanzo/gui' import { useI18n } from '@hanzo/i18n/react' -import { Button, Input, Textarea } from '@hanzo/ui' +import { AlertCircle, Sparkles, X } from '@hanzogui/lucide-icons-2' +import { Button, Input, Skeleton, Textarea } from '@hanzo/ui' import { useState } from 'react' +import { RING } from '../pane.ts' import { agents, CAST_CAP, CAST_TASK, create, EMPTY, free, handle, type Agent } from '../api/agents.ts' import { portrait, saved, sketch, type Portrait, type Sketch } from '../api/draft.ts' import { useTarget } from '../host.tsx' import { say } from './say.ts' -import { Field, Line, Mark, Sheet } from './ui.tsx' +import { Field, Mark, Sheet } from './ui.tsx' /** How long a portrait is waited for before the draft is shown without one. */ const WAIT = 6000 +function ErrorLine({ text }: { text: string }) { + if (!text) return null + return ( + + + + {text} + + + ) +} + +function DraftSkeleton({ label }: { label: string }) { + return ( + + + + + + + + + ) +} + export function Drafted({ onMade }: { onMade: (a: Agent) => void }) { const { t } = useI18n() const target = useTarget() const [line, setLine] = useState('') const [busy, setBusy] = useState(false) - const [note, setNote] = useState('') + const [error, setError] = useState('') const [draft, setDraft] = useState<{ s: Sketch; face: Portrait | null } | null>(null) const make = async () => { if (!line.trim() || busy) return setBusy(true) - setNote('') + setError('') try { const s = await sketch(target, line) const face = s.figure ? await portrait(s.figure, AbortSignal.timeout(WAIT)) : null setDraft({ s, face }) } catch (e) { - setNote(say(e, t)) + setError(say(e, t)) } finally { setBusy(false) } } return ( - - - + + void make()} - /> - - {note} + {busy ? : null} + {draft ? setDraft(null)} onMade={onMade} /> : null} ) @@ -72,11 +151,11 @@ function Review({ draft, onClose, onMade }: { draft: { s: Sketch; face: Portrait const [instructions, setInstructions] = useState(draft.s.instructions) const [opening, setOpening] = useState(draft.s.opening) const [working, setWorking] = useState(false) - const [note, setNote] = useState('') + const [error, setError] = useState('') const save = async () => { setWorking(true) - setNote('') + setError('') try { const have = await agents(target) const made = await create(target, { @@ -91,7 +170,7 @@ function Review({ draft, onClose, onMade }: { draft: { s: Sketch; face: Portrait }) onMade(made) } catch (e) { - setNote(say(e, t)) + setError(say(e, t)) setWorking(false) } } @@ -100,27 +179,31 @@ function Review({ draft, onClose, onMade }: { draft: { s: Sketch; face: Portrait !o && onClose()}> {draft.s.emoji} : undefined} /> - - + + + {draft.face?.licence ? ( + + {t('Portrait: {licence}', { licence: draft.face.licence })} + + ) : null} - + -