diff --git a/apps/web/package.json b/apps/web/package.json index 6c3530b..9814ae1 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -7,7 +7,7 @@ "start": "next start -p 3670", "start:dev": "node scripts/dev.mjs", "lint": "biome lint src", - "test": "node --test src/lib/docs-nav.test.mjs src/lib/playback.test.mjs src/lib/launch.test.mjs src/lib/format-bytes.test.mjs src/lib/run-delete.test.mjs src/lib/player-choice.test.mjs src/lib/nav.test.mjs src/lib/crumbs.test.mjs src/lib/theme.test.mjs src/lib/overview-stats.test.mjs src/lib/status.test.mjs src/lib/share-page.test.mjs src/lib/shares.test.mjs src/lib/schedule.test.mjs" + "test": "node --test src/lib/docs-nav.test.mjs src/lib/playback.test.mjs src/lib/launch.test.mjs src/lib/format-bytes.test.mjs src/lib/run-delete.test.mjs src/lib/player-choice.test.mjs src/lib/nav.test.mjs src/lib/crumbs.test.mjs src/lib/theme.test.mjs src/lib/overview-stats.test.mjs src/lib/status.test.mjs src/lib/share-page.test.mjs src/lib/shares.test.mjs src/lib/schedule.test.mjs src/lib/add-project.test.mjs" }, "dependencies": { "@andrewbehma/glass-ui": "0.37.0", diff --git a/apps/web/src/components/projects/add-project-dialog.tsx b/apps/web/src/components/projects/add-project-dialog.tsx new file mode 100644 index 0000000..536d6a8 --- /dev/null +++ b/apps/web/src/components/projects/add-project-dialog.tsx @@ -0,0 +1,334 @@ +'use client'; + +import { Banner } from '@andrewbehma/glass-ui/banner'; +import { Button } from '@andrewbehma/glass-ui/button'; +import { DialogContent, DialogRoot } from '@andrewbehma/glass-ui/dialog'; +import { Field, Input } from '@andrewbehma/glass-ui/field'; +import Link from 'next/link'; +import { useRouter } from 'next/navigation'; +import { useEffect, useId, useReducer, useRef, useState } from 'react'; +import { t } from '@/i18n'; +import { + type AddProjectState, + addProjectReducer, + canAdd, + canCreateConfig, + createInspector, + folderErrorKey, + githubUrlValue, + INITIAL_STATE, + inspectionResult, + isProjectName, + machineChoice, + pathPlaceholder, + preselectMachine, +} from '@/lib/add-project'; +import { + initFolder, + inspectFolder, + type Project, + type Runner, + registerFolder, +} from '@/lib/api'; +import { InspectionPanel } from './add-project/inspection-panel'; +import { MachineField } from './add-project/machine-field'; + +const FORM_ID = 'add-project-form'; + +/** The folder the dialog asks about, numbered as the reducer numbers it. */ +interface Target { + seq: number; + runnerId: string; + path: string; +} + +/** + * Adds a project from a folder on one of the user's machines (spec #379). The + * page remounts it on every open, so it always starts empty. + */ +export function AddProjectDialog({ + open, + onOpenChange, + machines, + projects, +}: { + open: boolean; + onOpenChange: (open: boolean) => void; + machines: Runner[]; + projects: Project[]; +}) { + const router = useRouter(); + const machineId = useId(); + const pathId = useId(); + const nameId = useId(); + const githubId = useId(); + const [runnerId, setRunnerId] = useState(() => + preselectMachine(machines, projects), + ); + const [path, setPath] = useState(''); + // Until typed, the name and the link follow what the machine found. + const [name, setName] = useState(null); + const [githubUrl, setGithubUrl] = useState(null); + const [checked, setChecked] = useState(false); + const [state, dispatch] = useReducer(addProjectReducer, INITIAL_STATE); + const target = useRef({ seq: 0, runnerId, path: '' }); + const [inspector] = useState(() => + createInspector({ + inspect: async (seq) => { + const { runnerId: id, path: folder } = target.current; + if (target.current.seq !== seq) return; + const result = await inspectFolder(id, folder); + dispatch( + result.ok + ? { type: 'inspected', seq, inspection: result.data } + : { type: 'inspect-failed', seq, error: folderErrorKey(result) }, + ); + }, + }), + ); + useEffect(() => inspector.dispose, [inspector]); + + const machine = machines.find((item) => item.id === runnerId); + const inspection = 'inspection' in state ? state.inspection : null; + const nameValue = name ?? inspection?.name ?? ''; + const githubValue = githubUrl ?? inspection?.githubUrl ?? ''; + const nameValid = isProjectName(nameValue); + const githubValid = githubUrlValue(githubValue).ok; + const working = + state.phase === 'initialising' || state.phase === 'registering'; + const showsAdd = + state.phase === 'idle' || + state.phase === 'inspecting' || + state.phase === 'registering' || + canAdd(state); + + /** A new machine or path: a new folder to inspect once typing pauses. */ + function change(nextRunnerId: string, nextPath: string) { + const folder = nextPath.trim(); + const chosen = machines.find((item) => item.id === nextRunnerId); + const ready = + chosen !== undefined && + machineChoice(chosen) === 'ready' && + folder !== ''; + const seq = target.current.seq + 1; + target.current = { seq, runnerId: nextRunnerId, path: folder }; + setName(null); + setGithubUrl(null); + setChecked(false); + dispatch({ type: 'changed', seq, ready }); + inspector.change(seq, ready); + } + + async function createConfig() { + if (!canCreateConfig(state)) return; + const { seq, runnerId: id, path: folder } = target.current; + dispatch({ type: 'init-started', seq }); + const result = await initFolder(id, folder); + dispatch( + result.ok + ? { + type: 'initialised', + seq, + created: result.data.created, + inspection: result.data.inspection, + } + : { type: 'init-failed', seq, error: folderErrorKey(result) }, + ); + } + + async function register() { + if (!canAdd(state)) return; + setChecked(true); + const link = githubUrlValue(githubValue); + if (!nameValid || !link.ok) return; + const { seq, runnerId: id, path: folder } = target.current; + dispatch({ type: 'register-started', seq }); + const result = await registerFolder({ + runnerId: id, + path: folder, + name: nameValue.trim(), + githubUrl: link.url, + }); + if (!result.ok) { + dispatch({ + type: 'register-failed', + seq, + error: folderErrorKey(result), + existingId: + result.code === 'project-exists' ? (result.projectId ?? null) : null, + }); + return; + } + const { id: projectId } = result.data.project; + dispatch({ type: 'registered', seq, projectId }); + router.push(`/app/projects/${encodeURIComponent(projectId)}`); + } + + return ( + { + // A request in flight is not hidden by closing over it. + if (state.phase !== 'registering') onOpenChange(next); + }} + > + + + {machines.length > 0 && showsAdd ? ( + + ) : null} + + } + > + {machines.length === 0 ? ( + + {t('projects.add.machines')} + + } + > + {t('projects.add.noMachines')} + + ) : ( +
{ + event.preventDefault(); + // Enter runs the action the folder offers (Decision 6). + if (canAdd(state)) void register(); + else if (canCreateConfig(state)) void createConfig(); + }} + > + {machines.every((item) => machineChoice(item) !== 'ready') ? ( + {t('projects.add.noReadyMachines')} + ) : null} + { + setRunnerId(value); + change(value, path); + }} + /> + + { + setPath(event.target.value); + change(runnerId, event.target.value); + }} + /> + + + {inspection && inspectionResult(inspection) === 'found' ? ( + <> + + setName(event.target.value)} + /> + + + setGithubUrl(event.target.value)} + /> + + + ) : null} +

+ {announcement(state)} +

+ + )} +
+
+ ); +} + +/** What the status region reads out as the folder is looked at (Decision 6). */ +function announcement(state: AddProjectState): string { + switch (state.phase) { + case 'idle': + case 'done': + return ''; + case 'inspecting': + return t('projects.add.inspecting'); + case 'failed': + return t(state.error); + case 'initialising': + return t('projects.add.creatingConfig'); + case 'registering': + return t('projects.add.submitting'); + } + if (state.error) return t(state.error); + switch (inspectionResult(state.inspection)) { + case 'found': { + const count = state.inspection.scenarios.length; + return `${t('projects.add.found')}. ${ + count === 1 + ? t('projects.add.scenarioCountOne') + : t('projects.add.scenarioCount', { count }) + }`; + } + case 'no-config': + return t('projects.add.noConfig'); + case 'config-invalid': + return t('projects.add.configInvalid'); + } +} diff --git a/apps/web/src/components/projects/add-project/inspection-panel.tsx b/apps/web/src/components/projects/add-project/inspection-panel.tsx new file mode 100644 index 0000000..0970920 --- /dev/null +++ b/apps/web/src/components/projects/add-project/inspection-panel.tsx @@ -0,0 +1,189 @@ +import { Banner } from '@andrewbehma/glass-ui/banner'; +import { Button } from '@andrewbehma/glass-ui/button'; +import { Card } from '@andrewbehma/glass-ui/card'; +import { KeyValueList } from '@andrewbehma/glass-ui/key-value-list'; +import { Spinner } from '@andrewbehma/glass-ui/spinner'; +import { CircleCheck } from 'lucide-react'; +import Link from 'next/link'; +import { t } from '@/i18n'; +import { + type AddProjectState, + type FolderErrorKey, + type FolderInspection, + inspectionResult, + SCENARIOS_SHOWN, +} from '@/lib/add-project'; + +/** Where the allowed folders are documented (spec #380). */ +const ALLOW_DOCS = '/docs/runner#allowed-folders'; + +/** + * What the machine found in the folder (spec #379, Decision 3). It shows only + * the inspection's fields — never a file's content (Decision 5). + */ +export function InspectionPanel({ + state, + onCreateConfig, +}: { + state: AddProjectState; + onCreateConfig: () => void; +}) { + switch (state.phase) { + case 'idle': + case 'done': + return null; + case 'inspecting': + return ( +

+ + {t('projects.add.inspecting')} +

+ ); + case 'failed': + return ; + } + const result = inspectionResult(state.inspection); + return ( +
+ {result === 'found' ? ( + + ) : result === 'no-config' ? ( + + {state.phase === 'initialising' + ? t('projects.add.creatingConfig') + : t('projects.add.createConfig')} + + } + > + {t('projects.add.noConfig')} + + ) : ( + {t('projects.add.configInvalid')} + )} + {state.created && state.created.length > 0 ? ( + + {t('projects.add.createdHint')} + + ) : null} + {state.error ? ( + + ) : null} +
+ ); +} + +function Found({ inspection }: { inspection: FolderInspection }) { + const { scenarios } = inspection; + const shown = scenarios.slice(0, SCENARIOS_SHOWN).map(({ name }) => name); + const more = scenarios.length - shown.length; + return ( + +

+ + + {t('projects.add.found')} + + + {scenarios.length === 1 + ? t('projects.add.scenarioCountOne') + : t('projects.add.scenarioCount', { count: scenarios.length })} + +

+ 0 + ? ` ${t('projects.add.scenarioMore', { count: more })}` + : '', + ].join(''), + }, + ...(inspection.githubUrl + ? [ + { + key: 'github', + label: t('projects.add.github'), + value: ( + + {inspection.githubUrl.replace(/^https:\/\//, '')} + + ), + }, + ] + : []), + ]} + /> +
+ ); +} + +function FolderError({ + error, + existingId, +}: { + error: FolderErrorKey; + existingId: string | null; +}) { + if (error === 'projects.add.errors.pathNotAllowed') { + return ( + + {t('projects.add.allowDocs')} + + } + > + {t(error)}{' '} + {t('projects.add.allowCommand')} + + ); + } + return ( + + {t('projects.add.openExisting')} + + ) : undefined + } + > + {t(error)} + + ); +} diff --git a/apps/web/src/components/projects/add-project/machine-field.tsx b/apps/web/src/components/projects/add-project/machine-field.tsx new file mode 100644 index 0000000..2d52f2a --- /dev/null +++ b/apps/web/src/components/projects/add-project/machine-field.tsx @@ -0,0 +1,74 @@ +import { Field, Select } from '@andrewbehma/glass-ui/field'; +import { StatusPill } from '@andrewbehma/glass-ui/status-pill'; +import { StatusIndicator } from '@/components/status/status-indicator'; +import { t } from '@/i18n'; +import { machineChoice } from '@/lib/add-project'; +import type { Runner } from '@/lib/api'; +import { machineStatus } from '@/lib/status'; + +/** + * The machine picker (spec #379, Decision 2): offline machines and machines + * whose CLI cannot add projects are listed but cannot be chosen. + */ +export function MachineField({ + id, + machines, + value, + disabled, + onChange, +}: { + id: string; + machines: Runner[]; + value: string; + disabled: boolean; + onChange: (runnerId: string) => void; +}) { + const chosen = machines.find((machine) => machine.id === value); + const outdated = machines.some( + (machine) => machineChoice(machine) === 'outdated', + ); + return ( + +
+ + {chosen ? ( + machineChoice(chosen) === 'outdated' ? ( + + ) : ( + + ) + ) : null} +
+
+ ); +} diff --git a/apps/web/src/components/projects/project-list.tsx b/apps/web/src/components/projects/project-list.tsx index 98abd5c..fb7f745 100644 --- a/apps/web/src/components/projects/project-list.tsx +++ b/apps/web/src/components/projects/project-list.tsx @@ -5,15 +5,16 @@ import { Button } from '@andrewbehma/glass-ui/button'; import { Card } from '@andrewbehma/glass-ui/card'; import { ConfirmDialog } from '@andrewbehma/glass-ui/confirm-dialog'; import { EmptyState } from '@andrewbehma/glass-ui/empty-state'; -import { Field, Input, Select } from '@andrewbehma/glass-ui/field'; +import { Input } from '@andrewbehma/glass-ui/field'; +import { Plus } from 'lucide-react'; import Link from 'next/link'; import { useRouter } from 'next/navigation'; -import { type FormEvent, useId, useState } from 'react'; +import { useState } from 'react'; import { StatusIndicator } from '@/components/status/status-indicator'; import { t } from '@/i18n'; +import { isProjectName } from '@/lib/add-project'; import { type ApiResult, - createProject, deleteProject, type Project, type Runner, @@ -24,17 +25,12 @@ import { formatRelative } from '@/lib/format-relative'; import { lastRunStatus } from '@/lib/status'; import type { ErrorKey } from '@/lib/validation'; import { apiErrorKey } from '../auth/form-parts'; +import { GithubMark } from '../auth/github-mark'; +import { AddProjectDialog } from './add-project-dialog'; import { MachinePill } from './machine-pill'; import { StaleBadge } from './stale-badge'; -const NAME_MAX = 200; - -type Failure = - | 'projects.errors.name' - | 'projects.errors.bind' - | 'projects.errors.notFound'; - -type Editing = { id: string; mode: 'rename' | 'bind' }; +type Failure = 'projects.errors.name' | 'projects.errors.notFound'; export function ProjectList({ projects, @@ -44,13 +40,16 @@ export function ProjectList({ machines: Runner[]; }) { const router = useRouter(); - const [editing, setEditing] = useState(null); + const [renaming, setRenaming] = useState(null); const [deleting, setDeleting] = useState(null); const [busy, setBusy] = useState(false); const [error, setError] = useState(); + const [adding, setAdding] = useState(false); + // Every open mounts a fresh dialog, so it never shows the last folder. + const [addKey, setAddKey] = useState(0); function stop() { - setEditing(null); + setRenaming(null); setError(undefined); } @@ -78,44 +77,18 @@ export function ProjectList({ return false; } - async function create(name: string): Promise { - const value = name.trim(); - if (value.length < 1 || [...value].length > NAME_MAX) { - setError('projects.errors.name'); - return false; - } - return run(() => createProject(value), 'projects.errors.name'); - } - async function rename(project: Project, name: string) { - const value = name.trim(); - if (value.length < 1 || [...value].length > NAME_MAX) { + if (!isProjectName(name)) { setError('projects.errors.name'); return; } if ( await run( - () => updateProject(project.id, { name: value }), + () => updateProject(project.id, { name: name.trim() }), 'projects.errors.name', ) ) { - setEditing(null); - } - } - - async function bind(project: Project, runnerId: string, rootPath: string) { - const path = rootPath.trim(); - if (!runnerId || path.length < 1) { - setError('projects.errors.bind'); - return; - } - if ( - await run( - () => updateProject(project.id, { runnerId, rootPath: path }), - 'projects.errors.bind', - ) - ) { - setEditing(null); + setRenaming(null); } } @@ -126,8 +99,19 @@ export function ProjectList({ return (
+
+ +
{error ? {t(error)} : null} - {projects.length === 0 ? (
- {editing?.id === project.id && editing.mode === 'rename' ? ( + {renaming === project.id ? ( )} - {editing?.id === project.id && editing.mode === 'bind' ? ( - bind(project, runnerId, path)} - onCancel={stop} - /> - ) : null}
-
+
+ {project.githubUrl ? ( + + + + ) : null} -
); } @@ -265,36 +250,6 @@ function ProjectSummary({ project }: { project: Project }) { ); } -function CreateForm({ - busy, - onCreate, -}: { - busy: boolean; - onCreate: (name: string) => Promise; -}) { - const [value, setValue] = useState(''); - async function submit(event: FormEvent) { - event.preventDefault(); - if (await onCreate(value)) setValue(''); - } - return ( -
-
- setValue(event.target.value)} - required - /> -
- -
- ); -} - function RenameForm({ project, busy, @@ -339,84 +294,3 @@ function RenameForm({ ); } - -function BindForm({ - project, - machines, - busy, - onBind, - onCancel, -}: { - project: Project; - machines: Runner[]; - busy: boolean; - onBind: (runnerId: string, rootPath: string) => void; - onCancel: () => void; -}) { - const machineId = useId(); - const pathId = useId(); - const [runnerId, setRunnerId] = useState(project.runner?.id ?? ''); - const [path, setPath] = useState(project.rootPath ?? ''); - if (machines.length === 0) { - return ( - - {t('projects.bind.noMachines')}{' '} - - {t('projects.bind.machines')} - - - ); - } - return ( -
{ - event.preventDefault(); - onBind(runnerId, path); - }} - > - - - - - setPath(event.target.value)} - required - /> - -
- - -
-
- ); -} diff --git a/apps/web/src/i18n/en.ts b/apps/web/src/i18n/en.ts index a545b8c..92098a3 100644 --- a/apps/web/src/i18n/en.ts +++ b/apps/web/src/i18n/en.ts @@ -247,17 +247,75 @@ export const en = { loadFailed: 'We could not load your projects. Try again in a moment.', empty: { title: 'No projects yet', - body: 'A project appears when a paired machine runs a scenario in a folder. You can also create one here and bind it to a folder later.', + body: 'A project appears when a paired machine runs a scenario in a folder. You can also add a folder from one of your machines here.', docs: 'Read how to record a first run', }, - create: { - label: 'New project', - placeholder: 'Project name', - submit: 'Create project', - submitting: 'Creating…', + add: { + action: 'Add project', + title: 'Add project', + description: + 'Choose one of your machines and a folder on it. DemoFlow asks the machine what it finds there.', + machine: 'Machine', + machinePlaceholder: 'Choose a machine', + outdated: 'Update the CLI', + optionOffline: '{name} (offline)', + optionOutdated: '{name} (update the CLI)', + outdatedHint: + 'A machine marked “update the CLI” runs an older DemoFlow CLI: update it there and restart its runner to add projects from the website.', + noMachines: 'Pair a machine first, then add a folder from it.', + noReadyMachines: + 'None of your machines can be chosen now: start the runner on one, or update its CLI.', + machines: 'Go to machines', + path: 'Folder', + pathHint: 'The project folder on that machine, as an absolute path.', + inspecting: 'Looking at the folder…', + found: 'demoflow.config.json found', + scenarioCountOne: '1 scenario', + scenarioCount: '{count} scenarios', + scenarioMore: 'and {count} more', + scenarios: 'Scenarios', + noScenarios: 'No scenarios yet', + folderName: 'Folder', + github: 'GitHub', + noConfig: 'This folder has no demoflow.config.json.', + createConfig: 'Create config', + creatingConfig: 'Creating…', + created: 'Created {files}.', + createdHint: + 'Set devCommand and baseUrl in demoflow.config.json in the repository so DemoFlow can start your app.', + configInvalid: + 'This folder has a demoflow.config.json that DemoFlow cannot read. Fix it in the repository, then type the path again.', + allowCommand: 'demoflow runner allow ', + allowDocs: 'How to allow a folder', + name: 'Name', + githubUrl: 'GitHub repository', + githubUrlHint: 'Optional. https://github.com//', + githubUrlInvalid: + 'Enter https://github.com//, or leave it empty.', + submit: 'Add project', + submitting: 'Adding…', + cancel: 'Cancel', + openExisting: 'Open the existing project', + errors: { + pathNotAllowed: + 'This folder is outside the folders this machine allows. On that machine run:', + configMissing: 'This folder has no demoflow.config.json.', + configInvalid: 'The demoflow.config.json in this folder is not valid.', + runnerNotFound: 'This machine is gone. Choose another one.', + runnerOffline: + 'This machine went offline. Start its runner and try again.', + runnerOutdated: + 'Update the CLI on this machine to add projects from the website.', + runnerBusy: 'This machine is busy. Try again in a moment.', + runnerTimeout: 'The machine did not answer in time. Try again.', + runnerError: 'The machine could not do that. Try again.', + projectExists: 'This folder is already a project.', + invalid: 'Check the folder path, the name and the GitHub link.', + }, }, item: { noFolder: 'No folder bound yet', + github: 'Open {name} on GitHub', machineRemoved: 'Machine removed', noRuns: 'No runs yet', runCount: '{count} runs', @@ -270,20 +328,6 @@ export const en = { saving: 'Saving…', cancel: 'Cancel', }, - bind: { - action: 'Bind to a folder', - title: 'Bind “{name}” to a folder', - machine: 'Machine', - machinePlaceholder: 'Choose a machine', - path: 'Absolute folder path', - pathHint: - 'The project root on that machine. If DemoFlow already made a project for this folder, its runs move here and it is removed.', - noMachines: 'Pair a machine first, then bind the project to it.', - machines: 'Go to machines', - submit: 'Bind', - submitting: 'Binding…', - cancel: 'Cancel', - }, delete: { action: 'Delete', title: 'Delete “{name}”?', @@ -291,7 +335,6 @@ export const en = { }, errors: { name: 'Enter a name of 1 to 200 characters.', - bind: 'Choose a machine and enter an absolute folder path.', notFound: 'This project is already gone. The list was refreshed.', }, library: { diff --git a/apps/web/src/lib/add-project.test.mjs b/apps/web/src/lib/add-project.test.mjs new file mode 100644 index 0000000..1bd0ea0 --- /dev/null +++ b/apps/web/src/lib/add-project.test.mjs @@ -0,0 +1,313 @@ +import assert from 'node:assert/strict'; +import { mock, test } from 'node:test'; +import { + addProjectReducer, + canAdd, + canCreateConfig, + createInspector, + folderErrorKey, + githubUrlValue, + INITIAL_STATE, + INSPECT_DELAY_MS, + inspectionResult, + isProjectName, + machineChoice, + pathPlaceholder, + preselectMachine, +} from './add-project.ts'; + +const inspection = { + rootPath: '/home/me/app', + name: 'app', + hasConfig: true, + configValid: true, + scenarios: [{ id: 'demoflow/a.demo.json', name: 'Login' }], + githubUrl: 'https://github.com/me/app', +}; +const noConfig = { + ...inspection, + hasConfig: false, + configValid: false, + scenarios: [], +}; + +/** Runs the events through the reducer from the initial state. */ +function play(...events) { + return events.reduce(addProjectReducer, INITIAL_STATE); +} + +test('only an online machine announcing projects can be chosen', () => { + assert.equal( + machineChoice({ online: true, features: ['projects'] }), + 'ready', + ); + assert.equal( + machineChoice({ online: false, features: ['projects'] }), + 'offline', + ); + assert.equal(machineChoice({ online: true, features: [] }), 'outdated'); + assert.equal(machineChoice({ online: true }), 'outdated'); +}); + +test('the machine of the latest run is preselected when it can be chosen', () => { + const machines = [ + { id: 'a', online: true, features: ['projects'] }, + { id: 'b', online: true, features: ['projects'] }, + { id: 'c', online: false, features: ['projects'] }, + ]; + const run = (runnerId, startedAt) => ({ + runner: { id: runnerId }, + lastRun: { startedAt }, + }); + assert.equal( + preselectMachine(machines, [ + run('a', '2026-10-01T00:00:00Z'), + run('b', '2026-10-02T00:00:00Z'), + ]), + 'b', + ); + // The latest run's machine is offline: the first that can be chosen. + assert.equal( + preselectMachine(machines, [run('c', '2026-10-03T00:00:00Z')]), + 'a', + ); + assert.equal(preselectMachine(machines, []), 'a'); + assert.equal(preselectMachine([machines[2]], []), ''); +}); + +test('the path placeholder follows the machine platform', () => { + assert.equal(pathPlaceholder('win32 10.0.22631'), 'C:\\Users\\you\\my-app'); + assert.equal(pathPlaceholder('darwin 24.1.0'), '/Users/you/my-app'); + assert.equal(pathPlaceholder('linux 6.19.10'), '/home/you/my-app'); + assert.equal(pathPlaceholder(undefined), '/home/you/my-app'); +}); + +test('an inspection is found, without config, or with an invalid one', () => { + assert.equal(inspectionResult(inspection), 'found'); + assert.equal(inspectionResult(noConfig), 'no-config'); + assert.equal( + inspectionResult({ ...inspection, configValid: false }), + 'config-invalid', + ); +}); + +test('every folder error code has its own message', () => { + const expected = { + 'path-not-allowed': 'pathNotAllowed', + 'config-missing': 'configMissing', + 'config-invalid': 'configInvalid', + 'runner-not-found': 'runnerNotFound', + 'runner-offline': 'runnerOffline', + 'runner-outdated': 'runnerOutdated', + 'runner-busy': 'runnerBusy', + 'runner-timeout': 'runnerTimeout', + 'runner-error': 'runnerError', + 'project-exists': 'projectExists', + }; + for (const [code, key] of Object.entries(expected)) { + assert.equal( + folderErrorKey({ error: 'invalid', code }), + `projects.add.errors.${key}`, + ); + } + assert.equal( + folderErrorKey({ error: 'rate_limited' }), + 'auth.errors.rateLimited', + ); + assert.equal( + folderErrorKey({ error: 'invalid' }), + 'projects.add.errors.invalid', + ); + assert.equal(folderErrorKey({ error: 'unknown' }), 'auth.errors.unknown'); +}); + +test('a GitHub link is a repository page or nothing', () => { + assert.deepEqual(githubUrlValue(' '), { ok: true, url: null }); + assert.deepEqual(githubUrlValue(' https://github.com/me/app '), { + ok: true, + url: 'https://github.com/me/app', + }); + for (const bad of [ + 'http://github.com/me/app', + 'https://gitlab.com/me/app', + 'https://user:token@github.com/me/app', + 'https://github.com/me/app/tree/main', + ]) { + assert.deepEqual(githubUrlValue(bad), { ok: false }); + } +}); + +test('a project name is 1 to 200 characters', () => { + assert.equal(isProjectName(' app '), true); + assert.equal(isProjectName(' '), false); + assert.equal(isProjectName('a'.repeat(200)), true); + assert.equal(isProjectName('a'.repeat(201)), false); +}); + +test('a folder with a valid config can be added', () => { + const state = play( + { type: 'changed', seq: 1, ready: true }, + { type: 'inspected', seq: 1, inspection }, + ); + assert.equal(state.phase, 'inspected'); + assert.equal(canAdd(state), true); + assert.equal(canCreateConfig(state), false); + const done = [ + { type: 'register-started', seq: 1 }, + { type: 'registered', seq: 1, projectId: 'p1' }, + ].reduce(addProjectReducer, state); + assert.deepEqual(done, { phase: 'done', seq: 1, projectId: 'p1' }); +}); + +test('a folder without config offers Create config, then is found', () => { + const state = play( + { type: 'changed', seq: 1, ready: true }, + { type: 'inspected', seq: 1, inspection: noConfig }, + ); + assert.equal(canAdd(state), false); + assert.equal(canCreateConfig(state), true); + const created = ['demoflow.config.json', 'demoflow/first.demo.json']; + const after = [ + { type: 'init-started', seq: 1 }, + { type: 'initialised', seq: 1, created, inspection }, + ].reduce(addProjectReducer, state); + assert.equal(after.phase, 'inspected'); + assert.deepEqual(after.created, created); + assert.equal(canAdd(after), true); +}); + +test('an invalid config offers neither action', () => { + const state = play( + { type: 'changed', seq: 1, ready: true }, + { + type: 'inspected', + seq: 1, + inspection: { ...inspection, configValid: false }, + }, + ); + assert.equal(canAdd(state), false); + assert.equal(canCreateConfig(state), false); + assert.equal( + addProjectReducer(state, { type: 'register-started', seq: 1 }), + state, + ); +}); + +test('a refused folder fails with the allow-roots message and no Add', () => { + const state = play( + { type: 'changed', seq: 1, ready: true }, + { + type: 'inspect-failed', + seq: 1, + error: 'projects.add.errors.pathNotAllowed', + }, + ); + assert.deepEqual(state, { + phase: 'failed', + seq: 1, + error: 'projects.add.errors.pathNotAllowed', + }); + assert.equal(canAdd(state), false); +}); + +test('a folder that is already a project offers to open it', () => { + const state = play( + { type: 'changed', seq: 1, ready: true }, + { type: 'inspected', seq: 1, inspection }, + { type: 'register-started', seq: 1 }, + { + type: 'register-failed', + seq: 1, + error: 'projects.add.errors.projectExists', + existingId: 'p0', + }, + ); + assert.equal(state.phase, 'inspected'); + assert.equal(state.error, 'projects.add.errors.projectExists'); + assert.equal(state.existingId, 'p0'); +}); + +test('a stale answer is never shown', () => { + const state = play( + { type: 'changed', seq: 1, ready: true }, + { type: 'changed', seq: 2, ready: true }, + { type: 'inspected', seq: 1, inspection: noConfig }, + ); + assert.deepEqual(state, { phase: 'inspecting', seq: 2 }); + const failed = addProjectReducer(state, { + type: 'inspect-failed', + seq: 1, + error: 'projects.add.errors.pathNotAllowed', + }); + assert.equal(failed, state); + assert.equal( + addProjectReducer(state, { type: 'inspected', seq: 2, inspection }).phase, + 'inspected', + ); +}); + +test('an older change does not undo a newer one', () => { + const state = play( + { type: 'changed', seq: 2, ready: true }, + { type: 'changed', seq: 1, ready: false }, + ); + assert.deepEqual(state, { phase: 'inspecting', seq: 2 }); +}); + +test('clearing the path goes back to idle and drops the pending answer', () => { + const state = play( + { type: 'changed', seq: 1, ready: true }, + { type: 'changed', seq: 2, ready: false }, + { type: 'inspected', seq: 1, inspection }, + ); + assert.deepEqual(state, { phase: 'idle', seq: 2 }); +}); + +test('typing quickly sends one inspection per pause', () => { + mock.timers.enable({ apis: ['setTimeout'] }); + try { + const sent = []; + const inspector = createInspector({ + inspect: async (seq) => { + sent.push(seq); + }, + }); + // Five keystrokes, each within the pause of the one before. + for (let seq = 1; seq <= 5; seq++) { + inspector.change(seq, true); + mock.timers.tick(INSPECT_DELAY_MS - 1); + } + assert.deepEqual(sent, []); + mock.timers.tick(1); + assert.deepEqual(sent, [5]); + // A pause, then two more keystrokes: one more inspection. + inspector.change(6, true); + mock.timers.tick(100); + inspector.change(7, true); + mock.timers.tick(INSPECT_DELAY_MS); + assert.deepEqual(sent, [5, 7]); + } finally { + mock.timers.reset(); + } +}); + +test('an empty path or a disposed dialog sends nothing', () => { + mock.timers.enable({ apis: ['setTimeout'] }); + try { + const sent = []; + const inspector = createInspector({ + inspect: async (seq) => { + sent.push(seq); + }, + }); + inspector.change(1, true); + inspector.change(2, false); + mock.timers.tick(INSPECT_DELAY_MS * 2); + inspector.change(3, true); + inspector.dispose(); + mock.timers.tick(INSPECT_DELAY_MS * 2); + assert.deepEqual(sent, []); + } finally { + mock.timers.reset(); + } +}); diff --git a/apps/web/src/lib/add-project.ts b/apps/web/src/lib/add-project.ts new file mode 100644 index 0000000..109d5fd --- /dev/null +++ b/apps/web/src/lib/add-project.ts @@ -0,0 +1,327 @@ +// Rules of the Add project dialog (spec #379). Plain functions and a reducer, +// so they are unit-tested without a browser. + +/** What the machine found in a folder (spec #377, Decision 5). */ +export interface FolderInspection { + rootPath: string; + name: string; + hasConfig: boolean; + configValid: boolean; + scenarios: { id: string; name: string }[]; + githubUrl: string | null; +} + +/** The pause after the last keystroke before the folder is inspected (Decision 3). */ +export const INSPECT_DELAY_MS = 600; + +/** How many scenario names the inspection shows. */ +export const SCENARIOS_SHOWN = 5; + +export const PROJECT_NAME_MAX = 200; + +/** The API's pattern for a project's GitHub link (spec #378, Decision 1). */ +export const GITHUB_URL_PATTERN = + /^https:\/\/github\.com\/[A-Za-z0-9._-]{1,100}\/[A-Za-z0-9._-]{1,100}$/; + +// Machines. + +export type MachineChoice = 'ready' | 'offline' | 'outdated'; + +/** + * Whether a machine can be chosen (Decision 2): online, and announcing + * `projects`. An API older than spec #378 sends no `features`: outdated. + */ +export function machineChoice(machine: { + online: boolean; + features?: readonly string[]; +}): MachineChoice { + if (!machine.online) return 'offline'; + return machine.features?.includes('projects') ? 'ready' : 'outdated'; +} + +/** + * The machine chosen when the dialog opens: the one that reported the latest + * run when it can be chosen, else the first that can, else none. + */ +export function preselectMachine( + machines: readonly { + id: string; + online: boolean; + features?: readonly string[]; + }[], + projects: readonly { + runner: { id: string } | null; + lastRun: { startedAt: string } | null; + }[], +): string { + const ready = machines.filter( + (machine) => machineChoice(machine) === 'ready', + ); + let latest: { runnerId: string; at: number } | null = null; + for (const project of projects) { + if (!project.runner || !project.lastRun) continue; + const at = Date.parse(project.lastRun.startedAt); + if (latest === null || at > latest.at) { + latest = { runnerId: project.runner.id, at }; + } + } + const last = ready.find((machine) => machine.id === latest?.runnerId); + return (last ?? ready[0])?.id ?? ''; +} + +/** + * The path placeholder in the machine's platform style (Decision 4), from the + * `os` its CLI reported at pairing (`win32 10.0…`, `darwin 24…`, `linux 6…`). + */ +export function pathPlaceholder(os: string | undefined): string { + if (os?.startsWith('win32')) return 'C:\\Users\\you\\my-app'; + if (os?.startsWith('darwin')) return '/Users/you/my-app'; + return '/home/you/my-app'; +} + +// What the inspection means. + +export type InspectionResult = 'found' | 'no-config' | 'config-invalid'; + +export function inspectionResult( + inspection: FolderInspection, +): InspectionResult { + if (!inspection.hasConfig) return 'no-config'; + return inspection.configValid ? 'found' : 'config-invalid'; +} + +export type FolderErrorKey = + | 'projects.add.errors.pathNotAllowed' + | 'projects.add.errors.configMissing' + | 'projects.add.errors.configInvalid' + | 'projects.add.errors.runnerNotFound' + | 'projects.add.errors.runnerOffline' + | 'projects.add.errors.runnerOutdated' + | 'projects.add.errors.runnerBusy' + | 'projects.add.errors.runnerTimeout' + | 'projects.add.errors.runnerError' + | 'projects.add.errors.projectExists' + | 'projects.add.errors.invalid' + | 'auth.errors.rateLimited' + | 'auth.errors.unknown'; + +/** The message for a failed folder call, from its `{ error }` code. */ +export function folderErrorKey(failure: { + error: string; + code?: string; +}): FolderErrorKey { + switch (failure.code) { + case 'path-not-allowed': + return 'projects.add.errors.pathNotAllowed'; + case 'config-missing': + return 'projects.add.errors.configMissing'; + case 'config-invalid': + return 'projects.add.errors.configInvalid'; + case 'runner-not-found': + return 'projects.add.errors.runnerNotFound'; + case 'runner-offline': + return 'projects.add.errors.runnerOffline'; + case 'runner-outdated': + return 'projects.add.errors.runnerOutdated'; + case 'runner-busy': + return 'projects.add.errors.runnerBusy'; + case 'runner-timeout': + return 'projects.add.errors.runnerTimeout'; + case 'runner-error': + return 'projects.add.errors.runnerError'; + case 'project-exists': + return 'projects.add.errors.projectExists'; + } + if (failure.error === 'rate_limited') return 'auth.errors.rateLimited'; + if (failure.error === 'invalid') return 'projects.add.errors.invalid'; + return 'auth.errors.unknown'; +} + +/** A typed GitHub link: empty is none, anything else must be a repository page. */ +export function githubUrlValue( + value: string, +): { ok: true; url: string | null } | { ok: false } { + const url = value.trim(); + if (url === '') return { ok: true, url: null }; + return GITHUB_URL_PATTERN.test(url) ? { ok: true, url } : { ok: false }; +} + +export function isProjectName(value: string): boolean { + const name = value.trim(); + return name.length > 0 && [...name].length <= PROJECT_NAME_MAX; +} + +// The flow (Decision 3). + +/** + * `idle → inspecting → inspected | failed → (initialising → inspected) → + * registering → done`, and back to `inspected` with an error when a step + * fails. `seq` numbers the folder the dialog asks about: every machine or path + * change takes a new one, and an answer for another number is stale. + */ +export type AddProjectState = + | { phase: 'idle'; seq: number } + | { phase: 'inspecting'; seq: number } + | { phase: 'failed'; seq: number; error: FolderErrorKey } + | { + phase: 'inspected' | 'initialising' | 'registering'; + seq: number; + inspection: FolderInspection; + /** Files the dialog's Create config wrote, to say so. */ + created: string[] | null; + error: FolderErrorKey | null; + /** With `project-exists`: the project that holds the folder. */ + existingId: string | null; + } + | { phase: 'done'; seq: number; projectId: string }; + +export type AddProjectEvent = + /** A new machine or path; `ready` when both are set and it is inspected next. */ + | { type: 'changed'; seq: number; ready: boolean } + | { type: 'inspected'; seq: number; inspection: FolderInspection } + | { type: 'inspect-failed'; seq: number; error: FolderErrorKey } + | { type: 'init-started'; seq: number } + | { + type: 'initialised'; + seq: number; + created: string[]; + inspection: FolderInspection; + } + | { type: 'init-failed'; seq: number; error: FolderErrorKey } + | { type: 'register-started'; seq: number } + | { type: 'registered'; seq: number; projectId: string } + | { + type: 'register-failed'; + seq: number; + error: FolderErrorKey; + existingId?: string | null; + }; + +export const INITIAL_STATE: AddProjectState = { phase: 'idle', seq: 0 }; + +export function addProjectReducer( + state: AddProjectState, + event: AddProjectEvent, +): AddProjectState { + if (event.type === 'changed') { + if (event.seq <= state.seq || state.phase === 'done') return state; + return { phase: event.ready ? 'inspecting' : 'idle', seq: event.seq }; + } + // Every other event answers a folder: only the current one counts. + if (event.seq !== state.seq) return state; + switch (event.type) { + case 'inspected': + if (state.phase !== 'inspecting') return state; + return found(state.seq, event.inspection, null); + case 'inspect-failed': + if (state.phase !== 'inspecting') return state; + return { phase: 'failed', seq: state.seq, error: event.error }; + case 'init-started': + if ( + state.phase !== 'inspected' || + inspectionResult(state.inspection) !== 'no-config' + ) { + return state; + } + return { ...state, phase: 'initialising', error: null }; + case 'initialised': + if (state.phase !== 'initialising') return state; + return found(state.seq, event.inspection, event.created); + case 'init-failed': + if (state.phase !== 'initialising') return state; + return { ...state, phase: 'inspected', error: event.error }; + case 'register-started': + if ( + state.phase !== 'inspected' || + inspectionResult(state.inspection) !== 'found' + ) { + return state; + } + return { ...state, phase: 'registering', error: null, existingId: null }; + case 'registered': + if (state.phase !== 'registering') return state; + return { phase: 'done', seq: state.seq, projectId: event.projectId }; + case 'register-failed': + if (state.phase !== 'registering') return state; + return { + ...state, + phase: 'inspected', + error: event.error, + existingId: event.existingId ?? null, + }; + } +} + +function found( + seq: number, + inspection: FolderInspection, + created: string[] | null, +): AddProjectState { + return { + phase: 'inspected', + seq, + inspection, + created, + error: null, + existingId: null, + }; +} + +/** Add project is offered only for a folder with a valid config. */ +export function canAdd(state: AddProjectState): boolean { + return ( + state.phase === 'inspected' && + inspectionResult(state.inspection) === 'found' + ); +} + +/** Create config is offered only for a folder without one. */ +export function canCreateConfig(state: AddProjectState): boolean { + return ( + state.phase === 'inspected' && + inspectionResult(state.inspection) === 'no-config' + ); +} + +// The debounce. + +interface Timers { + setTimeout: (callback: () => void, ms: number) => unknown; + clearTimeout: (handle: unknown) => void; +} + +/** + * Inspects the folder once typing pauses for `delayMs` (Decision 3). Every + * `change` cancels the pending inspection; one already sent answers with its + * own `seq`, which the reducer drops as stale. + */ +export function createInspector(options: { + inspect: (seq: number) => Promise; + delayMs?: number; + timers?: Timers; +}): { change: (seq: number, ready: boolean) => void; dispose: () => void } { + const timers: Timers = options.timers ?? { + setTimeout: (callback, ms) => globalThis.setTimeout(callback, ms), + clearTimeout: (handle) => + globalThis.clearTimeout(handle as ReturnType), + }; + const delayMs = options.delayMs ?? INSPECT_DELAY_MS; + let pending: unknown = null; + + function cancel() { + if (pending !== null) timers.clearTimeout(pending); + pending = null; + } + + return { + change(seq, ready) { + cancel(); + if (!ready) return; + pending = timers.setTimeout(() => { + pending = null; + void options.inspect(seq); + }, delayMs); + }, + dispose: cancel, + }; +} diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts index 5bfe6f5..29528f2 100644 --- a/apps/web/src/lib/api.ts +++ b/apps/web/src/lib/api.ts @@ -2,11 +2,20 @@ // same-origin `/api/…`; a server component passes the API's internal origin // and the request's cookie header instead. +import type { FolderInspection } from './add-project'; + export type ApiError = 'invalid' | 'rate_limited' | 'unknown'; export type ApiResult = | { ok: true; data: T } - | { ok: false; error: ApiError; status?: number; code?: string }; + | { + ok: false; + error: ApiError; + status?: number; + code?: string; + /** With `project-exists`: the project that holds the folder (spec #378). */ + projectId?: string; + }; /** A pending device code, as the signed-in user sees it (spec #135). */ export interface DeviceRequest { @@ -31,6 +40,8 @@ export interface Runner { lastSeenAt: string | null; /** The client IP at connect; shown only to the owner. */ lastSeenIp: string | null; + /** What its current socket can do (`projects`, spec #378); absent on an older API. */ + features?: string[]; } export interface PublicUser { @@ -71,17 +82,27 @@ function errorFor(status: number): ApiError { return 'unknown'; } -/** The `{ error }` code of a failed response, when its body has one. */ -async function errorCode(response: Response): Promise { +/** The `{ error, projectId }` of a failed response, when its body has them. */ +async function errorBody( + response: Response, +): Promise<{ code?: string; projectId?: string }> { try { const body: unknown = await response.json(); - if (typeof body === 'object' && body !== null && 'error' in body) { - return typeof body.error === 'string' ? body.error : undefined; + if (typeof body === 'object' && body !== null) { + const code = + 'error' in body && typeof body.error === 'string' + ? body.error + : undefined; + const projectId = + 'projectId' in body && typeof body.projectId === 'string' + ? body.projectId + : undefined; + return { code, projectId }; } } catch { // No JSON body: the status alone has to do. } - return undefined; + return {}; } export async function request( @@ -108,7 +129,7 @@ export async function request( ok: false, error: errorFor(response.status), status: response.status, - code: await errorCode(response), + ...(await errorBody(response)), }; } const text = await response.text(); @@ -243,6 +264,8 @@ export interface Project { rootPath: string | null; /** Null for a project never bound, or whose machine was revoked. */ runner: { id: string; name: string } | null; + /** `https://github.com//`; absent on an API older than #378. */ + githubUrl?: string | null; runCount: number; /** Scenarios whose latest run failed (spec #362); absent on an older API. */ staleCount?: number; @@ -264,17 +287,10 @@ export function listProjects(target?: Target) { ); } -export function createProject(name: string) { - return request<{ project: Project }>('/projects', { - method: 'POST', - body: { name }, - }); -} - -/** Renames and binds; `runnerId` and `rootPath` come together or not at all. */ +/** Renames, and sets or clears (`null`) the GitHub link (spec #378). */ export function updateProject( id: string, - changes: { name?: string; runnerId?: string; rootPath?: string }, + changes: { name?: string; githubUrl?: string | null }, ) { return request<{ project: Project }>(`/projects/${encodeURIComponent(id)}`, { method: 'PATCH', @@ -288,6 +304,45 @@ export function deleteProject(id: string) { }); } +// Adding a project from a folder on a machine (spec #379, API from #378). + +export interface FolderInit { + /** Files the machine wrote, relative to the folder. */ + created: string[]; + /** Files that were there already and stayed as they were. */ + kept: string[]; + inspection: FolderInspection; +} + +/** What the machine finds in the folder; nothing is stored. */ +export function inspectFolder(runnerId: string, path: string) { + return request('/projects/folders/inspect', { + method: 'POST', + body: { runnerId, path }, + }); +} + +/** Writes the config template into a folder without one. */ +export function initFolder(runnerId: string, path: string) { + return request('/projects/folders/init', { + method: 'POST', + body: { runnerId, path }, + }); +} + +/** Adds the folder as a project; `githubUrl: null` stores no link. */ +export function registerFolder(folder: { + runnerId: string; + path: string; + name: string; + githubUrl: string | null; +}) { + return request<{ project: Project }>('/projects/folders/register', { + method: 'POST', + body: folder, + }); +} + // The run page (spec #193, API contract from spec #191 Decision 9). /** One run with its project and the machine that recorded it. */ diff --git a/demoflow/cards/C-195-feat-web-add-project-dialog-machine-path.demo.json b/demoflow/cards/C-195-feat-web-add-project-dialog-machine-path.demo.json new file mode 100644 index 0000000..288ec72 --- /dev/null +++ b/demoflow/cards/C-195-feat-web-add-project-dialog-machine-path.demo.json @@ -0,0 +1,32 @@ +{ + "schemaVersion": 1, + "name": "Add project dialog", + "description": "Sign in off camera, then open the new Add project dialog from the Projects page: it replaces the old create and bind forms with one place to choose a machine and a folder, and closes with Escape.", + "viewport": { "width": 1280, "height": 720 }, + "setup": [ + { + "action": "include", + "fragment": "sign-in", + "with": { "next": "/app/projects" } + } + ], + "steps": [ + { + "action": "assertVisible", + "target": { "role": "heading", "name": "Projects", "exact": true } + }, + { + "action": "click", + "target": { "role": "button", "name": "Add project", "exact": true } + }, + { + "action": "assertVisible", + "target": { "role": "dialog", "name": "Add project", "exact": true } + }, + { "action": "press", "key": "Escape" }, + { + "action": "assertVisible", + "target": { "role": "heading", "name": "Projects", "exact": true } + } + ] +}