From 6356e72bd97a08e74a5415b6d15e7c6ee8090c12 Mon Sep 17 00:00:00 2001 From: Zach Kelling Date: Fri, 20 Nov 2026 19:42:57 -0800 Subject: [PATCH] @hanzo/build 0.2.138: redesign a site from its address on Hanzo Desktop (hanzo-inc/app#312) A host that has the computer and can open a site (Host.site, site.ts) is offered the address pasted in New as a redesign: the host opens the site and saves a copy for the agent, serves the folder's redesign/ live and shows it in Chrome; the agent critiques it and builds the new site as static files. An ask that only holds a link is a normal run. Claude-Session: https://claude.ai/code/session_015XYKLn69gF4x75RWePpDBV --- README.md | 10 +- package.json | 2 +- src/e2e/host.tsx | 37 ++++- src/e2e/redesign.spec.ts | 156 ++++++++++++++++++++ src/host.tsx | 11 ++ src/index.ts | 1 + src/landing.tsx | 31 +++- src/redesign.tsx | 298 +++++++++++++++++++++++++++++++++++++++ src/site.test.ts | 139 ++++++++++++++++++ src/site.ts | 192 +++++++++++++++++++++++++ 10 files changed, 869 insertions(+), 8 deletions(-) create mode 100644 src/e2e/redesign.spec.ts create mode 100644 src/redesign.tsx create mode 100644 src/site.test.ts create mode 100644 src/site.ts diff --git a/README.md b/README.md index 5be04e8..88c54b1 100644 --- a/README.md +++ b/README.md @@ -301,7 +301,15 @@ The agent reads, edits and runs in that folder only. What it said shows under th composer in words (`plainAnswer`: the folder's path is its name, `~` is "your home folder"), what it did only in Developer mode (`Done.process`), and the first run says "Setting up Hanzo Dev on this computer…" while the host fetches the agent -(`run`'s `setup` callback). +(`run`'s `setup` callback). A host that can +also open a site (Hanzo Desktop hands `site`, site.ts) offers to redesign one from +its address: an address pasted alone, or with a request to redesign it, or Redesign +a site… in the composer's commands. The host opens the site from the computer's own +connection and saves a copy of it into the folder (`.hanzo/reference`), serves the +folder's `redesign/` live and shows it in Chrome; the agent, which has no network, +reads the copy, answers with a critique and builds the new site there as static +files, and the preview follows each file it saves. An ask that only holds a link is +a normal run. **A run.** The transcript as it streams, drawn by what each part is: what the agent says as markdown, each command it runs as a card that opens onto its diff --git a/package.json b/package.json index 8fd05a6..3e8f537 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@hanzo/build", - "version": "0.2.137", + "version": "0.2.138", "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.", diff --git a/src/e2e/host.tsx b/src/e2e/host.tsx index 97192f9..35a9eff 100644 --- a/src/e2e/host.tsx +++ b/src/e2e/host.tsx @@ -17,6 +17,8 @@ * ?folders=a,b instead of f1..fn: the computer's folders by name, the last one used most recently * ?found=a,b folders the computer finds a moment after the first read (it says so through `changed`), never opened in Hanzo * ?setup=1 the first run fetches the agent: it says 40% and waits for "Finish setup" before it says 100% and runs + * ?site= the host can redesign a site (Hanzo Desktop's `site`; needs ?local): `ok`, or `fail` where the site will + * not open. Every step it is asked for is written out under the sidebar (Redesign steps) */ import '@hanzo/font/css' import '@hanzo/ui/theme.css' @@ -27,7 +29,7 @@ import { Sidebar, SidebarItem } from '@hanzo/ui/chat' import { StrictMode, useState } from 'react' import { createRoot } from 'react-dom/client' -import { administers, Builder, DevSection, Grip, type Folder, type Host, type Local } from '../index.ts' +import { administers, Builder, DevSection, Grip, type Folder, type Host, type Local, type Site } from '../index.ts' const ORG = 'acme' const bearer = () => window.localStorage.getItem('hanzo_iam_access_token') @@ -68,11 +70,36 @@ function computer(n: number, ran: (line: string) => void, names: string[], found }) fetching?.(100) } - return { ok: true, output: `Edited README.md in ${folder}`, process: `exec bash -lc 'ls ~' in ${folder}\n succeeded in 12ms` } + return { + ok: true, + output: prompt.startsWith('Redesign the website') ? 'The page is cluttered. I rebuilt it around one clear call to action.' : `Edited README.md in ${folder}`, + process: `exec bash -lc 'ls ~' in ${folder}\n succeeded in 12ms`, + } }, } } +/** A host that can redesign a site, as Hanzo Desktop's `site` answers: `fail` is a site that will not open. */ +function website(mode: string, said: (line: string) => void): Site { + return { + folder: async (name) => { + said(`folder ${name}`) + return { path: `/Users/dave/Documents/Hanzo/${name}`, name } + }, + capture: async (url, folder) => { + said(`capture ${url} -> ${folder}`) + if (mode === 'fail') throw new Error('The site took too long to answer.') + return { title: 'Acme Plumbing', url, files: ['page.html', 'text.md', 'style-1.css'], screenshot: false } + }, + preview: async (folder) => { + said(`preview ${folder}`) + return { url: 'http://127.0.0.1:9933/' } + }, + stop: async (folder) => said(`stop ${folder}`), + show: async (url) => said(`show ${url}`), + } +} + function Page() { const q = new URLSearchParams(window.location.search) const [at, setAt] = useState(q.get('at') ?? '') @@ -87,6 +114,8 @@ function Page() { ? computer(Number(q.get('local')) || 0, (line) => setRan((r) => [...r, line]), (q.get('folders') ?? '').split(',').filter(Boolean), (q.get('found') ?? '').split(',').filter(Boolean), setup) : undefined, ) + const [steps, setSteps] = useState([]) + const [site] = useState(() => (q.has('site') ? website(q.get('site') ?? 'ok', (line) => setSteps((s) => [...s, line])) : undefined)) const token = bearer() const host: Host = { name: 'Hanzo', @@ -103,6 +132,7 @@ function Page() { links: { github: '/dev/-/sync', customize: '/dev/-/customize', settings: '/settings', home: '/' }, open: () => {}, ...(local ? { local } : {}), + ...(site ? { site } : {}), } const label = q.get('label') if (shut) @@ -134,6 +164,9 @@ function Page() { {ran.join(' | ')} {setup ? setup.finish()}>Finish setup : null} + + {steps.join(' | ')} + diff --git a/src/e2e/redesign.spec.ts b/src/e2e/redesign.spec.ts new file mode 100644 index 0000000..cbaf4af --- /dev/null +++ b/src/e2e/redesign.spec.ts @@ -0,0 +1,156 @@ +/** + * Redesign a site from its address (hanzo-inc/app issue 312, hanzoai/desktop issue 15): on a host that has the computer + * and can open a site, an address pasted in New is offered as a redesign; one press has the host open the site and save a + * copy, serve the redesign live and show it in Chrome, and the agent critique and build it in a new folder. An ask that + * only holds a link is sent as it is. Driven through the host page (/src/e2e/host.html): `?local=` hands the builder + * the computer, `?site=` the host's way of redesigning a site. + */ +import type { Page } from '@playwright/test' + +import { expect, test } from './fixture.ts' +import { signIn, type Sent } from './signed.ts' + +const HOST = '/src/e2e/host.html' +const ask = (page: Page) => page.getByRole('textbox', { name: 'Describe a task or ask a question' }) +const runs = (page: Page) => page.getByLabel('Runs on this computer') +const steps = (page: Page) => page.getByLabel('Redesign steps') +const offer = (page: Page) => page.locator('[data-slot="redesign-offer"]') +const card = (page: Page) => page.locator('[data-slot="redesign"]') +const platform = (sent: Sent[]) => sent.filter((s) => s.method === 'POST' && (s.path === '/v1/agent/turns' || s.path === '/v1/agent/coding')) + +const quiet = (page: Page) => + signIn(page, ({ path }) => { + if (path === '/v1/agent/sessions') return { json: { sessions: [], next: '' } } + if (path === '/v1/agent/sessions/stream') return { text: '', type: 'text/event-stream' } + if (path === '/v1/agent/targets') return { json: { targets: [] } } + return undefined + }) + +test.describe('Redesign a site', () => { + test('an address pasted alone is offered, and one press opens the site, serves the redesign and has the agent build it', async ({ page }, info) => { + const sent = await quiet(page) + await page.goto(`${HOST}?local=2&site=ok`) + await ask(page).fill('https://www.acme.test/plumbing', { timeout: 45_000 }) + await expect(offer(page)).toContainText('Redesign acme.test?') + await expect(offer(page)).toContainText('Hanzo opens it, reviews it, and builds a new version here while you watch it in Chrome.') + await page.screenshot({ path: info.outputPath('redesign-offer.png') }) + + await offer(page).getByRole('button', { name: 'Redesign this site' }).click() + await expect(card(page)).toContainText('Redesigned acme.test') + // The steps, in order: a new folder named for the site, the site saved into it, the redesign served, then shown. + await expect(steps(page)).toHaveText( + 'folder acme-redesign | capture https://www.acme.test/plumbing -> /Users/dave/Documents/Hanzo/acme-redesign | preview /Users/dave/Documents/Hanzo/acme-redesign | show http://127.0.0.1:9933/', + ) + // The agent is sent to that folder with what was saved and what to do. + const run = await runs(page).textContent() + expect(run).toContain('/Users/dave/Documents/Hanzo/acme-redesign <- Redesign the website https://www.acme.test/plumbing (Acme Plumbing).') + expect(run).toContain('- .hanzo/reference/text.md:') + expect(run).toContain('- .hanzo/reference/style-1.css: one of its stylesheets') + expect(run).not.toContain('screenshot') + expect(run).toContain('Do not start a server and do not use the network') + // The card says where it is, how to see it, and what the agent said; the ask was taken. + await expect(card(page)).toContainText('Live preview: http://127.0.0.1:9933/') + await expect(card(page)).toContainText('/Users/dave/Documents/Hanzo/acme-redesign') + await expect(card(page)).toContainText('The page is cluttered. I rebuilt it around one clear call to action.') + await expect(ask(page)).toHaveValue('') + await expect(offer(page)).toHaveCount(0) + await page.screenshot({ path: info.outputPath('redesign-done.png') }) + + // Open in Chrome shows the same address again. + await card(page).getByRole('button', { name: 'Open in Chrome' }).click() + await expect(steps(page)).toContainText('show http://127.0.0.1:9933/ | show http://127.0.0.1:9933/') + // The redesign's folder is now the one Auto picks, so the next ask goes to it and the preview follows its files. + await expect(page.getByRole('button', { name: /^Folder: / })).toHaveAccessibleName('Folder: Auto · acme-redesign') + // Nothing went to the platform. + expect(platform(sent)).toHaveLength(0) + }) + + test('Enter on an address alone starts it too, and "redesign
and …" keeps what was said', async ({ page }) => { + await quiet(page) + await page.goto(`${HOST}?local=1&site=ok`) + await ask(page).fill('Redesign shop.acme.com and make it darker', { timeout: 45_000 }) + await expect(offer(page)).toContainText('Redesign shop.acme.com?') + await ask(page).press('Enter') + await expect(card(page)).toContainText('Redesigned shop.acme.com') + await expect(steps(page)).toContainText('folder shop-acme-redesign') + await expect(runs(page)).toContainText('The person added: “Redesign and make it darker”') + }) + + test('an ask that only holds a link is a normal run, with no offer', async ({ page }) => { + await quiet(page) + await page.goto(`${HOST}?local=1&site=ok`) + await ask(page).fill('What does https://acme.test say about pricing?', { timeout: 45_000 }) + await expect(offer(page)).toHaveCount(0) + await ask(page).press('Enter') + await expect(runs(page)).toHaveText('/Users/dave/f1 <- What does https://acme.test say about pricing?') + await expect(steps(page)).toHaveText('') + await expect(card(page)).toHaveCount(0) + }) + + test('a folder the person chose is built in, and no new one is made', async ({ page }) => { + await quiet(page) + await page.goto(`${HOST}?local=2&site=ok`) + await page.getByRole('button', { name: /^Folder: / }).click({ timeout: 45_000 }) + await page.getByRole('listbox', { name: 'Folder' }).getByRole('option', { name: /^f1/ }).click() + await ask(page).fill('acme.com') + await ask(page).press('Enter') + await expect(card(page)).toContainText('Redesigned acme.com') + await expect(steps(page)).toHaveText('capture https://acme.com/ -> /Users/dave/f1 | preview /Users/dave/f1 | show http://127.0.0.1:9933/') + await expect(runs(page)).toContainText('/Users/dave/f1 <- Redesign the website') + }) + + test('a site that will not open is said in plain words, nothing is built, and the person can try again', async ({ page }, info) => { + await quiet(page) + await page.goto(`${HOST}?local=1&site=fail`) + await ask(page).fill('https://slow.test', { timeout: 45_000 }) + await ask(page).press('Enter') + await expect(card(page)).toContainText('Could not redesign slow.test') + await expect(card(page)).toContainText('The site took too long to answer.') + await expect(steps(page)).toContainText('capture https://slow.test/') + await expect(steps(page)).not.toContainText('preview') + await expect(runs(page)).toHaveText('') + await expect(card(page).getByRole('button', { name: 'Open in Chrome' })).toHaveCount(0) + await page.screenshot({ path: info.outputPath('redesign-failed.png') }) + // Nothing is stuck: the composer takes another ask. + await expect(ask(page)).toBeEditable() + await ask(page).fill('Fix the typo') + await ask(page).press('Enter') + await expect(runs(page)).toHaveText('/Users/dave/f1 <- Fix the typo') + }) + + test('Redesign a site… asks for the address, and refuses what is not one', async ({ page }, info) => { + await quiet(page) + await page.goto(`${HOST}?local=1&site=ok`) + await ask(page).focus({ timeout: 45_000 }) + await page.keyboard.press('Control+k') + await page.getByRole('listbox', { name: 'Commands' }).getByRole('option', { name: /Redesign a site/ }).click() + const dialog = page.getByRole('dialog', { name: 'Redesign a site' }) + await expect(dialog).toBeVisible() + await page.screenshot({ path: info.outputPath('redesign-ask.png') }) + await dialog.getByRole('textbox', { name: 'Site address' }).fill('not a site') + await dialog.getByRole('button', { name: 'Redesign', exact: true }).click() + await expect(dialog).toContainText('Paste a site’s address, like https://example.com.') + await dialog.getByRole('textbox', { name: 'Site address' }).fill('example.com') + await dialog.getByRole('textbox', { name: 'Site address' }).press('Enter') + await expect(card(page)).toContainText('Redesigned example.com') + await expect(steps(page)).toContainText('folder example-redesign') + }) + + test('a host that cannot open a site offers nothing of it, and neither does a computer on another place', async ({ page }) => { + await quiet(page) + // The computer, but no way to open a site. + await page.goto(`${HOST}?local=1`) + await ask(page).fill('https://acme.test', { timeout: 45_000 }) + await expect(offer(page)).toHaveCount(0) + await ask(page).focus() + await page.keyboard.press('Control+k') + await expect(page.getByRole('listbox', { name: 'Commands' }).getByRole('option', { name: /Redesign a site/ })).toHaveCount(0) + await page.keyboard.press('Escape') + // A site-capable host, with the run sent to the cloud workspace instead of this computer. + await page.goto(`${HOST}?local=1&site=ok`) + await page.getByRole('button', { name: /^Where the run runs: / }).click({ timeout: 45_000 }) + await page.getByRole('listbox', { name: 'Where the run runs' }).getByRole('option', { name: /Auto \(Cloud\)/ }).click() + await ask(page).fill('https://acme.test') + await expect(offer(page)).toHaveCount(0) + }) +}) diff --git a/src/host.tsx b/src/host.tsx index c22cab4..6672a43 100644 --- a/src/host.tsx +++ b/src/host.tsx @@ -13,6 +13,7 @@ import type { Cast } from './api/agents.ts' import type { Target } from './api/call.ts' import type { Theme } from './api/pref.ts' import type { Local } from './local.ts' +import type { Site } from './site.ts' export interface Person { name: string @@ -123,6 +124,11 @@ export interface Host { * offers This computer with Auto picking the folder used last. A browser page has no folder of its own: absent. */ local?: Local + /** + * Opening a site, saving a copy of it for the agent, and serving its redesign live in the person's browser (site.ts): + * Hanzo Desktop can, so New on This computer offers to redesign a site from its address. A browser page cannot: absent. + */ + site?: Site } const Context = createContext(null) @@ -152,6 +158,11 @@ export function useLocal(): Local | null { return useContext(Context)?.local ?? null } +/** The host's way of redesigning a site, where the host runs on a computer that can (Hanzo Desktop). */ +export function useSite(): Site | null { + return useContext(Context)?.site ?? null +} + /** The host's browser, where one is mounted and has one. */ export function useBrowser(): Browser | null { return useContext(Context)?.browser ?? null diff --git a/src/index.ts b/src/index.ts index 860ff4d..0373a87 100644 --- a/src/index.ts +++ b/src/index.ts @@ -43,6 +43,7 @@ export type { Limits } from './api/limits.ts' export type { Target } from './api/call.ts' export type { Browse, Browser, Host, Person, Shown } from './host.tsx' export type { Done, Folder, Local } from './local.ts' +export type { Live, Saved, Site } from './site.ts' export type { Session, Status } from './api/sessions.ts' export { mark as markRun, marks as runMarks, useMarks as useRunMarks, type RunMark, type RunMarks } from './runmeta.ts' export { talks } from './api/talk.ts' diff --git a/src/landing.tsx b/src/landing.tsx index f50a70a..b9a2a4f 100644 --- a/src/landing.tsx +++ b/src/landing.tsx @@ -25,7 +25,7 @@ import { SizableText, useMedia, XStack, YStack } from '@hanzo/gui' import { phrase } from '@hanzo/i18n' import { useI18n } from '@hanzo/i18n/react' -import { CircleDot, Cloud, Code, FolderGit2, FolderOpen, GitBranch, Laptop, LayoutTemplate, Link2, Monitor, Play } from '@hanzogui/lucide-icons-2' +import { CircleDot, Cloud, Code, FolderGit2, FolderOpen, GitBranch, Globe, Laptop, LayoutTemplate, Link2, Monitor, Play } from '@hanzogui/lucide-icons-2' import { Button, Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@hanzo/ui' import { Composer, MEASURE, type Command, type Shelf } from '@hanzo/ui/chat' import { BranchSelect, ChipSelect, FooterLink, RepoSelect, type Repo as RowRepo } from '@hanzo/ui/product' @@ -49,9 +49,11 @@ import { asHub, gone, isForge, isHub, settle, type HubRepo } from './choice.ts' import { useCached, useKept, usePlaces, useRead } from './data.ts' import { useDevMode } from './dev-mode.ts' import { takeHandoff } from './handoff.ts' -import { useHost, useLocal, useTarget } from './host.tsx' +import { useHost, useLocal, useSite, useTarget } from './host.tsx' import { failed, HERE, recent, where, type Folder } from './local.ts' import { plainAnswer } from './plain.ts' +import { useRedesign } from './redesign.tsx' +import { urlOf } from './site.ts' import { level, pacing, useMind } from './mind.ts' import { usePrefs } from './prefs.tsx' import { Publish, type Source } from './publish.tsx' @@ -212,6 +214,7 @@ export function Landing({ onStarted }: { onStarted: (session: string) => void }) const [devMode] = useDevMode() const { prefs, save: savePrefs } = usePrefs() const local = useLocal() + const site = useSite() const [stored, keep] = useKept | null>(`hanzo.build.new.${host.org ?? 'none'}`, null) // What was chosen here, over the person's coding defaults (Settings → Code), over // the first run's. Field by field: a codebase or an issue handed over from its own @@ -306,6 +309,21 @@ export function Landing({ onStarted }: { onStarted: (session: string) => void }) // The folders found on the computer arrive after the first read. const [, folded] = useState(0) useEffect(() => local?.changed?.(() => folded((n) => n + 1)), [local]) + // An address pasted here is offered as a redesign of that site (redesign.tsx): the folder the person chose is built in, Auto makes a new one. + const redesign = useRedesign({ + local, + site, + here, + draft, + chosen: folderAt.auto ? null : folderAt.folder, + carried: carry.text, + devMode, + started: () => { + setDraft('') + setFiles([]) + setNote('') + }, + }) // Why this mode cannot run where it is sent: a plan is the sandbox's, on a machine and on this computer alike. const refused = here ? (mode === 'plan' ? t('A plan runs in the cloud workspace. On this computer, switch to Build.') : '') : unhonoured(mode, place.id, t) @@ -389,6 +407,9 @@ export function Landing({ onStarted }: { onStarted: (session: string) => void }) // The composer sends only a draft with words in it, and not while a send is out. const send = async (said: string = draft) => { + // A site's address, alone or asked to be redesigned, starts a redesign (redesign.tsx); any other ask is a run. + const asked = redesign.can ? urlOf(said) : null + if (asked) return void (await redesign.start(asked)) // This computer needs no sign-in to the platform and no repository: the agent runs in the folder, here. if (here && local) return void (await sendHere(said)) if (!signed) { @@ -453,7 +474,7 @@ export function Landing({ onStarted }: { onStarted: (session: string) => void }) * composer when it ends, and what it did only in Developer mode. */ const sendHere = async (said: string) => { - if (!local || busy) return + if (!local || busy || redesign.busy) return if (refused) { setNote(refused) return @@ -770,6 +791,7 @@ export function Landing({ onStarted }: { onStarted: (session: string) => void }) { id: 'projects', label: t('Open projects'), icon: , run: screen('projects') }, { id: 'sync', label: t('Connect GitHub…'), icon: , run: screen('sync') }, { id: 'address', label: t('Use a git URL'), icon: , run: () => setGiving(true) }, + ...(redesign.can ? [{ id: 'redesign', label: t('Redesign a site…'), icon: , run: redesign.ask }] : []), ] // The `+` menu's Connectors shelf gives power users 1-click access to attach a GitHub project even when the composer bar is kept clean. @@ -903,13 +925,14 @@ export function Landing({ onStarted }: { onStarted: (session: string) => void }) {note || refused || mind.note} ) : null} + {redesign.view} {ran ? : null} void send()} - busy={busy} + busy={busy || redesign.busy} placeholder={t('Ask, build, or run anything…')} label={t('Describe a task or ask a question')} plus={{ diff --git a/src/redesign.tsx b/src/redesign.tsx new file mode 100644 index 0000000..0a78812 --- /dev/null +++ b/src/redesign.tsx @@ -0,0 +1,298 @@ +/** + * Redesign a site from its address, in New on This computer (hanzo-inc/app issue 312, hanzoai/desktop issue 15). + * + * An address pasted alone, or with a request to redesign it, is offered as a redesign and never taken for one on its + * own: the offer says what Hanzo will do and one press does it, and an ask that only holds a link is sent as it is + * (site.ts `urlOf`). The steps are the host's and the agent's (site.ts): the host opens the site and saves a copy + * into a folder, serves that folder's `redesign/` live and shows it in Chrome; the agent reads the copy, writes a + * critique as its answer and builds the new site there. The card says which step it is in, the live address, and how + * to open it again; the preview keeps following the folder, so every later run in it shows as it is saved. + */ +import { SizableText, XStack, YStack } from '@hanzo/gui' +import { useI18n } from '@hanzo/i18n/react' +import { ExternalLink, Globe } from '@hanzogui/lucide-icons-2' +import { Button, Dialog, DialogContent, DialogTitle, Input } from '@hanzo/ui' +import { useId, useMemo, useRef, useState, type ReactNode } from 'react' + +import type { Folder, Local } from './local.ts' +import { plainAnswer } from './plain.ts' +import { addressOf, brief, folderName, hostOf, stopped, urlOf, type Asked, type Site } from './site.ts' + +type Stage = 'opening' | 'building' | 'done' | 'failed' + +/** One redesign, as the card shows it. */ +interface Going { + /** The site's address, and what a person calls it. */ + url: string + host: string + /** Where the redesign is built; null until the site is saved. */ + folder: Folder | null + stage: Stage + /** The live address, once it is being served. */ + preview: string | null + /** The agent's critique and summary, once it has finished. */ + output: string + /** What it did on the way, drawn only in Developer mode. */ + process: string + /** How far the agent's first-run setup has got, while the host fetches it. */ + setup: number | null + /** Why it stopped, when it did. */ + why: string +} + +export interface Redesign { + /** The site the draft asks for, when New is where a redesign can start. */ + found: Asked | null + /** Whether a step of one is under way. */ + busy: boolean + /** Start one. False when it could not begin. */ + start: (asked: Asked) => Promise + /** Ask for an address in a dialog, then start. */ + ask: () => void + /** Whether this host can redesign a site at all. */ + can: boolean + /** The offer, the dialog and the card, to draw above the composer. */ + view: ReactNode +} + +export function useRedesign({ + local, + site, + here, + draft, + chosen, + carried, + devMode, + started, +}: { + local: Local | null + site: Site | null + /** New is on This computer. */ + here: boolean + draft: string + /** The folder the person chose themselves, or null for Auto: a chosen folder is built in, Auto makes a new one. */ + chosen: Folder | null + /** What the run carries beside the ask: the skills and memory the person turned on. */ + carried: string + /** Developer mode: the process is drawn as well as the answer. */ + devMode: boolean + /** The ask was taken. */ + started: () => void +}): Redesign { + const { t } = useI18n() + const can = Boolean(site && local && here) + const found = useMemo(() => (can ? urlOf(draft) : null), [can, draft]) + const [going, setGoing] = useState(null) + const [asking, setAsking] = useState(false) + const busy = going?.stage === 'opening' || going?.stage === 'building' + // The folder being served, so a new redesign lets the last one go. + const served = useRef(null) + + const start = async (asked: Asked): Promise => { + if (!site || !local || busy) return false + started() + const host = hostOf(asked.url) + const update = (patch: Partial) => setGoing((g) => (g ? { ...g, ...patch } : g)) + setGoing({ url: asked.url, host, folder: null, stage: 'opening', preview: null, output: '', process: '', setup: null, why: '' }) + try { + if (served.current) { + const last = served.current + served.current = null + await site.stop(last).catch(() => undefined) + } + const folder = chosen ?? (await site.folder(folderName(asked.url))) + const saved = await site.capture(asked.url, folder.path) + // The folder exists now, and is the one Auto picks next: what is said after this goes to the redesign. + local.use(folder.path) + const preview = await site.preview(folder.path) + served.current = folder.path + update({ folder, stage: 'building', preview: preview.url }) + // The preview opens at once, on the page that says the design is being built; a browser that will not open it + // is no reason to stop, and the card has the address and the button. + void site.show(preview.url).catch(() => undefined) + const prompt = [carried, brief(saved, asked.note)].filter(Boolean).join('\n\n') + const done = await local.run(folder.path, prompt, (percent) => update({ setup: percent })) + const answer = { output: done.output.trim(), process: (done.process ?? '').trim() } + update(done.ok ? { stage: 'done', ...answer } : { stage: 'failed', ...answer, why: t('Hanzo Dev stopped before it finished. Try again.') }) + return true + } catch (e) { + update({ stage: 'failed', why: stopped(e, t) }) + return false + } + } + + const show = () => { + if (going?.preview) void site?.show(going.preview).catch(() => undefined) + } + + const view = ( + <> + {found && !busy ? void start(found)} /> : null} + {going ? : null} + {site ? void start({ url, note: '' })} /> : null} + + ) + + return { found, busy, start, ask: () => setAsking(true), can, view } +} + +/** The offer: what Hanzo will do with the address, and the press that does it. */ +function Offer({ host, onStart }: { host: string; onStart: () => void }) { + const { t } = useI18n() + return ( + + + + + + {t('Redesign {site}?', { site: host })} + + + {t('Hanzo opens it, reviews it, and builds a new version here while you watch it in Chrome.')} + + + + + + ) +} + +/** Where a redesign is, step by step, with the live address and what the agent said. */ +function Card({ going, devMode, onShow }: { going: Going; devMode: boolean; onShow: () => void }) { + const { t } = useI18n() + const head = + going.stage === 'opening' + ? t('Opening {site}…', { site: going.host }) + : going.stage === 'building' + ? t('Redesigning {site}…', { site: going.host }) + : going.stage === 'done' + ? t('Redesigned {site}', { site: going.host }) + : t('Could not redesign {site}', { site: going.host }) + const fetching = going.stage === 'building' && going.setup !== null && going.setup < 100 + const said = going.output && going.folder ? plainAnswer(going.output, going.folder, t) : going.output + const step = + going.stage === 'opening' + ? t('Opening the site and saving a copy to work from.') + : going.stage === 'building' + ? t('Reviewing the site and building the new design. The preview changes as the files are saved.') + : going.why + return ( + + + + + {head} + + + {step ? ( + + {step} + + ) : null} + {going.preview ? ( + + + {t('Live preview: {address}', { address: going.preview })} + + + + ) : null} + {going.folder ? ( + + {going.folder.path} + + ) : null} + {fetching ? ( + + {t('Setting up Hanzo Dev on this computer… {percent}%', { percent: going.setup })} + + ) : null} + {said ? ( + + + {said} + + + ) : null} + {devMode && going.process ? ( + + + {t('What Hanzo ran')} + + + {going.process} + + + ) : null} + + ) +} + +/** Asking for an address, for a person who has not pasted one. */ +function Asking({ open, onOpenChange, onStart }: { open: boolean; onOpenChange: (o: boolean) => void; onStart: (url: string) => void }) { + const { t } = useI18n() + const id = useId() + const [value, setValue] = useState('') + const [note, setNote] = useState('') + const close = (o: boolean) => { + if (!o) { + setValue('') + setNote('') + } + onOpenChange(o) + } + const go = () => { + const url = addressOf(value) + if (!url) return setNote(t('Paste a site’s address, like https://example.com.')) + close(false) + onStart(url) + } + return ( + + + {t('Redesign a site')} + + {t('Hanzo opens the site, reviews it, and builds a new version here while you watch it in Chrome.')} + + + + {t('Site address')} + + { + if (e.key === 'Enter') go() + }} + /> + + {note ? ( + + {note} + + ) : null} + + + + + + + ) +} diff --git a/src/site.test.ts b/src/site.test.ts new file mode 100644 index 0000000..31359fb --- /dev/null +++ b/src/site.test.ts @@ -0,0 +1,139 @@ +import { describe, expect, it } from 'vitest' + +import { addressOf, brief, folderName, hostOf, siteName, stopped, urlOf, type Saved } from './site.ts' + +describe('which words are a site (hanzo-inc/app issue 312)', () => { + it('takes an address with a scheme as written', () => { + expect(addressOf('https://example.com/a?b=1#c')).toBe('https://example.com/a?b=1#c') + expect(addressOf('http://example.com')).toBe('http://example.com/') + expect(addressOf('HTTPS://Example.COM')).toBe('https://example.com/') + }) + + it('gives a bare name the scheme a site has', () => { + expect(addressOf('example.com')).toBe('https://example.com/') + expect(addressOf('www.example.co')).toBe('https://www.example.co/') + expect(addressOf('blog.example.dev/posts/1')).toBe('https://blog.example.dev/posts/1') + expect(addressOf('example.com:8443/x')).toBe('https://example.com:8443/x') + }) + + it('takes this computer’s own addresses over http', () => { + expect(addressOf('localhost:3000')).toBe('http://localhost:3000/') + expect(addressOf('127.0.0.1:5173/app')).toBe('http://127.0.0.1:5173/app') + }) + + it('leaves out the punctuation of a sentence', () => { + expect(addressOf('(https://example.com)')).toBe('https://example.com/') + expect(addressOf('"example.com".')).toBe('https://example.com/') + expect(addressOf('https://example.com/a,')).toBe('https://example.com/a') + expect(addressOf('https://en.wikipedia.org/wiki/Foo_(bar)')).toBe('https://en.wikipedia.org/wiki/Foo_(bar)') + expect(addressOf('https://en.wikipedia.org/wiki/Foo_(bar))')).toBe('https://en.wikipedia.org/wiki/Foo_(bar)') + }) + + it('does not take a file name, a path or a word for a site', () => { + for (const no of ['README.md', 'index.html', 'main.rs', 'setup.sh', 'app.js', 'package.json', 'src/index.ts', 'hello', 'a.b', 'v1.2', '1.5', '', ' ', 'localhost', 'example.invalidtld']) { + expect(addressOf(no), no).toBeNull() + } + }) + + it('does not take an address with a login in it, or a scheme the web has not', () => { + for (const no of ['https://user:pw@example.com', 'https://user@example.com', 'file:///etc/passwd', 'ftp://example.com', 'javascript:alert(1)']) { + expect(addressOf(no), no).toBeNull() + } + }) + + it('does not choke on a very long word', () => { + expect(addressOf('a'.repeat(5000) + '.com')).toBeNull() + expect(addressOf('a'.repeat(300) + '!')).toBeNull() + }) +}) + +describe('when an ask is about a site', () => { + it('is an address alone', () => { + expect(urlOf('https://example.com')).toEqual({ url: 'https://example.com/', note: '' }) + expect(urlOf(' example.com ')).toEqual({ url: 'https://example.com/', note: '' }) + expect(urlOf('localhost:3000')).toEqual({ url: 'http://localhost:3000/', note: '' }) + }) + + it('is one address with a request to redesign it, and keeps the rest of what was said', () => { + expect(urlOf('Redesign https://example.com and make it darker')).toEqual({ + url: 'https://example.com/', + note: 'Redesign and make it darker', + }) + expect(urlOf('please redesign example.com.')).toEqual({ url: 'https://example.com/', note: 'please redesign' }) + expect(urlOf('Can you critique www.example.org for me?')).toEqual({ url: 'https://www.example.org/', note: 'Can you critique for me?' }) + expect(urlOf('revamp my site localhost:3000')).toEqual({ url: 'http://localhost:3000/', note: 'revamp my site' }) + }) + + it('is not a message that merely holds a link: that is sent as it is', () => { + expect(urlOf('What is https://example.com?')).toBeNull() + expect(urlOf('See https://example.com/docs for the API')).toBeNull() + expect(urlOf('Fix the typo in README.md')).toBeNull() + expect(urlOf('Add a checkout page')).toBeNull() + expect(urlOf('')).toBeNull() + }) + + it('is not about two sites at once', () => { + expect(urlOf('Redesign example.com and example.org')).toBeNull() + expect(urlOf('example.com example.org')).toBeNull() + }) +}) + +describe('what the redesign is called', () => { + it('names the site by its host without www and its top-level name', () => { + expect(siteName('https://example.com/')).toBe('example') + expect(siteName('https://www.example.com/a')).toBe('example') + expect(siteName('https://blog.example.com')).toBe('blog-example') + expect(siteName('https://shop.example.co.uk')).toBe('shop-example') + expect(siteName('http://localhost:3000')).toBe('localhost') + expect(siteName('http://127.0.0.1:8080')).toBe('localhost') + expect(siteName('http://[::1]:8080/')).toBe('localhost') + expect(siteName('not an address')).toBe('site') + expect(folderName('https://www.hanzo.ai')).toBe('hanzo-redesign') + }) + + it('says a site as a person reads it', () => { + expect(hostOf('https://www.example.com/a/b')).toBe('example.com') + expect(hostOf('http://localhost:3000/')).toBe('localhost:3000') + }) +}) + +describe('what the agent is told', () => { + const saved: Saved = { + title: 'Acme Plumbing', + url: 'https://acme.test/', + files: ['page.html', 'text.md', 'style-1.css', 'screenshot.png'], + screenshot: true, + } + + it('names the site, each file saved, and the two things to do', () => { + const text = brief(saved) + expect(text).toContain('Redesign the website https://acme.test/ (Acme Plumbing).') + expect(text).toContain('- .hanzo/reference/text.md: the site’s address, its words in reading order, and the pictures it shows') + expect(text).toContain('- .hanzo/reference/page.html: the page as the site sent it') + expect(text).toContain('- .hanzo/reference/style-1.css: one of its stylesheets') + expect(text).toContain('- .hanzo/reference/screenshot.png: how the page looks') + expect(text).toContain('1. Critique it.') + expect(text).toContain('2. Rebuild it.') + expect(text).toContain('`redesign/`') + expect(text).toContain('Do not start a server and do not use the network') + expect(text).not.toContain('The person added') + }) + + it('carries what the person said besides the address', () => { + expect(brief(saved, ' make it darker ')).toContain('The person added: “make it darker”') + }) + + it('does not list a picture that was not taken, and does not repeat an address as its own title', () => { + const text = brief({ title: 'https://acme.test/', url: 'https://acme.test/', files: ['page.html', 'text.md'], screenshot: false }) + expect(text).not.toContain('screenshot') + expect(text).toContain('Redesign the website https://acme.test/.') + }) +}) + +describe('when a step stops', () => { + it('says the host’s own words, else that it could not start', () => { + expect(stopped('The site took too long to answer.')).toBe('The site took too long to answer.') + expect(stopped(new Error('Hanzo could not find that site. Check the address and try again.'))).toBe('Hanzo could not find that site. Check the address and try again.') + expect(stopped(undefined)).toBe('The redesign could not start. Try again.') + }) +}) diff --git a/src/site.ts b/src/site.ts new file mode 100644 index 0000000..ad67a44 --- /dev/null +++ b/src/site.ts @@ -0,0 +1,192 @@ +/** + * Redesigning a site from its address (hanzo-inc/app issue 312, hanzoai/desktop issue 15). + * + * A person pastes a site's address into New on This computer. Hanzo opens the site, reads it, critiques it, and + * builds a redesign in a folder here while a live preview of it runs in the person's browser. + * + * THE HOST DOES WHAT THE AGENT CANNOT. The agent that rebuilds the site works in its folder with no network, so the + * host (Hanzo Desktop) opens the site from the computer's own connection and saves a copy into the folder + * (`capture`: the page, its words, its stylesheets, and a picture when the person's browser can take one), serves the + * folder's `redesign/` live (`preview`), and shows it in Chrome (`show`). The agent reads the copy, writes its + * critique as its answer, and writes the new site as static files into `redesign/`; the preview follows each file it + * saves. A host that cannot do this (a browser page) supplies no `Site`, and New offers nothing of it. + * + * Nothing here chooses where a request may go: the host decides what it will open. What is here is the contract, and + * the pure parts of it: which words are a site's address, what the folder is called, and what the agent is told. + */ +import type { Say } from '@hanzo/i18n/react' + +import type { Folder } from './local.ts' +import { english } from './say.ts' + +/** What a host saved of a site, as it says it. */ +export interface Saved { + /** What the site calls itself, or its address. */ + title: string + /** Where the site ended, after any redirects: the address the copy is of. */ + url: string + /** The files saved under `.hanzo/reference/` in the folder, by name. */ + files: readonly string[] + /** Whether one of them is a picture of the page. */ + screenshot: boolean +} + +/** A live preview of a folder's `redesign/`. */ +export interface Live { + /** The address that shows it, on this computer. */ + url: string +} + +/** What a host that can redesign a site can do. Every answer is plain words when it refuses: they are said as they come. */ +export interface Site { + /** The folder a redesign of `name` goes in: a new one, named for it. It is made when the site is saved. */ + folder: (name: string) => Promise + /** Open the site and save a copy of it into `folder`, for the agent to read. */ + capture: (url: string, folder: string) => Promise + /** Serve `folder`'s `redesign/` live; the same address for as long as it runs, reloading as its files change. */ + preview: (folder: string) => Promise + /** Stop serving it. */ + stop: (folder: string) => Promise + /** Show a preview in the person's browser: Chrome where it is installed. */ + show: (url: string) => Promise +} + +/** The top-level names a bare address may end in: the ones people paste. A file name (`index.html`, `README.md`, `main.rs`) is none of them. */ +const TLDS = new Set( + 'com org net io ai app dev co me xyz site shop store online tech design studio agency news blog edu gov info biz us uk ca de fr jp au nz in eu nl se no es it ch be pl br mx cn'.split(' '), +) + +/** The verbs that ask for this with an address in the same sentence. */ +const REDESIGN = /\b(re-?design|re-?build|re-?vamp|re-?style|re-?work|modernis[ez]e|refresh|critique|improve|review)\b/i + +/** A scheme-less address that names this computer: it carries a port, so the word `localhost` alone is not one. */ +const LOCAL = /^(?:localhost|127(?:\.\d{1,3}){3}|\[::1\]):\d{1,5}(?:[/?#]\S*)?$/i + +/** A bare name: labels, a top-level name people paste, an optional port and path. */ +const BARE = /^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+([a-z]{2,24})(?::\d{1,5})?(?:[/?#]\S*)?$/i + +/** What a sentence hangs off the front of an address, and off its end, that is not part of it. */ +const FRONT = /^[(<["'“‘]+/ + +/** An address as written in a sentence: without the brackets, quotes and punctuation round it (a `)` that closes a `(` inside it stays). */ +function bare(word: string): string { + let text = word.trim().replace(FRONT, '') + for (;;) { + const last = text[text.length - 1] + const open = last === ')' && (text.match(/\(/g)?.length ?? 0) >= (text.match(/\)/g)?.length ?? 0) + if (!last || open || !'.,;:!?\'"”’>])'.includes(last)) return text + text = text.slice(0, -1) + } +} + +/** One word as an address, or null. A scheme is taken as written; a bare name must end in a name people paste. */ +export function addressOf(word: string): string | null { + const text = bare(word) + if (!text || text.length > 2048) return null + let full: string + if (/^https?:\/\//i.test(text)) full = text + else if (LOCAL.test(text)) full = `http://${text}` + else { + const m = BARE.exec(text) + if (!m || !TLDS.has(m[1]!.toLowerCase())) return null + full = `https://${text}` + } + try { + const url = new URL(full) + if (!url.hostname || url.username || url.password) return null + if (!url.hostname.includes('.') && !url.hostname.includes(':') && url.hostname !== 'localhost') return null + return url.href + } catch { + return null + } +} + +/** A site named in the ask, and what the person said besides. */ +export interface Asked { + /** The address, whole. */ + url: string + /** The rest of what they said, which goes to the agent as their direction; '' for an address alone. */ + note: string +} + +/** + * The site an ask is about, or null when it is about none. An ask is a site's when it is an address alone, or has one + * address and asks to redesign, rebuild, restyle or critique: anything else is a message that happens to hold a link, + * and is sent as it is. + */ +export function urlOf(ask: string): Asked | null { + const words = ask.trim().split(/\s+/).filter(Boolean) + if (!words.length) return null + const found = words.map((w) => ({ w, url: addressOf(w) })).filter((x) => x.url !== null) + if (words.length === 1) return found[0] ? { url: found[0].url!, note: '' } : null + if (found.length !== 1) return null + const note = words.filter((w) => w !== found[0]!.w).join(' ') + return REDESIGN.test(note) ? { url: found[0]!.url!, note } : null +} + +/** The site's own name: its host without `www.` and its top-level name (`blog.example.com` is `blog-example`). */ +export function siteName(url: string): string { + let host = '' + try { + host = new URL(url).hostname.toLowerCase() + } catch { + return 'site' + } + host = host.replace(/^www\./, '').replace(/^\[|\]$/g, '') + if (host === 'localhost' || host.endsWith('.localhost') || /^[\d.]+$/.test(host) || host.includes(':')) return 'localhost' + const labels = host.split('.') + if (labels.length > 1) labels.pop() + if (labels.length > 1 && ['co', 'com', 'org', 'net', 'ac', 'gov', 'edu'].includes(labels[labels.length - 1]!)) labels.pop() + return labels.join('-').replace(/[^a-z0-9-]+/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '') || 'site' +} + +/** What the redesign's folder is called: `example-redesign`. */ +export function folderName(url: string): string { + return `${siteName(url)}-redesign` +} + +/** What a person reads for a site: its host, without `www.`. */ +export function hostOf(url: string): string { + try { + return new URL(url).host.replace(/^www\./, '') + } catch { + return url + } +} + +/** What each saved file is, in the words the agent is told. */ +function describe(file: string): string { + if (file === 'text.md') return 'the site’s address, its words in reading order, and the pictures it shows' + if (file === 'page.html') return 'the page as the site sent it' + if (/^style-\d+\.css$/.test(file)) return 'one of its stylesheets' + if (/^screenshot\./.test(file)) return 'how the page looks' + return 'saved from the site' +} + +/** + * What the agent is told. It has no network and no browser: it reads the copy the host saved, answers with a plain + * critique, and writes the new site as static files into `redesign/`, which is already being shown. + */ +export function brief(saved: Saved, note = ''): string { + const what = saved.title && saved.title !== saved.url ? `${saved.url} (${saved.title})` : saved.url + const lines = [ + `Redesign the website ${what}.`, + '', + 'The site is saved in this folder for you to read, so you need no network:', + ...saved.files.map((f) => `- .hanzo/reference/${f}: ${describe(f)}`), + '', + 'Do two things.', + '', + '1. Critique it. Begin your answer with a short critique in plain language: what works, what does not, and what you will change, across design, content and usability. Ten lines at most, no jargon.', + '2. Rebuild it. Build the redesigned site as plain static files in the folder `redesign/` here: `index.html`, with its CSS, any scripts and any images beside it, linked by relative paths. Keep the site’s own words and purpose. Improve the layout, type, colour, spacing and clarity, and make it work well on a phone. Pictures may be linked from their own addresses, as text.md lists them. Do not start a server and do not use the network: a live preview of `redesign/` is already open for the person and reloads by itself each time you save a file.', + ] + if (note.trim()) lines.push('', `The person added: “${note.trim()}”`) + lines.push('', 'End by saying, in a sentence or two, what you changed and what to look at first.') + return lines.join('\n') +} + +/** Why a step stopped, in the reader's words: the host's own plain refusals as they come, else this. */ +export function stopped(e: unknown, say: Say = english): string { + const why = typeof e === 'string' ? e : e instanceof Error ? e.message : '' + return why || say('The redesign could not start. Try again.') +}