From 8401945f4d05b90d192a9feab60ab33c6a8ccf6b Mon Sep 17 00:00:00 2001 From: Zach Kelling Date: Fri, 20 Nov 2026 19:33:58 -0800 Subject: [PATCH] @hanzo/build 0.2.136: Auto picks the folder the ask is about; a local run's answer is in words, its process only in Developer mode MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit hanzoai/desktop issues 12, 13, 19. - route(folders, ask): the folder whose name the ask says (then the folders it sits in), else the one used last; same words, same folder. where() takes the ask, so the Folder pill reads Auto · as it is typed. - Local: folders() may arrive after the first read (changed), run() takes a setup callback and answers process beside output. The first run says Setting up Hanzo Dev on this computer… while the host fetches it. - A run on this computer shows what the agent said, in words (plainAnswer: the folder's path is its name, ~ is your home folder); what it did folds behind Developer mode. - failed() no longer sends anyone to npm. - plainPath keeps a sentence's full stop outside the path. Claude-Session: https://claude.ai/code/session_015XYKLn69gF4x75RWePpDBV --- package.json | 2 +- src/e2e/host.tsx | 38 +++++++++++++-- src/e2e/local.spec.ts | 70 +++++++++++++++++++++++++-- src/landing.tsx | 71 +++++++++++++++++++++------- src/local.test.ts | 78 ++++++++++++++++++++++++++++-- src/local.ts | 107 +++++++++++++++++++++++++++++++++++------- src/plain.test.ts | 34 +++++++++++++- src/plain.ts | 36 ++++++++++++-- 8 files changed, 379 insertions(+), 57 deletions(-) diff --git a/package.json b/package.json index abef5cf..4cd7997 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@hanzo/build", - "version": "0.2.135", + "version": "0.2.136", "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 0da6fd4..97192f9 100644 --- a/src/e2e/host.tsx +++ b/src/e2e/host.tsx @@ -14,6 +14,9 @@ * ?at= the address to start at * ?local= the host has the computer (Hanzo Desktop's `local`), with n folders opened already; its folder dialog * answers /Users/dave/picked, and every run it is asked for is written out under the sidebar (Runs on this computer) + * ?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 */ import '@hanzo/font/css' import '@hanzo/ui/theme.css' @@ -30,8 +33,16 @@ const ORG = 'acme' const bearer = () => window.localStorage.getItem('hanzo_iam_access_token') /** A computer with `n` folders opened (the last one used most recently), as Hanzo Desktop's `local` answers. */ -function computer(n: number, ran: (line: string) => void): Local { - let folders: Folder[] = Array.from({ length: n }, (_, i) => ({ path: `/Users/dave/f${i + 1}`, name: `f${i + 1}`, used: i + 1 })) +function computer(n: number, ran: (line: string) => void, names: string[], found: string[], setup: { finish: () => void } | null): Local { + const listeners = new Set<() => void>() + let folders: Folder[] = (names.length ? names : Array.from({ length: n }, (_, i) => `f${i + 1}`)).map((name, i) => ({ path: `/Users/dave/${name}`, name, used: i + 1 })) + if (found.length) { + // Found on the computer, never opened in Hanzo: listed after a moment, in the order the host found them. + setTimeout(() => { + folders = [...folders, ...found.map((name) => ({ path: `/Users/dave/${name}`, name }))] + for (const l of listeners) l() + }, 300) + } const use = (path: string) => { const top = Math.max(0, ...folders.map((f) => f.used ?? 0)) + 1 const known = folders.some((f) => f.path === path) @@ -39,14 +50,25 @@ function computer(n: number, ran: (line: string) => void): Local { } return { folders: () => folders, + changed: (listener) => { + listeners.add(listener) + return () => listeners.delete(listener) + }, pick: async () => { use('/Users/dave/picked') return folders.find((f) => f.path === '/Users/dave/picked') ?? null }, use, - run: async (folder, prompt) => { + run: async (folder, prompt, fetching) => { ran(`${folder} <- ${prompt}`) - return { ok: true, output: `Edited README.md in ${folder}` } + if (setup) { + fetching?.(40) + await new Promise((resolve) => { + setup.finish = resolve + }) + fetching?.(100) + } + return { ok: true, output: `Edited README.md in ${folder}`, process: `exec bash -lc 'ls ~' in ${folder}\n succeeded in 12ms` } }, } } @@ -59,7 +81,12 @@ function Page() { const [width, setWidth] = useState(264) const [shut, setShut] = useState(false) const [ran, setRan] = useState([]) - const [local] = useState(() => (q.has('local') ? computer(Number(q.get('local')) || 0, (line) => setRan((r) => [...r, line])) : undefined)) + const [setup] = useState(() => (q.get('setup') === '1' ? { finish: () => {} } : null)) + const [local] = useState(() => + q.has('local') + ? 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 token = bearer() const host: Host = { name: 'Hanzo', @@ -106,6 +133,7 @@ function Page() { {ran.join(' | ')} + {setup ? setup.finish()}>Finish setup : null} diff --git a/src/e2e/local.spec.ts b/src/e2e/local.spec.ts index 2e9ba16..deb9228 100644 --- a/src/e2e/local.spec.ts +++ b/src/e2e/local.spec.ts @@ -1,8 +1,9 @@ /** * This computer (hanzo-inc/app issues 309 and 310): on a host that has the computer, New offers it first, with Auto - * picking the folder used last; a run there needs no repository and no GitHub, and goes to the host's own runner, - * never to the platform. Driven through the host page (/src/e2e/host.html), whose `?local=` hands the builder a - * computer with n folders. + * picking the folder the ask is about, else the one used last; a run there needs no repository and no GitHub, and + * goes to the host's own runner, never to the platform. What the agent said is drawn in words, and what it did only in + * Developer mode. Driven through the host page (/src/e2e/host.html), whose `?local=` hands the builder a computer + * with n folders. */ import type { Page } from '@playwright/test' @@ -37,7 +38,7 @@ test.describe('This computer', () => { await ask(page).press('Enter') await expect(runs(page)).toHaveText('/Users/dave/f2 <- Fix the typo in the README') await expect(page.locator('[data-slot="ran-here"]')).toContainText('Done in f2') - await expect(page.locator('[data-slot="ran-here"]')).toContainText('Edited README.md in /Users/dave/f2') + await expect(page.locator('[data-slot="ran-here"]')).toContainText('Edited README.md in f2') await expect(ask(page)).toHaveValue('') // Nothing went to the platform: the run is the computer's. expect(platform(sent)).toHaveLength(0) @@ -86,4 +87,65 @@ test.describe('This computer', () => { await chip(page, 'Where the run runs').click({ timeout: 45_000 }) await expect(list(page, 'Where the run runs').getByRole('option', { name: /This computer/ })).toHaveCount(0) }) + + test('Auto follows the ask: the pill names the folder the words are about, live, and Send goes there', async ({ page }) => { + const sent = await quiet(page) + await page.goto(`${HOST}?local=0&folders=shop,docs,blog`) + // Nothing typed: the folder used last. + await expect(chip(page, 'Folder')).toHaveAccessibleName('Folder: Auto · blog', { timeout: 45_000 }) + await ask(page).fill('Fix the checkout button in shop') + await expect(chip(page, 'Folder')).toHaveAccessibleName('Folder: Auto · shop') + await ask(page).fill('Fix the typo in the docs') + await expect(chip(page, 'Folder')).toHaveAccessibleName('Folder: Auto · docs') + await ask(page).press('Enter') + await expect(runs(page)).toHaveText('/Users/dave/docs <- Fix the typo in the docs') + // A folder the person chose is not moved by the words. + await chip(page, 'Folder').click() + await list(page, 'Folder').getByRole('option', { name: /^shop/ }).click() + await ask(page).fill('Write a post on my blog') + await expect(chip(page, 'Folder')).toHaveAccessibleName('Folder: shop') + expect(platform(sent)).toHaveLength(0) + }) + + test('the folders the computer finds later are offered, and Auto can pick one the person never opened', async ({ page }) => { + await quiet(page) + await page.goto(`${HOST}?local=0&folders=blog&found=portfolio`) + await expect(chip(page, 'Folder')).toHaveAccessibleName('Folder: Auto · blog', { timeout: 45_000 }) + await ask(page).fill('Redo my portfolio homepage') + await expect(chip(page, 'Folder')).toHaveAccessibleName('Folder: Auto · portfolio') + await ask(page).press('Enter') + await expect(runs(page)).toHaveText('/Users/dave/portfolio <- Redo my portfolio homepage') + }) + + test('the answer is in words, and the process only in Developer mode', async ({ page }) => { + await quiet(page) + await page.goto(`${HOST}?local=1`) + await ask(page).fill('Add a checkout page') + await ask(page).press('Enter') + const here = page.locator('[data-slot="ran-here"]') + await expect(here).toContainText('Done in f1', { timeout: 45_000 }) + await expect(here.locator('[data-slot="ran-answer"]')).toHaveText('Edited README.md in f1') + await expect(here).not.toContainText('bash -lc') + await expect(here).not.toContainText('~') + await expect(here.locator('[data-slot="ran-process"]')).toHaveCount(0) + // Developer mode shows what the agent did, as it ran it. + await page.evaluate(() => { + window.localStorage.setItem('hanzo.dev_mode', 'true') + window.dispatchEvent(new CustomEvent('hanzo:dev-mode', { detail: { enabled: true } })) + }) + await expect(here.locator('[data-slot="ran-process"]')).toContainText("exec bash -lc 'ls ~' in /Users/dave/f1") + }) + + test('the first run says it is setting Hanzo Dev up, then runs', async ({ page }) => { + await quiet(page) + await page.goto(`${HOST}?local=1&setup=1`) + await ask(page).fill('Add a checkout page') + await ask(page).press('Enter') + const here = page.locator('[data-slot="ran-here"]') + await expect(here.locator('[data-slot="ran-setup"]')).toHaveText('Setting up Hanzo Dev on this computer… 40%', { timeout: 45_000 }) + await expect(here).toContainText('Working in f1…') + await page.getByRole('button', { name: 'Finish setup' }).click() + await expect(here).toContainText('Done in f1') + await expect(here.locator('[data-slot="ran-setup"]')).toHaveCount(0) + }) }) diff --git a/src/landing.tsx b/src/landing.tsx index 445ce51..f50a70a 100644 --- a/src/landing.tsx +++ b/src/landing.tsx @@ -51,6 +51,7 @@ import { useDevMode } from './dev-mode.ts' import { takeHandoff } from './handoff.ts' import { useHost, useLocal, useTarget } from './host.tsx' import { failed, HERE, recent, where, type Folder } from './local.ts' +import { plainAnswer } from './plain.ts' import { level, pacing, useMind } from './mind.ts' import { usePrefs } from './prefs.tsx' import { Publish, type Source } from './publish.tsx' @@ -93,13 +94,16 @@ const FIRST: Kept = { repo: null, branch: '', place: '', folder: '', mode: 'buil /** This computer, as a place: always there on a host that has it. */ const HERE_PLACE: Place = { id: HERE, label: 'This computer', kind: 'here', status: 'online', capacity: '' } -/** What a run on this computer is doing, or did: its folder, its ask, and once it finished, what it printed. */ +/** What a run on this computer is doing, or did: its folder, its ask, and once it finished, what the agent said and did. */ interface Ran { folder: Folder ask: string going: boolean ok: boolean + /** What the agent said at the end. */ output: string + /** What it did on the way: shown in Developer mode only. */ + process: string } /** @@ -146,14 +150,20 @@ export function hold(u: Unsent): void { } } -/** A run on this computer: where it works, what it was asked, and once it ends, what the agent printed. */ -function RanHere({ ran }: { ran: Ran }) { +/** + * A run on this computer: where it works, and once it ends, what the agent said, in words (`plainAnswer`). What it did + * on the way (its commands and what they printed) is drawn only in Developer mode; the first run waits while the host + * fetches the agent, and says so. + */ +function RanHere({ ran, setup, devMode }: { ran: Ran; setup: number | null; devMode: boolean }) { const { t } = useI18n() + const fetching = ran.going && setup !== null && setup < 100 const head = ran.going ? t('Working in {name}…', { name: ran.folder.name }) : ran.ok ? t('Done in {name}', { name: ran.folder.name }) : t('Stopped in {name}', { name: ran.folder.name }) + const said = ran.output ? plainAnswer(ran.output, ran.folder, t) : '' return ( @@ -162,13 +172,29 @@ function RanHere({ ran }: { ran: Ran }) { {head} - - {ran.folder.path} - - {ran.output ? ( + {fetching ? ( + + {t('Setting up Hanzo Dev on this computer… {percent}%', { percent: setup })} + + ) : null} + {said ? ( - - {ran.output} + + {said} + + + ) : !ran.going && !ran.ok ? ( + + {t('Hanzo Dev stopped before it finished. Try again.')} + + ) : null} + {devMode && ran.process ? ( + + + {t('What Hanzo ran')} + + + {ran.process} ) : null} @@ -272,8 +298,14 @@ export function Landing({ onStarted }: { onStarted: (session: string) => void }) const place: Place = here ? SANDBOX : (places.value.find((p) => p.id === kept.place) ?? SANDBOX) // The folders this computer opened, most recent first, and the one a run here goes to: the one chosen, else Auto's. const folders = local ? recent(local.folders()) : [] - const folderAt = where(folders, kept.folder) + // The folder Auto picks is the one the words typed so far are about (local.ts `route`), so the pill says where Send goes. + const folderAt = where(folders, kept.folder, draft) const [ran, setRan] = useState(null) + // How far the agent's first-run setup has got, while the host fetches it. + const [fetched, setFetched] = useState(null) + // The folders found on the computer arrive after the first read. + const [, folded] = useState(0) + useEffect(() => local?.changed?.(() => folded((n) => n + 1)), [local]) // 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) @@ -416,8 +448,9 @@ export function Landing({ onStarted }: { onStarted: (session: string) => void }) } /** - * A run on this computer: in the folder chosen, else Auto's (the one used last), else one the person picks now, once. - * The agent reads, edits and runs there and nowhere else; what it printed is shown under the composer when it ends. + * A run on this computer: in the folder chosen, else Auto's (the one the ask is about, else the one used last), else one + * the person picks now, once. The agent reads, edits and runs there and nowhere else; what it said is shown under the + * composer when it ends, and what it did only in Developer mode. */ const sendHere = async (said: string) => { if (!local || busy) return @@ -425,7 +458,7 @@ export function Landing({ onStarted }: { onStarted: (session: string) => void }) setNote(refused) return } - let folder = folderAt.folder + let folder = where(folders, kept.folder, said).folder if (!folder) { setNote(t('Choose a folder for this run')) folder = await local.pick().catch(() => null) @@ -437,16 +470,18 @@ export function Landing({ onStarted }: { onStarted: (session: string) => void }) const prompt = [carry.text, compose(ask, files)].filter(Boolean).join('\n\n') setBusy(true) setNote('') - setRan({ folder, ask, going: true, ok: true, output: '' }) + setRan({ folder, ask, going: true, ok: true, output: '', process: '' }) + setFetched(null) try { - const done = await local.run(folder.path, prompt) - setRan({ folder, ask, going: false, ok: done.ok, output: done.output.trim() }) + const done = await local.run(folder.path, prompt, setFetched) + setRan({ folder, ask, going: false, ok: done.ok, output: done.output.trim(), process: (done.process ?? '').trim() }) setDraft('') setFiles([]) } catch (e) { setRan(null) setNote(failed(e, t)) } finally { + setFetched(null) setBusy(false) } } @@ -591,7 +626,7 @@ export function Landing({ onStarted }: { onStarted: (session: string) => void }) { id: AUTO, label: t('Auto'), - hint: folders[0] ? t('Last used: {name}', { name: folders[0].name }) : t('The folder you used last'), + hint: t('The folder your ask is about, else the one you used last'), icon: , }, ...folders.map((f) => ({ id: f.path, label: f.name, hint: f.path, icon: })), @@ -868,7 +903,7 @@ export function Landing({ onStarted }: { onStarted: (session: string) => void }) {note || refused || mind.note} ) : null} - {ran ? : null} + {ran ? : null} { expect(named('C:\\work\\api')).toBe('api') }) - it('says how to install the agent when the computer has none, and never asks for a repository', () => { + it('says what stopped a run in the host\'s own plain words, and never sends anyone to a terminal', () => { + const offline = failed(new Error('Hanzo Dev could not be downloaded. Check your internet connection and try again.')) + expect(offline).toBe('Hanzo Dev could not be downloaded. Check your internet connection and try again.') + expect(failed('The folder /Users/me/gone is not on this computer any more. Choose another folder.')).toContain('not on this computer any more') + // A host that never found the agent (an older Desktop) is asked to update, not to install anything. const missing = failed(new Error('Failed to invoke dev at "dev": No such file or directory (os error 2)')) - expect(missing).toContain('npm install -g @hanzo/dev') - expect(missing).not.toMatch(/repositor|github/i) - expect(failed(new Error('permission denied'))).toBe('The run on this computer could not start: permission denied') + expect(missing).toBe('Hanzo Dev is not set up on this computer yet. Update Hanzo Desktop, then send again.') + for (const said of [offline, missing, failed(new Error(''))]) expect(said).not.toMatch(/npm|install -g|terminal|repositor|github/i) + expect(failed(new Error(''))).toBe('The run on this computer could not start. Try again.') }) it("keeps This computer's place id apart from a machine's and the sandbox's", () => { @@ -45,3 +49,67 @@ describe('a folder on this computer (hanzo-inc/app issues 309 and 310)', () => { expect(HERE.startsWith('tgt_')).toBe(false) }) }) + +describe('Auto is the folder the ask is about, else the one used last', () => { + const shop: Folder = { path: '/Users/me/work/shop', name: 'shop', used: 100 } + const blog: Folder = { path: '/Users/me/work/my-blog', name: 'my-blog', used: 300 } + const docs: Folder = { path: '/Users/me/work/acme/docs', name: 'docs', used: 200 } + const web: Folder = { path: '/Users/me/work/acme/web', name: 'web', used: 50 } + const all = [shop, blog, docs, web] + + it('goes to the folder the words name, over the one used last', () => { + expect(route(all, 'Fix the checkout in shop')).toBe(shop) + expect(route(all, 'add a post to my blog')).toBe(blog) + expect(route(all, 'Update the DOCS for the new api')).toBe(docs) + }) + + it('reads a name in the singular or the plural, accents folded, camelCase as two words', () => { + expect(route(all, 'list the shops we have')).toBe(shop) + expect(route([{ path: '/x/Café', name: 'Café' }, blog], 'open the cafe menu')?.name).toBe('Café') + expect(route([{ path: '/x/myShop', name: 'myShop', used: 1 }, blog], 'tidy up my shop page')?.name).toBe('myShop') + }) + + it('falls back to the folder used last when the words name none', () => { + expect(route(all, 'make it faster')).toBe(blog) + expect(route(all, '')).toBe(blog) + expect(route([], 'anything')).toBeNull() + }) + + it('goes to a folder by the folder it sits in when its own name is not said', () => { + expect(route([blog, web], 'redo the acme homepage')).toBe(web) + // A name said beats a place said. + expect(route([docs, web], 'acme web')).toBe(web) + }) + + it('does not take where projects live for which project', () => { + expect(route(all, 'work on my project in the home folder')).toBe(blog) + expect(route([{ path: '/Users/me/code', name: 'code', used: 1 }, shop], 'write some code')).toBe(shop) + }) + + it('prefers the folder it names whole, then the more recent one', () => { + const wide: Folder = { path: '/Users/me/work/shop-site-redesign', name: 'shop-site-redesign', used: 900 } + expect(route([wide, shop], 'fix the shop')).toBe(shop) + const twin: Folder = { path: '/Users/me/old/shop', name: 'shop', used: 10 } + expect(route([twin, shop], 'fix the shop')).toBe(shop) + expect(route([wide, shop], 'redo the shop site redesign')).toBe(wide) + }) + + it('reads a short name only when the whole of it is said', () => { + const ui: Folder = { path: '/Users/me/ui', name: 'ui', used: 1 } + expect(route([ui, blog], 'fix the ui')).toBe(ui) + expect(route([ui, blog], 'build a quick demo')).toBe(blog) + }) + + it('is the same answer every time for the same words', () => { + const once = route(all, 'something about docs and shop') + for (let i = 0; i < 5; i++) expect(route(all, 'something about docs and shop')).toBe(once) + expect(once).toBe(docs) + }) + + it('where() follows the ask only for Auto: a folder chosen stays chosen', () => { + expect(where(all, '', 'fix the shop')).toEqual({ folder: shop, auto: true }) + expect(where(all, '/Users/me/work/shop', 'write a post on my blog')).toEqual({ folder: shop, auto: false }) + expect(where(all, '/Users/me/gone', 'fix the shop')).toEqual({ folder: shop, auto: true }) + expect(where(all, '')).toEqual({ folder: blog, auto: true }) + }) +}) diff --git a/src/local.ts b/src/local.ts index 48caf0d..990f615 100644 --- a/src/local.ts +++ b/src/local.ts @@ -6,10 +6,12 @@ * hands none, and New then offers the cloud workspace and the org's machines as before. Nothing here sniffs a user * agent: the host says what it has. * - * AUTO IS THE FOLDER USED LAST. A person who chose no folder works in the one they worked in most recently, on this - * computer; one who never opened any is asked for one, once, on their first send, and that folder is then the one - * Auto picks. Choosing a folder in the pill keeps it for the next New; choosing Auto again goes back to the most - * recent. That is the whole rule, so a person can always say where a run will go before they send it. + * AUTO IS THE FOLDER THE ASK IS ABOUT, ELSE THE ONE USED LAST (`route`). The folders are the ones Hanzo opened and + * the project folders the host found on the computer; a person who chose no folder works in the one their words + * name ("fix the footer in shop" goes to `shop`), and in the one they worked in most recently when their words + * name none. One who has no folder at all is asked for one, once, on their first send, and that folder is then + * the one Auto picks. Choosing a folder in the pill keeps it for the next New; choosing Auto again goes back to + * the rule. The pill says where the run will go as the words are typed, so a person can always say before they send. * * A run on this computer reads, edits and runs in its folder and nowhere else (the agent's workspace-write sandbox), * and it needs no repository: a folder that is a git checkout keeps its history, and one that is not stays one. @@ -33,20 +35,27 @@ export interface Folder { /** What a run on this computer answers with once it has finished. */ export interface Done { ok: boolean - /** What the agent printed: its answer and what it changed. */ + /** What the agent said at the end: its answer, and what it changed. What a person reads. */ output: string + /** What it did on the way: its commands and what they printed. Drawn only in Developer mode. */ + process?: string } +/** How far the coding agent's setup has got, 0 to 100, while the host fetches it for the first run. */ +export type Setup = (percent: number) => void + /** What a host with the computer can do with its folders. */ export interface Local { - /** The folders this computer has opened in Hanzo, in any order (`recent` sorts them). */ + /** The folders this computer has: the ones opened in Hanzo and the project folders found on it (`recent` sorts them). */ folders: () => readonly Folder[] + /** Hears when `folders` has changed, as the ones found arrive after the first read; answers how to stop hearing. */ + changed?: (listener: () => void) => () => void /** The computer's own folder dialog; null when the person closes it. The folder chosen is kept. */ pick: () => Promise /** Mark a folder as the one used now, so Auto picks it next. */ use: (path: string) => void - /** Run the coding agent in `folder` with `prompt`, and answer once it has finished. */ - run: (folder: string, prompt: string) => Promise + /** Run the coding agent in `folder` with `prompt`, and answer once it has finished. `setup` hears the agent being fetched. */ + run: (folder: string, prompt: string, setup?: Setup) => Promise } /** The place id New keeps for this computer. A machine's is `tgt_…` and the cloud workspace's is ''. */ @@ -65,14 +74,74 @@ export function auto(folders: readonly Folder[]): Folder | null { return recent(folders)[0] ?? null } +/** Names a path says nowhere in particular: where people keep their projects, not which one. */ +const COMMON = new Set([ + 'users', 'user', 'home', 'documents', 'desktop', 'downloads', 'projects', 'project', 'code', 'src', 'source', 'sources', + 'work', 'dev', 'developer', 'repos', 'repo', 'repositories', 'github', 'git', 'workspace', 'workspaces', 'sites', 'mnt', + 'volumes', 'data', 'the', 'and', 'for', 'new', +]) + +/** The words of a text: letters and digits, lower case, accents folded; a camelCase name is two words. */ +function wordsOf(text: string): string[] { + return text + .replace(/([\p{Ll}\p{N}])(\p{Lu})/gu, '$1 $2') + .normalize('NFKD') + .replace(/[\u0300-\u036f]/g, '') + .toLowerCase() + .split(/[^\p{L}\p{N}]+/u) + .filter(Boolean) +} + +/** The words that tell one folder from another: not a place projects live in, and not a letter or two. */ +const telling = (text: string): string[] => wordsOf(text).filter((w) => w.length >= 3 && !COMMON.has(w)) + +/** Whether the ask says `word`, in the singular or the plural. */ +const says = (ask: ReadonlySet, word: string): boolean => ask.has(word) || ask.has(`${word}s`) || (word.endsWith('s') && ask.has(word.slice(0, -1))) + +/** + * The folder an ask is about, else the one used last. + * + * A folder is named by its own name first ("shop", "my-shop"; each word of it the ask says counts, and the + * folder it is all of beats one it is a little of), and then by the folders it sits in (`~/work/acme/web` is + * about "acme"). The ask is read as words: nothing is guessed from what it means, so the same words always go to + * the same folder, and a tie goes to the folder used more recently. An ask that names none goes where Auto + * went before: the folder used last. + */ +export function route(folders: readonly Folder[], ask: string): Folder | null { + const said = new Set(wordsOf(ask)) + const phrase = ` ${[...said].join(' ')} ` + let best: { folder: Folder; score: Score } | null = null + for (const folder of recent(folders)) { + const score = scored(folder, said, phrase) + if (score[0] > 0 && (!best || beats(score, best.score))) best = { folder, score } + } + return best?.folder ?? auto(folders) +} + +/** How well an ask names a folder: how it does so (its own name 2, a folder above it 1, not at all 0), how much of the name it says, and how many words. */ +type Score = readonly [how: number, share: number, words: number] + +const beats = (a: Score, b: Score): boolean => (a[0] !== b[0] ? a[0] > b[0] : a[1] !== b[1] ? a[1] > b[1] : a[2] > b[2]) + +function scored(folder: Folder, said: ReadonlySet, phrase: string): Score { + const own = telling(folder.name) + const hits = own.filter((w) => says(said, w)).length + const whole = wordsOf(folder.name).join(' ') + const distinct = wordsOf(folder.name).some((w) => !COMMON.has(w)) + if (hits > 0 || (distinct && phrase.includes(` ${whole} `))) return [2, own.length ? hits / own.length : 1, hits] + const above = telling(folder.path.replace(/[/\\]+$/, '').split(/[/\\]/).slice(0, -1).join('/')).filter((w) => says(said, w)).length + return above > 0 ? [1, 0, above] : [0, 0, 0] +} + /** - * The folder a run goes to: the one chosen (`kept`, a path), while this computer still lists it, else Auto's. - * A chosen folder the host no longer lists was removed, and is not where the next run goes. + * The folder a run goes to: the one chosen (`kept`, a path), while this computer still lists it, else the one the + * ask is about, else the one used last (`route`). A chosen folder the host no longer lists was removed, and is + * not where the next run goes. */ -export function where(folders: readonly Folder[], kept: string): { folder: Folder | null; auto: boolean } { +export function where(folders: readonly Folder[], kept: string, ask = ''): { folder: Folder | null; auto: boolean } { const chosen = kept ? folders.find((f) => f.path === kept) : undefined if (chosen) return { folder: chosen, auto: false } - return { folder: auto(folders), auto: true } + return { folder: route(folders, ask), auto: true } } /** A folder's last segment, for a path the host gave no name. */ @@ -81,15 +150,17 @@ export function named(path: string): string { } /** - * Why a run on this computer stopped before it began, in the reader's words: the agent is not installed, or the - * host refused. What the agent itself printed is its answer, and is shown as it is. + * Why a run on this computer stopped before it began, in the reader's words. The host fetches the agent itself + * and words what went wrong in plain sentences (no connection, a download that did not check out, a folder that + * is gone), so those are said as they came; a host that could not find the agent at all is told to update. + * What the agent itself printed is its answer, and is shown as it is. */ export function failed(e: unknown, say: Say = english): string { - const why = e instanceof Error ? e.message : typeof e === 'string' ? e : '' - if (/failed to invoke dev|no such file|not found|os error 2|cannot find/i.test(why)) { - return say('The Hanzo Dev agent is not installed on this computer. Install it with `npm install -g @hanzo/dev`, then send again.') + const why = (e instanceof Error ? e.message : typeof e === 'string' ? e : '').trim() + if (/failed to invoke dev|no such file|os error 2|cannot find/i.test(why)) { + return say('Hanzo Dev is not set up on this computer yet. Update Hanzo Desktop, then send again.') } - return why ? say('The run on this computer could not start: {why}', { why }) : say('The run on this computer could not start. Try again.') + return why || say('The run on this computer could not start. Try again.') } /** Words New marks for the reader's language (`phrase`), drawn through `t`. */ diff --git a/src/plain.test.ts b/src/plain.test.ts index 92719bb..1c6a588 100644 --- a/src/plain.test.ts +++ b/src/plain.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest' import { cards, type Card } from './api/turn.ts' -import { doing, fold, isProcess, plainPath, ranOf, worked } from './plain.ts' +import { doing, fold, isProcess, plainAnswer, plainPath, ranOf, worked } from './plain.ts' const said = (key: string, text: string, who: 'person' | 'agent' = 'agent'): Card => ({ kind: 'said', key, who, text }) const shell = (key: string, command: string, ran: 'running' | 'done' = 'done'): Card => ({ kind: 'shell', key, command, output: '', ran }) @@ -89,3 +89,35 @@ describe('result first: the process folds into one plain line (hanzo-inc/app iss ]) }) }) + +describe('what an agent said in a folder, in words', () => { + const folder = { path: '/Users/alex/work/shop', name: 'shop' } + + it('names a file by its folder and the folder by its name', () => { + expect(plainAnswer('I added /Users/alex/work/shop/checkout.html and linked it.', folder)).toBe('I added checkout.html in shop and linked it.') + expect(plainAnswer('Everything is in /Users/alex/work/shop.', folder)).toBe('Everything is in shop.') + expect(plainAnswer('Changed /Users/alex/work/shop/src/app.ts.', folder)).toBe('Changed src/app.ts in shop.') + expect(plainAnswer('(see /Users/alex/work/shop/README.md)', folder)).toBe('(see README.md in shop)') + }) + + it('says the home folder in words and leaves a longer name alone', () => { + expect(plainAnswer('Saved the key to ~/.config/hanzo.', folder)).toBe('Saved the key to .config/hanzo in your home folder.') + expect(plainAnswer('Listed ~ for you', folder)).toBe('Listed your home folder for you') + expect(plainAnswer('Also touched /Users/alex/work/shop2/x.ts', folder)).toBe('Also touched work/shop2/x.ts in your home folder') + }) + + it('reads a Windows folder, either slash', () => { + const win = { path: 'C:\\Users\\alex\\shop', name: 'shop' } + expect(plainAnswer('Wrote C:\\Users\\alex\\shop\\index.html', win)).toBe('Wrote index.html in shop') + expect(plainAnswer('Wrote C:/Users/alex/shop/index.html', win)).toBe('Wrote index.html in shop') + }) + + it('draws through the reader\'s language', () => { + const french = ((s: string, v?: Record) => `fr:${s}${v?.path ? `:${v.path}:${v.folder}` : ''}`) as never + expect(plainAnswer('Made /Users/alex/work/shop/a.ts', folder, french)).toBe('Made fr:{path} in {folder}:a.ts:shop') + }) + + it('leaves a text with no path as it was', () => { + expect(plainAnswer('I made the page faster.', folder)).toBe('I made the page faster.') + }) +}) diff --git a/src/plain.ts b/src/plain.ts index 3274f9c..eb2674c 100644 --- a/src/plain.ts +++ b/src/plain.ts @@ -89,18 +89,44 @@ const WORK = /(^|[\s'"`(=:,])\/work(\/[^\s'"`),;]*)?(?=$|[\s'"`),;:.])/g * project" and `/work/src/app.ts` is "src/app.ts". Anything else is left as written. */ export function plainPath(text: string, say: Say = english): string { - const rest = (tail: string | undefined) => (tail ?? '').replace(/^\/+/, '').replace(/\/+$/, '') + // The path inside a tail, and the sentence's own punctuation after it, which stays where it was written. + const split = (tail: string | undefined): [string, string] => { + const written = (tail ?? '').replace(/^\/+/, '') + const stop = /[.!?:]*$/.exec(written)?.[0] ?? '' + return [written.slice(0, written.length - stop.length).replace(/\/+$/, ''), stop] + } return text .replace(HOME, (_, lead: string, tail?: string) => { - const inside = rest(tail) - return lead + (inside ? say('{path} in your home folder', { path: inside }) : say('your home folder')) + const [inside, stop] = split(tail) + return lead + (inside ? say('{path} in your home folder', { path: inside }) : say('your home folder')) + stop }) .replace(WORK, (_, lead: string, tail?: string) => { - const inside = rest(tail) - return lead + (inside || say('your project')) + const [inside, stop] = split(tail) + return lead + (inside || say('your project')) + stop }) } +/** A text as a pattern that matches it literally. */ +const literal = (text: string): string => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + +/** + * What an agent said after working in a folder, said in words. Paths inside the folder are named by it + * ("checkout.html in shop"), the folder's own path by its name, and the home folder and the sandbox's `/work` + * as `plainPath` says them. Anything else is left as it was written. + */ +export function plainAnswer(text: string, folder: { path: string; name: string }, say: Say = english): string { + const root = folder.path.replace(/[/\\]+$/, '') + if (!root) return plainPath(text, say) + const own = new RegExp(`(^|[\\s'"\`(=:,])${root.split(/[/\\]+/).map(literal).join('[/\\\\]+')}([/\\\\][^\\s'"\`),;]*)?(?=$|[\\s'"\`),;:.!?])`, 'g') + const inside = text.replace(own, (_, lead: string, tail?: string) => { + const written = (tail ?? '').replace(/^[/\\]+/, '') + const stop = /[.!?:]*$/.exec(written)?.[0] ?? '' + const rest = written.slice(0, written.length - stop.length).replace(/[/\\]+$/, '') + return lead + (rest ? say('{path} in {folder}', { path: rest, folder: folder.name }) : folder.name) + stop + }) + return plainPath(inside, say) +} + /** A file's name as a person reads it: the last part of its path, said in words. */ const fileName = (path: string, say: Say): string => { const plain = plainPath(path, say)