diff --git a/package.json b/package.json index 4cd7997..8fd05a6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@hanzo/build", - "version": "0.2.136", + "version": "0.2.137", "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/api/sessions.ts b/src/api/sessions.ts index a5c00f9..ace9263 100644 --- a/src/api/sessions.ts +++ b/src/api/sessions.ts @@ -256,6 +256,11 @@ export async function stop(t: Target, id: string, why = 'Stopped from the builde await call(t, 'POST', `/v1/agent/sessions/${seg(id)}/stop`, { message: why }) } +/** A run, deleted for good: its record and every link it was shared by. */ +export async function remove(t: Target, id: string): Promise { + await call(t, 'DELETE', `/v1/agent/sessions/${seg(id)}`) +} + export async function pause(t: Target, id: string): Promise { await call(t, 'POST', `/v1/agent/sessions/${seg(id)}/pause`, {}) } diff --git a/src/e2e/cov-run.spec.ts b/src/e2e/cov-run.spec.ts index 8f9e338..d5fd203 100644 --- a/src/e2e/cov-run.spec.ts +++ b/src/e2e/cov-run.spec.ts @@ -70,6 +70,51 @@ test('a verdict that does not land is taken back and says why', async ({ page: p await expect(reply.getByRole('button', { name: 'Good result' })).toHaveAttribute('aria-pressed', 'false') }) +test('the run’s menu archives it at once, and deletes it only after a question in the middle of the page', async ({ page: p }, info) => { + const { sent } = await rig(p, { events: told() }) + await p.goto(`/${SESSION}`) + const title = p.getByRole('button', { name: 'Manage this run' }) + await expect(title.getByRole('heading', { name: 'universe: Add the widget' })).toBeVisible({ timeout: 45_000 }) + const marks = () => p.evaluate(() => JSON.parse(localStorage.getItem('hanzo.dev.runs.meta') ?? '{}')) + const gone = () => to(sent, 'DELETE', `/v1/agent/sessions/${SESSION}`).length + + // Delete asks first, names the run, and sits in the middle of the page; Cancel leaves everything as it was. + await title.click() + await p.getByRole('menuitem', { name: 'Delete' }).click() + const ask = p.locator('[data-slot="dialog-content"]') + await expect(ask.getByText('Delete this run?')).toBeVisible() + await expect(ask.getByText(/“universe: Add the widget” is deleted for good|“Add the widget” is deleted for good/)).toBeVisible() + const box = (await ask.boundingBox())! + const view = p.viewportSize()! + expect(Math.abs(box.x + box.width / 2 - view.width / 2), 'centred across').toBeLessThan(8) + expect(Math.abs(box.y + box.height / 2 - view.height / 2), 'centred down').toBeLessThan(80) + await p.screenshot({ path: info.outputPath('delete.png') }) + await ask.getByRole('button', { name: 'Cancel' }).click() + await expect(ask).toHaveCount(0) + expect(gone()).toBe(0) + expect(await marks()).toEqual({}) + + // Confirmed, it is deleted on the platform, marked deleted for every list, and the page leaves it. + await title.click() + await p.getByRole('menuitem', { name: 'Delete' }).click() + await ask.getByRole('button', { name: 'Delete' }).click() + await expect.poll(gone).toBe(1) + await expect.poll(marks).toEqual({ [SESSION]: { deleted: true } }) + await expect(p).not.toHaveURL(new RegExp(SESSION)) +}) + +test('Archive marks the run archived for every list and leaves it, deleting nothing', async ({ page: p }) => { + const { sent } = await rig(p, { events: told() }) + await p.goto(`/${SESSION}`) + const title = p.getByRole('button', { name: 'Manage this run' }) + await expect(title.getByRole('heading', { name: 'universe: Add the widget' })).toBeVisible({ timeout: 45_000 }) + await title.click() + await p.getByRole('menuitem', { name: 'Archive' }).click() + await expect(p).not.toHaveURL(new RegExp(SESSION)) + expect(await p.evaluate(() => JSON.parse(localStorage.getItem('hanzo.dev.runs.meta') ?? '{}'))).toEqual({ [SESSION]: { archived: true } }) + expect(to(sent, 'DELETE', `/v1/agent/sessions/${SESSION}`)).toHaveLength(0) +}) + test('the title is the run’s menu, and Share opens its story and copies its link', async ({ page: p }, info) => { await browser(p, { clipboard: 'keeps' }) const { sent } = await rig(p, { events: told(), record: { ...finished(), project: 'widgets' } }) diff --git a/src/index.ts b/src/index.ts index 2143622..860ff4d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -44,6 +44,7 @@ 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 { 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' export { detect, type Detected } from './api/skills.ts' export { Roles } from './customize/roles.tsx' diff --git a/src/run.tsx b/src/run.tsx index 9a40270..d22ba90 100644 --- a/src/run.tsx +++ b/src/run.tsx @@ -69,14 +69,16 @@ import { useLimits } from '@hanzo/ui/product/useLimits' import { useDictation, useVoice } from '@hanzo/voice' import { useEffect, useMemo, useState } from 'react' +import { Confirm } from './ask.tsx' import { copy as toClipboard } from './clipboard.ts' import { approve, followUp, headline, retry, start, steer, type Ask, type Earlier } from './api/coding.ts' import { limits as readLimits } from './api/models.ts' -import { list, message, pause, publish, rename, resume, stop, story, took } from './api/sessions.ts' +import { list, message, pause, publish, remove, rename, resume, stop, story, took } from './api/sessions.ts' import { answer, cards, followed, outcome, pull, settled, steps } from './api/turn.ts' import { answer as reply, say as talk, talks } from './api/talk.ts' import { verdict } from './api/verdict.ts' import { useKept, useProjects, useRead, useRun, type RunState } from './data.ts' +import { mark } from './runmeta.ts' import { Desk, SEED } from './desk.tsx' import { useDevMode } from './dev-mode.ts' import { KeepAwake, useKeepAwake } from './awake.tsx' @@ -141,6 +143,7 @@ function Job({ id, state: read }: { id: string; state: RunState }) { // The working sandbox run words were said to here: its follow-up opens once it starts. const [steered, setSteered] = useState('') const [naming, setNaming] = useState(false) + const [deleting, setDeleting] = useState(false) const [name, setName] = useState('') const [copied, setCopied] = useState('') const [unfolded, setUnfolded] = useState(false) @@ -765,6 +768,8 @@ function Job({ id, state: read }: { id: string; state: RunState }) { { + // Kept out of every list of runs (the sidebar's too, `runmeta.ts`) and still readable under Archived. + mark(id, { archived: true }) if (running) void stop(t, id, 'Archived').catch(() => undefined) host.go('') }} @@ -778,10 +783,7 @@ function Job({ id, state: read }: { id: string; state: RunState }) { { - if (running) void stop(t, id, 'Deleted').catch(() => undefined) - host.go('') - }} + onSelect={() => setDeleting(true)} > {say('Delete')} @@ -1156,6 +1158,21 @@ function Job({ id, state: read }: { id: string; state: RunState }) { {desk_(false)} ) : null} + { + if (running) await stop(t, id, 'Deleted').catch(() => undefined) + await remove(t, id) + mark(id, { deleted: true }) + host.go('') + }} + /> {say('Rename this run')} diff --git a/src/runmeta.test.ts b/src/runmeta.test.ts new file mode 100644 index 0000000..7deaf6d --- /dev/null +++ b/src/runmeta.test.ts @@ -0,0 +1,61 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { mark, marks, RUNS_EVENT, RUNS_KEY } from './runmeta.ts' + +afterEach(() => vi.unstubAllGlobals()) + +function device(seed: Record = {}, refuses = false) { + const store = new Map(Object.entries(seed)) + const target = new EventTarget() + const said: string[] = [] + vi.stubGlobal('window', { + localStorage: { + getItem: (k: string) => store.get(k) ?? null, + setItem: (k: string, v: string) => { + if (refuses) throw new Error('full') + store.set(k, v) + }, + }, + addEventListener: target.addEventListener.bind(target), + removeEventListener: target.removeEventListener.bind(target), + dispatchEvent: (e: Event) => { + said.push(e.type) + return target.dispatchEvent(e) + }, + }) + return { store, said } +} + +describe('a run’s marks, one store for every list that shows it', () => { + it('reads none where nothing was kept, and where what is kept is not a record', () => { + device() + expect(marks()).toEqual({}) + device({ [RUNS_KEY]: '[1,2]' }) + expect(marks()).toEqual({}) + device({ [RUNS_KEY]: 'not json' }) + expect(marks()).toEqual({}) + }) + + it('marks one run without touching another, and says so on the window', () => { + const { store, said } = device({ [RUNS_KEY]: JSON.stringify({ sess_a: { pinned: true } }) }) + mark('sess_b', { archived: true }) + mark('sess_b', { title: 'Footer' }) + expect(JSON.parse(store.get(RUNS_KEY)!)).toEqual({ sess_a: { pinned: true }, sess_b: { archived: true, title: 'Footer' } }) + expect(said).toEqual([RUNS_EVENT, RUNS_EVENT]) + }) + + it('hands back the same object until something changes, as a store snapshot must', () => { + device({ [RUNS_KEY]: JSON.stringify({ sess_a: { deleted: true } }) }) + const first = marks() + expect(marks()).toBe(first) + mark('sess_a', { archived: true }) + expect(marks()).not.toBe(first) + expect(marks().sess_a).toEqual({ deleted: true, archived: true }) + }) + + it('keeps a change for the page when storage refuses it', () => { + device({}, true) + mark('sess_a', { deleted: true }) + expect(marks().sess_a).toEqual({ deleted: true }) + }) +}) diff --git a/src/runmeta.ts b/src/runmeta.ts new file mode 100644 index 0000000..9cd4c8f --- /dev/null +++ b/src/runmeta.ts @@ -0,0 +1,79 @@ +/** + * What a person did to a run from their own lists: pinned, archived, deleted, renamed. + * + * One store, kept in this browser, for every place that lists or opens a run: the + * sidebar's Recents (hanzoai/app) and a run's own menu here. A run archived or + * deleted from either is gone from the other at once, in this window and in any + * other tab of the browser, because both read and write the same key and say so on + * the window (`RUNS_EVENT`). + */ +import { useCallback, useSyncExternalStore } from 'react' + +export const RUNS_KEY = 'hanzo.dev.runs.meta' +export const RUNS_EVENT = 'hanzo:runs-meta' + +/** One run's own marks; absent means none. */ +export interface RunMark { + title?: string + pinned?: boolean + archived?: boolean + deleted?: boolean +} + +export type RunMarks = Record + +const NONE: RunMarks = {} + +/** What storage held at the last read: the same object until it changes, as a store snapshot must be. */ +let held: { raw: string | null; marks: RunMarks } = { raw: null, marks: NONE } + +/** Every run's marks. Storage that throws, or holds what is not a record, reads as none. */ +export function marks(): RunMarks { + if (typeof window === 'undefined') return NONE + let raw: string | null = null + try { + raw = window.localStorage.getItem(RUNS_KEY) + } catch { + return held.marks + } + if (raw === held.raw) return held.marks + let parsed: unknown = null + try { + parsed = raw === null ? null : JSON.parse(raw) + } catch { + parsed = null + } + held = { raw, marks: parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? (parsed as RunMarks) : NONE } + return held.marks +} + +/** Mark one run: the keys in `patch` replace its own, the rest stay. Said on the window so every list redraws. */ +export function mark(id: string, patch: RunMark): void { + if (typeof window === 'undefined') return + const next: RunMarks = { ...marks(), [id]: { ...marks()[id], ...patch } } + try { + window.localStorage.setItem(RUNS_KEY, JSON.stringify(next)) + } catch { + // Kept for this page only: the change still shows, until the page is left. + held = { raw: held.raw, marks: next } + } + window.dispatchEvent(new Event(RUNS_EVENT)) +} + +function subscribe(changed: () => void): () => void { + const other = (e: StorageEvent) => { + if (e.key === RUNS_KEY || e.key === null) changed() + } + window.addEventListener(RUNS_EVENT, changed) + window.addEventListener('storage', other) + return () => { + window.removeEventListener(RUNS_EVENT, changed) + window.removeEventListener('storage', other) + } +} + +/** The runs' marks, and the way to mark one; the component redraws whenever either place changes them. */ +export function useMarks(): [RunMarks, (id: string, patch: RunMark) => void] { + const all = useSyncExternalStore(subscribe, marks, () => NONE) + return [all, useCallback((id, patch) => mark(id, patch), [])] +}