Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(home): draw the hire setup screen with json-render
trohitg9715b696d940
diff --git a/client/eslint.config.js b/client/eslint.config.jsindex 347b49d3..6463d6a0 100644--- a/client/eslint.config.js+++ b/client/eslint.config.js@@ -4,6 +4,9 @@ import reactHooks from 'eslint-plugin-react-hooks'import reactRefresh from 'eslint-plugin-react-refresh'import tseslint from 'typescript-eslint'+const GENUI_PRIVATE =+ 'Import the setup-screen pipeline from features/home/genui (its index) only; its modules are private to that folder.'+export default tseslint.config({ ignores: ['dist'] },{@@ -83,20 +86,28 @@ export default tseslint.config(},// Normal mode's setup-screen pipeline (catalogue, parser, normalizer,// renderer, draft store) is private to its folder: everything else- // imports it through features/home/genui/index.ts.+ // imports it through features/home/genui/index.ts. Only that folder is+ // caught: the shared json-render glue (lib/jsonRender) and other+ // generated-UI folders (features/chat/genui) are free to import.{files: ['src/**/*.{ts,tsx}'],ignores: ['src/features/home/genui/**'],+ rules: {+ 'no-restricted-imports': ['error', { patterns: [{ group: ['**/home/genui/*'], message: GENUI_PRIVATE }] }],+ },+ },+ // Home's own folders reach it relatively ("../genui/catalog"), which the+ // path pattern above cannot see; this block replaces it there.+ {+ files: ['src/features/home/**/*.{ts,tsx}'],+ ignores: ['src/features/home/genui/**'],rules: {'no-restricted-imports': ['error',{patterns: [- {- group: ['**/genui/*'],- message:- 'Import the setup-screen pipeline from features/home/genui (its index) only; its modules are private to that folder.',- },+ { group: ['**/home/genui/*'], message: GENUI_PRIVATE },+ { regex: '^(?:\\./|(?:\\.\\./)+)genui/', message: GENUI_PRIVATE },],},],diff --git a/client/src/features/home/genui/HireDraftPanel.tsx b/client/src/features/home/genui/HireDraftPanel.tsxindex 105a934f..6d2591f2 100644--- a/client/src/features/home/genui/HireDraftPanel.tsx+++ b/client/src/features/home/genui/HireDraftPanel.tsx@@ -4,28 +4,30 @@* has taken so far and Cancel; the screen itself when it arrives; or what* went wrong with a way to try again.*- * Buttons on the screen act through genui/actions: a change request puts- * the composer into editing mode, connect buttons open the provider's- * connect dialog, and Hire goes through useHire. Discard and a finished- * hire collapse the panel before it goes. The screen's layout JSON is a- * developer's view, shown in development builds only.+ * The screen is drawn by json-render (HireScreen, loaded lazily the first+ * time one shows: json-render is not part of Home's first chunk). Its+ * buttons act through genui/actions: a change request puts the composer+ * into editing mode, connect buttons open the provider's connect dialog,+ * and Hire goes through useHire. Discard and a finished hire collapse the+ * panel before it goes. The spec and its patch stream are a developer's+ * view, shown in development builds only.*/-import { Code, X } from 'lucide-react';-import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';+import { X } from 'lucide-react';+import { Suspense, lazy, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';import { ActionButton } from '@/components/ui/action-button';import { Button } from '@/components/ui/button';import { animate, finished } from '@/lib/motion';-import { cn } from '@/lib/utils';import { isConnected, useConnectors } from '../data/connectors';import { useHomeStore } from '../state/homeStore';import { MicroLabel } from '../ui/primitives';import { pillToast } from '../ui/pillToast';-import { runSpecAction, type ConnectCandidate } from './actions';+import type { ConnectCandidate, HireActionContext } from './actions';import { triggerAppNames, useDraftActions, useDraftStore, type DraftFailure } from './draftStore';-import { SpecView } from './render';import { useHire } from './useHire';-import { useReveal } from './useReveal';++const loadHireScreen = () => import('./HireScreen');+const HireScreen = lazy(loadHireScreen);/** After this long, the line says some models take a few minutes. */const SLOW_AFTER_SECONDS = 45;@@ -136,7 +138,6 @@ export function HireDraftPanel({ onConnect }: { onConnect: (providerId: string)const failure = useDraftStore((s) => s.failure);const spec = useDraftStore((s) => s.spec);const intro = useDraftStore((s) => s.intro);- const uiState = useDraftStore((s) => s.uiState);const apps = useDraftStore((s) => s.apps);const version = useDraftStore((s) => s.version);const hiring = useDraftStore((s) => s.hiring);@@ -146,13 +147,16 @@ export function HireDraftPanel({ onConnect }: { onConnect: (providerId: string)const { providers } = useConnectors();const sectionRef = useRef<HTMLElement>(null);const introRef = useRef<HTMLParagraphElement>(null);- const [showJson, setShowJson] = useState(false);const visible = status !== 'idle';const showSpec = Boolean(spec) && (status === 'ready' || (status === 'failed' && failure?.refine));- const revealed = useReveal(showSpec && spec ? spec.order : [], version);const triggerApps = useMemo(() => triggerAppNames(apps), [apps]);+ // Fetch the screen's code while the model writes, so it is there when the reply lands.+ useEffect(() => {+ if (status === 'working') void loadHireScreen();+ }, [status]);+// Enter: rise out of a blur the first time the panel appears.const wasVisible = useRef(false);useLayoutEffect(() => {@@ -208,24 +212,20 @@ export function HireDraftPanel({ onConnect }: { onConnect: (providerId: string)[onConnect, providers],);- const onAction = useCallback(- (action: string, rawParams: unknown) => {- runSpecAction(- action,- rawParams,- { state: useDraftStore.getState().uiState, apps, providers: candidates },- {- setValue: actions.setValue,- refine: () => {- actions.setRefining(true);- useHomeStore.getState().showHire({ focus: true });- },- openConnectors: () => openSettings('connectors'),- connect,- hire: (params) => void hire(params),+ const actionContext = useMemo<HireActionContext>(+ () => ({+ apps,+ providers: candidates,+ actions: {+ refine: () => {+ actions.setRefining(true);+ useHomeStore.getState().showHire({ focus: true });},- );- },+ openConnectors: () => openSettings('connectors'),+ connect,+ hire: (params) => void hire(params),+ },+ }),[actions, apps, candidates, connect, hire, openSettings],);@@ -268,38 +268,16 @@ export function HireDraftPanel({ onConnect }: { onConnect: (providerId: string)</p>)}{showSpec && spec && (- <>- <div className={cn('flex min-w-0 flex-col gap-3', hiring && 'pointer-events-none opacity-60')}>- <SpecView- spec={spec}- state={uiState}- revealed={revealed}- onAction={onAction}- onValue={actions.setValue}- triggerApps={triggerApps}- />- </div>- {import.meta.env.DEV && (- <>- <Button- variant="quiet"- size="xs"- onClick={() => setShowJson((on) => !on)}- title="See the layout the assistant generated"- aria-expanded={showJson}- className="gap-1.5 self-start font-mono text-2xs font-normal text-fg-faint hover:border-border-default hover:bg-transparent hover:text-fg-muted"- >- <Code aria-hidden />- {showJson ? 'Hide layout JSON' : 'Layout JSON'}- </Button>- {showJson && (- <pre className="m-0 max-h-70 overflow-auto rounded-row border border-border-default bg-bg-app px-3.5 py-3 font-mono text-2xs leading-normal whitespace-pre text-fg-muted">- {JSON.stringify(spec, null, 2)}- </pre>- )}- </>- )}- </>+ <Suspense fallback={null}>+ <HireScreen+ key={version}+ spec={spec}+ version={version}+ busy={hiring}+ triggerApps={triggerApps}+ actions={actionContext}+ />+ </Suspense>)}</div></section>diff --git a/client/src/features/home/genui/HireScreen.tsx b/client/src/features/home/genui/HireScreen.tsxnew file mode 100644index 00000000..f2b49b8d--- /dev/null+++ b/client/src/features/home/genui/HireScreen.tsx@@ -0,0 +1,72 @@+/**+ * The setup screen itself, drawn by json-render from the hire catalogue+ * (registry.ts). HireDraftPanel loads it lazily, the first time a screen+ * shows, so json-render stays out of Home's first chunk; it renders one per+ * version of the draft (keyed by it), so a new version starts afresh.+ *+ * The screen keeps its own state store (lib/jsonRender/uiState.ts), seeded+ * from the draft (what the model wrote, plus anything the owner already+ * changed on this version), and every change goes back to the draft+ * (setDraftValue), which Hire reads. Buttons run the hire actions+ * (actions.ts); setState is json-render's own. The screen appears one+ * element at a time (useSpecReveal) and each element rises in once.+ * Development builds also show the spec and its patch stream.+ */++import { useLayoutEffect, useMemo, useRef, useState } from 'react';+import type { Spec } from '@json-render/core';+import { JSONUIProvider, Renderer } from '@json-render/react';+import { LiveUiContext, SpecInspector, createUiStateStore, useSpecReveal } from '@/lib/jsonRender';+import { cn } from '@/lib/utils';+import { hireActionHandlers, type HireActionContext } from './actions';+import { setDraftValue, useDraftStore } from './draftStore';+import { HireSpecContext } from './hireSpecContext';+import type { NormalizedSpec } from './normalize';+import { hireRegistry } from './registry';++export interface HireScreenProps {+ spec: NormalizedSpec;+ version: number;+ /** A hire is in flight: the screen dims and takes no input. */+ busy: boolean;+ /** Apps that can start the work: any name the reply used -> the app's own name. */+ triggerApps: Readonly<Record<string, string>>;+ /** What the buttons reach on Home; read at each press. */+ actions: HireActionContext;+}++/** Unknown types are dropped by the normaliser; anything else renders nothing. */+function NoElement() {+ return null;+}++export default function HireScreen({ spec, version, busy, triggerApps, actions }: HireScreenProps) {+ const uiSpec = useMemo<Spec>(() => ({ root: spec.root, state: spec.state, elements: spec.elements }), [spec]);+ const { spec: shown, revealing } = useSpecReveal(uiSpec, version);+ const [store] = useState(() =>+ createUiStateStore(useDraftStore.getState().uiState, (changes) => {+ for (const { path, value } of changes) setDraftValue(path, value);+ }),+ );+ const latest = useRef(actions);+ useLayoutEffect(() => {+ latest.current = actions;+ });+ const [handlers] = useState(() => hireActionHandlers(() => latest.current));+ const context = useMemo(() => ({ writtenState: spec.state, triggerApps }), [spec.state, triggerApps]);++ return (+ <>+ <div className={cn('flex min-w-0 flex-col gap-3', busy && 'pointer-events-none opacity-60')}>+ <HireSpecContext.Provider value={context}>+ <LiveUiContext.Provider value>+ <JSONUIProvider registry={hireRegistry} store={store} handlers={handlers}>+ <Renderer spec={shown} registry={hireRegistry} loading={revealing} fallback={NoElement} />+ </JSONUIProvider>+ </LiveUiContext.Provider>+ </HireSpecContext.Provider>+ </div>+ {import.meta.env.DEV && <SpecInspector spec={uiSpec} />}+ </>+ );+}diff --git a/client/src/features/home/genui/MessagePreview.tsx b/client/src/features/home/genui/MessagePreview.tsxnew file mode 100644index 00000000..cd5ff8ce--- /dev/null+++ b/client/src/features/home/genui/MessagePreview.tsx@@ -0,0 +1,34 @@+/**+ * A message waiting to go out: the channel, who it is for, the text. The+ * setup screen's Draft shows one, and so does the approval step (the+ * employee page's "Waiting for you", as DraftMessagePreview). It lives on+ * its own so the employee page does not load the setup screen's renderer.+ */++import { cn } from '@/lib/utils';+import { MicroLabel } from '../ui/primitives';++export function MessagePreview({+ channel,+ to,+ subject,+ body,+ className,+}: {+ channel?: string;+ to?: string;+ subject?: string;+ body: string;+ className?: string;+}) {+ return (+ <div className={cn('overflow-hidden rounded-card border border-border-default bg-bg-elevated', className)}>+ <div className="flex items-center gap-2 border-b border-border-default bg-bg-panel px-3.5 py-2.5">+ <MicroLabel className="text-node-model-ink">{channel || 'Draft'}</MicroLabel>+ <span className="truncate text-sm text-fg-muted">to {to || '…'}</span>+ </div>+ {subject && <div className="px-3.5 pt-3 text-base font-semibold text-fg-default">{subject}</div>}+ <div className="px-3.5 pt-2.5 pb-3.5 text-base leading-relaxed whitespace-pre-wrap text-fg-default">{body}</div>+ </div>+ );+}diff --git a/client/src/features/home/genui/__fixtures__/replies.json b/client/src/features/home/genui/__fixtures__/replies.jsonindex 530004a1..9a7372a5 100644--- a/client/src/features/home/genui/__fixtures__/replies.json+++ b/client/src/features/home/genui/__fixtures__/replies.json@@ -198,5 +198,68 @@"expect": {"metricValue": ""}+ },+ {+ "name": "json-render shape: on.press and checked",+ "reply": "{\"text\":\"Meet Maya, your new receptionist.\",\"spec\":{\"root\":\"a\",\"state\":{\"rules\":{\"askFirst\":true,\"hours\":false},\"choices\":{\"report\":\"Daily\"}},\"elements\":{\"a\":{\"type\":\"Stack\",\"props\":{\"direction\":\"vertical\",\"gap\":\"md\"},\"children\":[\"b\",\"c\",\"d\",\"e\"]},\"b\":{\"type\":\"AgentCard\",\"props\":{\"name\":\"Maya\",\"role\":\"Receptionist\",\"description\":\"Answers WhatsApp and books visits.\",\"apps\":[\"WhatsApp\",\"Google Calendar\"],\"status\":\"ready\"},\"children\":[]},\"c\":{\"type\":\"Plan\",\"props\":{\"title\":\"Their routine\",\"steps\":[{\"title\":\"When a message arrives\",\"detail\":\"On WhatsApp\",\"role\":\"trigger\",\"app\":\"WhatsApp\"},{\"title\":\"Answer the question\",\"detail\":\"Using your notes\",\"role\":\"agent\"},{\"title\":\"Book the visit\",\"detail\":\"In your calendar\",\"role\":\"tool\",\"app\":\"Google Calendar\"}]},\"children\":[]},\"d\":{\"type\":\"Card\",\"props\":{\"title\":\"Ground rules\"},\"children\":[\"f\",\"g\",\"h\"]},\"f\":{\"type\":\"Toggle\",\"props\":{\"label\":\"Ask me before sending anything\",\"checked\":{\"$bindState\":\"/rules/askFirst\"}},\"children\":[]},\"g\":{\"type\":\"Toggle\",\"props\":{\"label\":\"Only reply 9 to 6\",\"checked\":{\"$bindState\":\"/rules/hours\"}},\"children\":[]},\"h\":{\"type\":\"Choice\",\"props\":{\"label\":\"Report\",\"options\":[\"Daily\",\"Weekly\"],\"value\":{\"$bindState\":\"/choices/report\"}},\"children\":[]},\"e\":{\"type\":\"Stack\",\"props\":{\"direction\":\"horizontal\",\"gap\":\"md\"},\"children\":[\"i\",\"j\"]},\"i\":{\"type\":\"Button\",\"props\":{\"label\":\"Hire Maya\",\"variant\":\"primary\"},\"on\":{\"press\":{\"action\":\"hire_employee\",\"params\":{\"name\":\"Maya\",\"role\":\"Receptionist\",\"apps\":[\"WhatsApp\",\"Google Calendar\"],\"trigger\":{\"kind\":\"app_event\",\"app\":\"WhatsApp\"},\"sendsVia\":\"WhatsApp\"}}},\"children\":[]},\"j\":{\"type\":\"Button\",\"props\":{\"label\":\"Change something\",\"variant\":\"secondary\"},\"on\":{\"press\":{\"action\":\"refine\"}},\"children\":[]}}}}",+ "salvageable": true,+ "expect": {+ "text": "Meet Maya, your new receptionist.",+ "hasAgent": "Maya",+ "hireButtons": 1,+ "refineButtons": 1,+ "askFirstToggles": 1,+ "sameAs": "clean minified reply"+ }+ },+ {+ "name": "on.press as a list, the first action unknown",+ "reply": "{\"text\":\"Ivy keeps your diary.\",\"spec\":{\"root\":\"r\",\"elements\":{\"r\":{\"type\":\"Stack\",\"props\":{\"direction\":\"vertical\"},\"children\":[\"a\",\"row\"]},\"a\":{\"type\":\"AgentCard\",\"props\":{\"name\":\"Ivy\",\"role\":\"Diary keeper\",\"apps\":[\"Google Calendar\"]}},\"row\":{\"type\":\"Stack\",\"props\":{\"direction\":\"horizontal\"},\"children\":[\"h\",\"c\"]},\"h\":{\"type\":\"Button\",\"props\":{\"label\":\"Hire Ivy\",\"variant\":\"primary\"},\"on\":{\"press\":[{\"action\":\"wave\"},{\"action\":\"hire_employee\",\"params\":{\"name\":\"Ivy\",\"trigger\":{\"kind\":\"schedule\",\"every\":\"weekday\",\"at\":\"08:00\"}}}]}},\"c\":{\"type\":\"Button\",\"props\":{\"label\":\"Change something\"},\"on\":{\"press\":{\"action\":\"ask\",\"params\":{\"text\":\"Only mornings\"}}}}}}}",+ "salvageable": true,+ "expect": {+ "hasAgent": "Ivy",+ "hireLabel": "Hire Ivy",+ "refineHasNoParams": true,+ "trigger": {+ "kind": "schedule",+ "every": "weekday",+ "at": "08:00"+ }+ }+ },+ {+ "name": "on written inside props",+ "reply": "{\"text\":\"Tom answers email.\",\"spec\":{\"root\":\"r\",\"elements\":{\"r\":{\"type\":\"Stack\",\"props\":{\"direction\":\"vertical\"},\"children\":[\"a\",\"row\"]},\"a\":{\"type\":\"AgentCard\",\"props\":{\"name\":\"Tom\",\"role\":\"Email helper\",\"apps\":[\"Gmail\"]}},\"row\":{\"type\":\"Stack\",\"props\":{\"direction\":\"horizontal\"},\"children\":[\"h\"]},\"h\":{\"type\":\"Button\",\"props\":{\"label\":\"Hire Tom\",\"variant\":\"primary\",\"on\":{\"press\":{\"action\":\"hire_employee\",\"params\":{\"name\":\"Tom\"}}}}}}}}",+ "salvageable": true,+ "expect": {+ "hasAgent": "Tom",+ "hireLabel": "Hire Tom"+ }+ },+ {+ "name": "buttons whose on.press names no known action",+ "reply": "{\"text\":\"Nope.\",\"spec\":{\"root\":\"r\",\"elements\":{\"b1\":{\"type\":\"Button\",\"props\":{\"label\":\"Go\"},\"on\":{\"press\":{\"action\":\"delete_everything\"}}},\"b2\":{\"type\":\"Button\",\"props\":{\"label\":\"Stop\"},\"on\":{\"press\":[{\"action\":\"pushState\"}]}}}}}",+ "salvageable": false+ },+ {+ "name": "prototype paths in expressions",+ "reply": "{\"text\":\"Paths.\",\"spec\":{\"root\":\"r\",\"state\":{\"rules\":{\"askFirst\":false}},\"elements\":{\"r\":{\"type\":\"Stack\",\"props\":{\"direction\":\"vertical\"},\"children\":[\"a\",\"t\",\"x\",\"rules\",\"row\"]},\"a\":{\"type\":\"AgentCard\",\"props\":{\"name\":\"Rex\",\"role\":\"Helper\",\"description\":{\"$state\":\"/__proto__/polluted\"}}},\"t\":{\"type\":\"Text\",\"props\":{\"text\":{\"$template\":\"Hi ${/constructor/name} and ${/rules/askFirst}\"}},\"visible\":{\"$state\":\"/prototype/x\"}},\"x\":{\"type\":\"Text\",\"props\":{\"text\":\"Shown\"},\"visible\":[{\"$state\":\"/rules/askFirst\",\"not\":true},{\"$state\":\"/a/__proto__\"}]},\"rules\":{\"type\":\"Card\",\"props\":{\"title\":\"Ground rules\"},\"children\":[\"f\",\"g\"]},\"f\":{\"type\":\"Toggle\",\"props\":{\"label\":\"Ask me before sending anything\",\"checked\":{\"$bindState\":\"/rules/askFirst\"}}},\"g\":{\"type\":\"Toggle\",\"props\":{\"label\":\"Weekends too\",\"checked\":{\"$bindState\":\"/rules/__proto__/weekends\"}}},\"row\":{\"type\":\"Stack\",\"props\":{\"direction\":\"horizontal\"},\"children\":[\"h\"]},\"h\":{\"type\":\"Button\",\"props\":{\"label\":\"Hire Rex\",\"variant\":\"primary\"},\"on\":{\"press\":{\"action\":\"hire_employee\",\"params\":{\"name\":\"Rex\",\"note\":{\"$state\":\"/constructor/prototype\"}}}}}}}}",+ "salvageable": true,+ "expect": {+ "hasAgent": "Rex",+ "noPollution": true,+ "noForbiddenPaths": true,+ "askFirstValue": false+ }+ },+ {+ "name": "watch, repeat, slots, $computed and confirm are dropped",+ "reply": "{\"text\":\"Extras.\",\"spec\":{\"root\":\"r\",\"elements\":{\"r\":{\"type\":\"Stack\",\"props\":{\"direction\":\"vertical\"},\"children\":[\"a\",\"n\",\"row\"],\"slots\":{\"footer\":[\"n\"]},\"repeat\":{\"statePath\":\"/items\"}},\"a\":{\"type\":\"AgentCard\",\"props\":{\"name\":\"Lia\",\"role\":\"Helper\",\"apps\":[]},\"watch\":{\"/rules/askFirst\":{\"action\":\"hire_employee\"}}},\"n\":{\"type\":\"Metric\",\"props\":{\"label\":\"Score\",\"value\":{\"$computed\":\"secret\",\"args\":{\"x\":1}},\"hint\":{\"$item\":\"x\"}}},\"row\":{\"type\":\"Stack\",\"props\":{\"direction\":\"horizontal\"},\"children\":[\"h\"]},\"h\":{\"type\":\"Button\",\"props\":{\"label\":\"Hire Lia\",\"variant\":\"primary\"},\"on\":{\"press\":{\"action\":\"hire_employee\",\"params\":{\"name\":\"Lia\"},\"confirm\":{\"title\":\"Sure?\",\"message\":\"Hire?\"},\"onSuccess\":{\"set\":{\"/__proto__/x\":1}},\"onError\":{\"action\":\"refine\"},\"preventDefault\":true}}}}}}",+ "salvageable": true,+ "expect": {+ "hasAgent": "Lia",+ "strippedExtras": true,+ "metricValue": ""+ }}]diff --git a/client/src/features/home/genui/__tests__/HireDraftPanel.test.tsx b/client/src/features/home/genui/__tests__/HireDraftPanel.test.tsxindex 3b60270f..0a91ac4f 100644--- a/client/src/features/home/genui/__tests__/HireDraftPanel.test.tsx+++ b/client/src/features/home/genui/__tests__/HireDraftPanel.test.tsx@@ -1,10 +1,13 @@/**- * The draft panel end to end: the screen renders, a double-clicked Hire+ * The draft panel end to end: the screen renders through json-render (its+ * code loads lazily, so the first look waits for it), a double-clicked Hire* sends one request, a finished hire clears the draft and opens the new* employee's page (with what the hire said, and the AI connect dialog when* there is no model), "Change something" hands the composer the draft,- * changing when they work reaches the hire, the wait is shown honestly with- * a way to cancel, and the layout JSON is for developers only.+ * controls write back into the draft, changing when they work reaches the+ * hire, a reply in json-render's own shape works the same, the wait is+ * shown honestly with a way to cancel, and the spec inspector is for+ * developers only.*/import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -45,15 +48,16 @@ import { resetDraftForTests, useDraftStore } from '../draftStore';import { normalizeSpec } from '../normalize';import { parseReply } from '../parse';-const reply = (corpus as unknown as { name: string; reply: string }[]).find((c) => c.name === 'clean minified reply')!.reply;+const replies = corpus as unknown as { name: string; reply: string }[];+const reply = replies.find((c) => c.name === 'clean minified reply')!.reply;-function seedReadyDraft() {- const parsed = parseReply(reply);+function seedReadyDraft(text = reply) {+ const parsed = parseReply(text);const spec = normalizeSpec(parsed.spec)!;useDraftStore.setState({status: 'ready',job: 'Answer WhatsApp',- turns: [{ change: null, reply }],+ turns: [{ change: null, reply: text }],spec,intro: parsed.text,uiState: spec.state,@@ -83,6 +87,11 @@ function hired(patch: Record<string, unknown> = {}) {};}+/** The screen has loaded and shows everything (reduced motion: no reveal). */+function hireButton() {+ return screen.findByRole('button', { name: 'Hire Maya' });+}+let restoreMotion: () => void;beforeEach(() => {@@ -103,12 +112,14 @@ afterEach(() => {});describe('HireDraftPanel', () => {- it('shows the introduction and the setup screen', () => {+ it('shows the introduction and the setup screen', async () => {renderPanel();expect(screen.getByText('Meet Maya, your new receptionist.')).toBeInTheDocument();- expect(screen.getByText('Their routine')).toBeInTheDocument();+ expect(await screen.findByText('Their routine')).toBeInTheDocument();expect(screen.getByText('When something new arrives in WhatsApp')).toBeInTheDocument();expect(screen.getByRole('switch', { name: 'Ask me before sending anything' })).toBeChecked();+ expect(screen.getByRole('switch', { name: 'Only reply 9 to 6' })).not.toBeChecked();+ expect(screen.getByRole('radio', { name: 'Daily' })).toBeChecked();});it('sends one hire for a double click, then clears the draft and opens the employee', async () => {@@ -117,7 +128,7 @@ describe('HireDraftPanel', () => {type === 'hire_employee' ? new Promise((resolve) => (finish = resolve)) : Promise.resolve({}),);const { queryClient } = renderPanel();- const hire = screen.getByRole('button', { name: 'Hire Maya' });+ const hire = await hireButton();fireEvent.click(hire);fireEvent.click(hire);const hires = sendRequest.mock.calls.filter(([type]) => type === 'hire_employee');@@ -141,8 +152,9 @@ describe('HireDraftPanel', () => {const warnings = ['Google Calendar is left out while they ask before sending anything'];sendRequest.mockResolvedValue(hired({ started: false, needs_ai: true, warnings }));renderPanel();+ const hire = await hireButton();await act(async () => {- fireEvent.click(screen.getByRole('button', { name: 'Hire Maya' }));+ fireEvent.click(hire);});const home = useHomeStore.getState();expect(home.view).toEqual({ kind: 'employee', workflowId: 'w1' });@@ -156,8 +168,9 @@ describe('HireDraftPanel', () => {it('tells the owner in plain words when the same hire is still going through', async () => {sendRequest.mockResolvedValue({ success: false, error: 'busy' });renderPanel();+ const hire = await hireButton();await act(async () => {- fireEvent.click(screen.getByRole('button', { name: 'Hire Maya' }));+ fireEvent.click(hire);});expect(pillToast).toHaveBeenCalledWith('They are still being set up. Give it a moment, then press Hire again.', {tone: 'error',@@ -166,22 +179,25 @@ describe('HireDraftPanel', () => {expect(useHomeStore.getState().view).toEqual({ kind: 'hire' });});- it('hands the draft to the composer for a change', () => {+ it('hands the draft to the composer for a change', async () => {renderPanel();- fireEvent.click(screen.getByRole('button', { name: 'Change something' }));+ fireEvent.click(await screen.findByRole('button', { name: 'Change something' }));expect(useDraftStore.getState().refining).toBe(true);});- it('writes a toggle back into the screen state', () => {+ it('writes a toggle and a choice back into the draft', async () => {renderPanel();- fireEvent.click(screen.getByRole('switch', { name: 'Only reply 9 to 6' }));+ fireEvent.click(await screen.findByRole('switch', { name: 'Only reply 9 to 6' }));expect(useDraftStore.getState().uiState).toMatchObject({ rules: { hours: true } });+ expect(screen.getByRole('switch', { name: 'Only reply 9 to 6' })).toBeChecked();+ fireEvent.click(screen.getByRole('radio', { name: 'Weekly' }));+ expect(useDraftStore.getState().uiState).toMatchObject({ choices: { report: 'Weekly' } });});it('hires on the schedule the owner picked, and the routine follows it', async () => {sendRequest.mockResolvedValue(hired());renderPanel();- fireEvent.click(screen.getByRole('button', { name: 'Edit' }));+ fireEvent.click(await screen.findByRole('button', { name: 'Edit' }));fireEvent.click(screen.getByRole('radio', { name: 'On a schedule' }));fireEvent.click(screen.getByRole('radio', { name: 'Weekdays' }));// The sentence and the routine's first step both say it.@@ -194,6 +210,20 @@ describe('HireDraftPanel', () => {expect(payload.steps[0]).toEqual({ title: 'Every weekday at 09:00', detail: '', role: 'trigger' });});+ it('works the same from a reply in json-render’s own shape', async () => {+ resetDraftForTests();+ seedReadyDraft(replies.find((c) => c.name === 'json-render shape: on.press and checked')!.reply);+ sendRequest.mockResolvedValue(hired());+ renderPanel();+ expect(await screen.findByRole('switch', { name: 'Ask me before sending anything' })).toBeChecked();+ fireEvent.click(screen.getByRole('switch', { name: 'Ask me before sending anything' }));+ await act(async () => {+ fireEvent.click(screen.getByRole('button', { name: 'Hire Maya' }));+ });+ const payload = sendRequest.mock.calls.find(([type]) => type === 'hire_employee')![1];+ expect(payload).toMatchObject({ name: 'Maya', rules: { ask_first: false }, sends_via: 'WhatsApp' });+ });+it('opens the guided AI connect dialog from a setup that found no AI model', () => {useDraftStore.setState({ status: 'failed', failure: { code: 'no_ai_provider', text: 'Answer WhatsApp', refine: false } });renderPanel();@@ -227,15 +257,20 @@ describe('HireDraftPanel', () => {expect(useDraftStore.getState()).toMatchObject({ status: 'idle', input: 'Answer WhatsApp' });});- it('shows the layout JSON in development builds only', () => {+ it('shows the spec and its patch stream in development builds only', async () => {vi.stubEnv('DEV', true);renderPanel();- expect(screen.getByRole('button', { name: /Layout JSON/ })).toBeInTheDocument();+ fireEvent.click(await screen.findByRole('button', { name: /Layout JSON/ }));+ expect(screen.getByRole('tab', { name: 'spec.json' })).toHaveAttribute('aria-selected', 'true');+ expect(screen.getByText(/"Their routine"/)).toBeInTheDocument();+ fireEvent.mouseDown(screen.getByRole('tab', { name: 'patches.jsonl' }));+ expect(screen.getByText(/\{"op":"add","path":"\/root","value":"a"\}/)).toBeInTheDocument();});- it('keeps the layout JSON out of a release build', () => {+ it('keeps the spec inspector out of a release build', async () => {vi.stubEnv('DEV', false);renderPanel();+ await hireButton();expect(screen.queryByRole('button', { name: /Layout JSON/ })).not.toBeInTheDocument();});});diff --git a/client/src/features/home/genui/__tests__/actions.test.ts b/client/src/features/home/genui/__tests__/actions.test.tsindex 7d9fccb5..6d461385 100644--- a/client/src/features/home/genui/__tests__/actions.test.ts+++ b/client/src/features/home/genui/__tests__/actions.test.ts@@ -1,5 +1,13 @@+/**+ * The setup screen's action handlers (json-render's ActionProvider calls+ * them with params already resolved at the press): connect an app by the+ * name the reply used, else by the provider's name, else open Connectors;+ * a change request carries nothing the model wrote; Hire gets its params;+ * and each press reads Home's callbacks as they are now.+ */+import { describe, expect, it, vi } from 'vitest';-import { matchProvider, runSpecAction, type SpecActionHandlers } from '../actions';+import { hireActionHandlers, matchProvider, type HireActionContext, type HireActions } from '../actions';const providers = [{ providerId: 'whatsapp', name: 'WhatsApp' },@@ -8,14 +16,18 @@ const providers = [{ providerId: 'stripe', name: 'Stripe' },];-function handlers(): SpecActionHandlers & Record<string, ReturnType<typeof vi.fn>> {- return {- setValue: vi.fn(),- refine: vi.fn(),- openConnectors: vi.fn(),- connect: vi.fn(),- hire: vi.fn(),- } as never;+const apps = {+ gmail: { app_id: 'gmail', provider_id: 'google', name: 'Gmail', icon_ref: null, connected: false, supported: true },+ quickbooks: { app_id: 'quickbooks', provider_id: '', name: 'QuickBooks', icon_ref: null, connected: false, supported: false },+};++function homeActions() {+ return { refine: vi.fn(), openConnectors: vi.fn(), connect: vi.fn(), hire: vi.fn() } satisfies HireActions;+}++function setup(actions = homeActions()) {+ const context: HireActionContext = { apps, providers, actions };+ return { handlers: hireActionHandlers(() => context), actions, context };}describe('matchProvider', () => {@@ -34,42 +46,47 @@ describe('matchProvider', () => {});});-describe('runSpecAction', () => {- const apps = {- gmail: { app_id: 'gmail', provider_id: 'google', name: 'Gmail', icon_ref: null, connected: false, supported: true },- quickbooks: { app_id: 'quickbooks', provider_id: '', name: 'QuickBooks', icon_ref: null, connected: false, supported: false },- };- const context = { state: { freq: 'weekly' }, apps, providers };+describe('hireActionHandlers', () => {+ it('handles the catalogue’s actions and leaves setState to json-render', () => {+ const { handlers } = setup();+ expect(Object.keys(handlers).sort()).toEqual(['connect_app', 'hire_employee', 'open_connectors', 'refine']);+ });it('connects an app the server resolved, by its provider', () => {- const h = handlers();- runSpecAction('connect_app', { app: 'Gmail' }, context, h);- expect(h.connect).toHaveBeenCalledWith('google', 'Gmail');+ const { handlers, actions } = setup();+ handlers.connect_app({ app: 'Gmail' });+ expect(actions.connect).toHaveBeenCalledWith('google', 'Gmail');});it('falls back to the provider names, and opens Connectors when nothing matches', () => {- const h = handlers();- runSpecAction('connect_app', { app: 'Stripe' }, context, h);- expect(h.connect).toHaveBeenCalledWith('stripe', 'Stripe');- runSpecAction('connect_app', { app: 'QuickBooks' }, context, h);- runSpecAction('connect_app', {}, context, h);- expect(h.openConnectors).toHaveBeenCalledTimes(2);+ const { handlers, actions } = setup();+ handlers.connect_app({ app: 'Stripe' });+ expect(actions.connect).toHaveBeenCalledWith('stripe', 'Stripe');+ handlers.connect_app({ app: 'QuickBooks' });+ handlers.connect_app({});+ handlers.connect_app({ app: 'constructor' });+ expect(actions.openConnectors).toHaveBeenCalledTimes(3);});- it('resolves params against the screen state', () => {- const h = handlers();- runSpecAction('setState', { statePath: '/choices/freq', value: { $state: '/freq' } }, context, h);- expect(h.setValue).toHaveBeenCalledWith('/choices/freq', 'weekly');- runSpecAction('hire_employee', { name: 'Maya', note: { $template: 'Reports ${/freq}' } }, context, h);- expect(h.hire).toHaveBeenCalledWith({ name: 'Maya', note: 'Reports weekly' });+ it('hands Hire its params, and a change request nothing', () => {+ const { handlers, actions } = setup();+ handlers.hire_employee({ name: 'Maya', note: 'Reports weekly' });+ expect(actions.hire).toHaveBeenCalledWith({ name: 'Maya', note: 'Reports weekly' });+ handlers.refine({ prompt: 'Only weekdays' });+ expect(actions.refine).toHaveBeenCalledTimes(1);+ expect(actions.refine).toHaveBeenCalledWith();+ handlers.open_connectors({});+ expect(actions.openConnectors).toHaveBeenCalledTimes(1);});- it('treats ask as a plain change request and ignores unknown actions', () => {- const h = handlers();- runSpecAction('ask', { prompt: 'Only weekdays' }, context, h);- expect(h.refine).toHaveBeenCalledTimes(1);- expect(h.refine).toHaveBeenCalledWith();- runSpecAction('delete_everything', {}, context, h);- expect(Object.values(h).every((fn) => fn.mock.calls.length <= 1)).toBe(true);+ it('reads Home’s callbacks at each press', () => {+ const first = homeActions();+ const later = homeActions();+ let context: HireActionContext = { apps, providers, actions: first };+ const handlers = hireActionHandlers(() => context);+ context = { ...context, actions: later };+ handlers.hire_employee({});+ expect(first.hire).not.toHaveBeenCalled();+ expect(later.hire).toHaveBeenCalledTimes(1);});});diff --git a/client/src/features/home/genui/__tests__/hirePayload.test.ts b/client/src/features/home/genui/__tests__/hirePayload.test.tsindex aa9d6716..61fb099d 100644--- a/client/src/features/home/genui/__tests__/hirePayload.test.ts+++ b/client/src/features/home/genui/__tests__/hirePayload.test.ts@@ -24,9 +24,10 @@ function specOf(name: string): NormalizedSpec {return normalizeSpec(parsed.spec)!;}+/** The hire button's params as json-render resolves them at the press. */function hireParams(spec: NormalizedSpec, state = spec.state) {- const id = spec.order.find((key) => spec.elements[key].props.action === 'hire_employee')!;- return resolveValue(spec.elements[id].props.actionParams ?? {}, state) as Record<string, unknown>;+ const id = spec.order.find((key) => spec.elements[key].on?.press.action === 'hire_employee')!;+ return resolveValue(spec.elements[id].on?.press.params ?? {}, state) as Record<string, unknown>;}describe('buildHirePayload', () => {@@ -72,6 +73,19 @@ describe('buildHirePayload', () => {expect(payload.choices[0].value).toBe('Weekly');});+ it('reads a reply in json-render’s shape the same way', () => {+ const shaped = specOf('json-render shape: on.press and checked');+ const state = setPath(shaped.state, '/rules/hours', true);+ const payload = buildHirePayload({ spec: shaped, state, params: hireParams(shaped, state), job: 'j', idempotencyKey: 'k' });+ expect(payload).toMatchObject({+ name: 'Maya',+ rules: { ask_first: true, items: [{ key: 'hours', label: 'Only reply 9 to 6', value: true }] },+ choices: [{ key: 'report', label: 'Report', value: 'Daily' }],+ trigger: { kind: 'app_event', app: 'WhatsApp' },+ sends_via: 'WhatsApp',+ });+ });+it('sends when they work as the owner left it, and the routine says so', () => {const state = setPath(spec.state, STATE_PATHS.trigger, { kind: 'schedule', every: 'weekday', at: '09:00' });const payload = buildHirePayload({ spec, state, params: hireParams(spec, state), job: 'j', idempotencyKey: 'k' });diff --git a/client/src/features/home/genui/__tests__/normalize.test.ts b/client/src/features/home/genui/__tests__/normalize.test.tsindex 6d0e3480..9fddb171 100644--- a/client/src/features/home/genui/__tests__/normalize.test.ts+++ b/client/src/features/home/genui/__tests__/normalize.test.ts@@ -1,4 +1,10 @@/**+ * The normalizer's output is json-render's shape whichever shape the model+ * wrote: a Button's action becomes `on.press` (from `on.press`, from `on`+ * written inside its props, or from the older `action` / `actionParams`+ * props), a Toggle binds `checked` (older replies say `value`), and every+ * expression whose path reaches a prototype is dropped.+ ** When they work, as the normalizer sets it up: one Schedule after the* routine, bound to /trigger, which starts as the hire button's trigger* (else the app the routine's first "When" step names, else the owner@@ -28,10 +34,108 @@ function screen(hireTrigger: unknown, extra: Record<string, Raw> = {}, planSteps})!;}+/** A screen with just these elements under the root (plus whatever the normalizer adds). */+function only(elements: Record<string, Raw>, state: Raw = {}) {+ return normalizeSpec({+ root: 'r',+ state,+ elements: { r: { type: 'Stack', props: { direction: 'vertical' }, children: Object.keys(elements) }, ...elements },+ })!;+}+function schedules(spec: NormalizedSpec): string[] {return spec.order.filter((id) => spec.elements[id].type === 'Schedule');}+describe('json-render shape', () => {+ const hireParams = { name: 'Maya', trigger: { kind: 'manual' } };++ it('takes a Button’s action from on.press, from on inside its props, or from its older props', () => {+ const shapes = [+ { type: 'Button', props: { label: 'Hire Maya' }, on: { press: { action: 'hire_employee', params: hireParams } } },+ { type: 'Button', props: { label: 'Hire Maya', on: { press: { action: 'hire_employee', params: hireParams } } } },+ { type: 'Button', props: { label: 'Hire Maya', action: 'hire_employee', actionParams: hireParams } },+ { type: 'Button', label: 'Hire Maya', action: 'hire_employee', actionParams: hireParams },+ ];+ for (const button of shapes) {+ const spec = only({ h: button });+ expect(spec.elements.h.on).toEqual({ press: { action: 'hire_employee', params: hireParams } });+ expect(spec.elements.h.props).toEqual({ label: 'Hire Maya' });+ }+ });++ it('prefers on.press over older props, and takes the first known action of a list', () => {+ const spec = only({+ h: {+ type: 'Button',+ props: { label: 'Hire', action: 'refine' },+ on: { press: [{ action: 'wave' }, { action: 'hire_employee', params: { name: 'Ivy' } }] },+ },+ });+ expect(spec.elements.h.on?.press).toEqual({ action: 'hire_employee', params: { name: 'Ivy' } });+ });++ it('keeps an action binding to its action and params', () => {+ const spec = only({+ h: {+ type: 'Button',+ props: { label: 'Hire' },+ on: {+ press: { action: 'hire_employee', params: { name: 'Lia' }, confirm: { title: 'Sure?', message: 'Hire?' }, onSuccess: { set: { '/x': 1 } } },+ hover: { action: 'refine' },+ },+ },+ });+ expect(spec.elements.h.on).toEqual({ press: { action: 'hire_employee', params: { name: 'Lia' } } });+ });++ it('turns ask into a plain change request and drops a Button whose action is unknown', () => {+ const spec = only({+ q: { type: 'Button', props: { label: 'Only weekdays' }, on: { press: { action: 'ask', params: { text: 'Only weekdays' } } } },+ x: { type: 'Button', props: { label: 'Push' }, on: { press: { action: 'pushState', params: { statePath: '/a', value: 1 } } } },+ });+ expect(spec.elements.q.on).toEqual({ press: { action: 'refine' } });+ expect(spec.elements.x).toBeUndefined();+ });++ it('binds a Toggle’s checked, reading value from older replies', () => {+ const spec = only({+ rules: { type: 'Card', props: { title: 'Ground rules' }, children: ['t1', 't2'] },+ t1: { type: 'Toggle', props: { label: 'Only 9 to 6', value: { $bindState: '/rules/hours' } } },+ t2: { type: 'Toggle', props: { label: 'Weekends', checked: { $bindState: '/rules/weekends' }, value: true } },+ });+ expect(spec.elements.t1.props).toEqual({ label: 'Only 9 to 6', checked: { $bindState: '/rules/hours' } });+ expect(spec.elements.t2.props).toEqual({ label: 'Weekends', checked: { $bindState: '/rules/weekends' } });+ // The ask-first toggle it adds binds checked too.+ const askFirst = spec.order.find((id) => bindingPath(spec.elements[id].props.checked) === STATE_PATHS.askFirst);+ expect(askFirst).toBeDefined();+ });++ it('drops expressions whose path reaches a prototype, wherever they are', () => {+ const spec = only({+ t: {+ type: 'Text',+ props: { text: { $template: 'Hi ${/__proto__/x} and ${ /name }' } },+ visible: { $state: '/constructor/x' },+ },+ m: { type: 'Metric', props: { label: { $state: '/prototype' }, value: { $computed: 'f' } }, visible: [{ $state: '/ok' }] },+ i: { type: 'Input', props: { label: 'Name', value: { $bindState: '/inputs/__proto__' } } },+ h: {+ type: 'Button',+ props: { label: 'Hire' },+ on: { press: { action: 'hire_employee', params: { name: { $state: '/__proto__/name' }, role: { $state: '/role' } } } },+ },+ });+ expect(spec.elements.t.props).toEqual({ text: { $template: 'Hi and ${/name}' } });+ expect(spec.elements.t.visible).toBe(false);+ expect(spec.elements.m.props).toEqual({});+ expect(spec.elements.m.visible).toEqual({ $and: [{ $state: '/ok' }] });+ expect(spec.elements.i.props).toEqual({ label: 'Name' });+ expect(spec.elements.h.on?.press.params).toEqual({ role: { $state: '/role' } });+ expect(JSON.stringify(spec)).not.toMatch(/__proto__|constructor|prototype|\$computed/);+ });+});+describe('when they work', () => {it('is one Schedule right after the routine, bound to /trigger', () => {const spec = screen({ kind: 'app_event', app: 'WhatsApp' });@@ -47,6 +151,18 @@ describe('when they work', () => {expect(getPath(spec.state, STATE_PATHS.trigger)).toEqual({ kind: 'schedule', every: 'weekday', at: '09:00' });});+ it('reads the hire button’s trigger from on.press as well', () => {+ const spec = only({+ a: { type: 'AgentCard', props: { name: 'Ivy', role: 'Diary keeper' } },+ h: {+ type: 'Button',+ props: { label: 'Hire Ivy', variant: 'primary' },+ on: { press: { action: 'hire_employee', params: { trigger: { kind: 'schedule', every: 'week', day: 'tue', at: '08:00' } } } },+ },+ });+ expect(getPath(spec.state, STATE_PATHS.trigger)).toEqual({ kind: 'schedule', every: 'week', day: 'tuesday', at: '08:00' });+ });+it('takes the routine’s app when the button names none, else the owner messaging them', () => {const steps = [{ title: 'When a message arrives', role: 'trigger', app: 'Telegram' }, { title: 'Answer', role: 'agent' }];expect(getPath(screen(undefined, {}, steps).state, STATE_PATHS.trigger)).toEqual({ kind: 'app_event', app: 'Telegram' });diff --git a/client/src/features/home/genui/__tests__/replies.test.ts b/client/src/features/home/genui/__tests__/replies.test.tsindex be195afd..537c6e06 100644--- a/client/src/features/home/genui/__tests__/replies.test.ts+++ b/client/src/features/home/genui/__tests__/replies.test.ts@@ -1,15 +1,18 @@/*** The shared corpus of model replies (genui/__fixtures__/replies.json):* each one parses and normalizes to a renderable screen exactly when it is- * marked salvageable, and every such screen can be hired, changed, asks- * first by default and says when they work. The server's salvage check runs the same corpus+ * marked salvageable, and every such screen is in json-render's shape, can+ * be hired and changed, asks first by default and says when they work.+ * Replies come in both shapes a model writes: the older one (a Toggle's+ * `value`, a Button's `action` / `actionParams` props) and json-render's+ * (`checked`, `on.press`). The server's salvage check runs the same corpus* (server/tests/services/employees/test_setup_salvage_parity.py), so the* two sides agree on which replies are worth retrying.*/import { describe, expect, it } from 'vitest';import corpus from '../__fixtures__/replies.json';-import { STATE_PATHS, isContainer } from '../catalog';+import { ACTION_TYPES, STATE_PATHS, isContainer } from '../catalog';import { bindingPath, getPath } from '../expressions';import { normalizeSpec, type NormalizedSpec } from '../normalize';import { parseReply } from '../parse';@@ -22,6 +25,7 @@ interface Case {}const cases = corpus as unknown as Case[];+const ELEMENT_KEYS = new Set(['type', 'props', 'children', 'visible', 'on']);function read(reply: string): { text: string; spec: NormalizedSpec | null } {const parsed = parseReply(reply);@@ -33,7 +37,7 @@ function elements(spec: NormalizedSpec) {}function buttons(spec: NormalizedSpec, action: string) {- return elements(spec).filter(([, element]) => element.type === 'Button' && element.props.action === action);+ return elements(spec).filter(([, element]) => element.type === 'Button' && element.on?.press.action === action);}function assertTree(spec: NormalizedSpec) {@@ -55,6 +59,22 @@ function assertTree(spec: NormalizedSpec) {expect(spec.order[0]).toBe(spec.root);}+/** json-render's element shape, and nothing a model may not reach. */+function assertJsonRenderShape(spec: NormalizedSpec) {+ for (const [id, element] of elements(spec)) {+ for (const key of Object.keys(element)) expect(ELEMENT_KEYS.has(key), `${id} has ${key}`).toBe(true);+ if (element.type === 'Button') {+ expect(ACTION_TYPES).toContain(element.on?.press.action);+ expect(Object.keys(element.on!.press).every((key) => key === 'action' || key === 'params')).toBe(true);+ expect(element.props).not.toHaveProperty('action');+ expect(element.props).not.toHaveProperty('actionParams');+ } else {+ expect(element.on).toBeUndefined();+ }+ if (element.type === 'Toggle') expect(element.props).not.toHaveProperty('value');+ }+}+describe('model reply corpus', () => {it.each(cases.map((c) => [c.name, c] as const))('%s', (_name, entry) => {const { text, spec } = read(entry.reply);@@ -64,11 +84,12 @@ describe('model reply corpus', () => {if (!spec) return;assertTree(spec);+ assertJsonRenderShape(spec);// Every screen can be hired, changed, and asks first by default.expect(buttons(spec, 'hire_employee')).toHaveLength(1);expect(buttons(spec, 'refine')).toHaveLength(1);const askFirst = elements(spec).filter(- ([, element]) => element.type === 'Toggle' && bindingPath(element.props.value) === STATE_PATHS.askFirst,+ ([, element]) => element.type === 'Toggle' && bindingPath(element.props.checked) === STATE_PATHS.askFirst,);expect(askFirst).toHaveLength(1);expect(typeof getPath(spec.state, STATE_PATHS.askFirst)).toBe('boolean');@@ -84,8 +105,9 @@ describe('model reply corpus', () => {expect(agent?.[1].props.name).toBe(want.hasAgent);}if ('hireLabel' in want) expect(buttons(spec, 'hire_employee')[0][1].props.label).toBe(want.hireLabel);- if ('refineHasNoParams' in want) expect(buttons(spec, 'refine')[0][1].props.actionParams).toBeUndefined();+ if ('refineHasNoParams' in want) expect(buttons(spec, 'refine')[0][1].on?.press.params).toBeUndefined();if ('askFirstValue' in want) expect(getPath(spec.state, STATE_PATHS.askFirst)).toBe(want.askFirstValue);+ if ('trigger' in want) expect(getPath(spec.state, STATE_PATHS.trigger)).toEqual(want.trigger);if ('togglesInRulesCard' in want) {const card = elements(spec).find(([, element]) => element.type === 'Card' && /rule/i.test(String(element.props.title)));const toggles = card?.[1].children.filter((child) => spec.elements[child].type === 'Toggle') ?? [];@@ -102,6 +124,16 @@ describe('model reply corpus', () => {for (const [, element] of elements(spec)) expect(Object.keys(element.props)).not.toContain('constructor');expect(Object.keys(spec.state)).not.toContain('__proto__');}+ if ('noForbiddenPaths' in want) {+ expect(JSON.stringify({ state: spec.state, elements: spec.elements })).not.toMatch(/__proto__|constructor|prototype/);+ }+ if ('strippedExtras' in want) {+ expect(JSON.stringify(spec)).not.toMatch(/\$computed|\$item|confirm|onSuccess|onError|preventDefault|watch|repeat|slots/);+ }+ if ('sameAs' in want) {+ const other = read(cases.find((c) => c.name === want.sameAs)!.reply).spec;+ expect(spec).toEqual(other);+ }});it('keeps the first of two parents and breaks the cycle', () => {@@ -116,7 +148,7 @@ describe('model reply corpus', () => {const row = elements(spec!).find(([, element]) => element.type === 'Stack' && element.props.direction === 'horizontal',);- expect(row?.[1].children.map((child) => spec!.elements[child].props.action)).toEqual(['hire_employee', 'refine']);+ expect(row?.[1].children.map((child) => spec!.elements[child].on?.press.action)).toEqual(['hire_employee', 'refine']);});it('keeps the model order when capping a long screen', () => {diff --git a/client/src/features/home/genui/actions.ts b/client/src/features/home/genui/actions.tsindex c99d4d4e..11ba3872 100644--- a/client/src/features/home/genui/actions.ts+++ b/client/src/features/home/genui/actions.ts@@ -1,7 +1,12 @@/**- * What a setup screen's buttons do. The model names an action; this maps it- * onto Home: change a value, start editing the draft, open Connectors,- * connect one app, or hire.+ * What a setup screen's buttons do, as json-render action handlers (given+ * to the screen's JSONUIProvider). Every Button presses one action through+ * its `on.press` binding; json-render resolves the binding's params against+ * the screen's state at the press and calls the handler with them. The+ * actions map onto Home: start editing the draft, open Connectors, connect+ * one app, or hire. `setState` is not here: json-render runs it itself,+ * writing the screen's state store (lib/jsonRender/uiState.ts), and the+ * store tells the draft.** `connect_app` names an app in the owner's words ("Gmail", "Google* calendar"). The server resolves the names a reply uses against the app@@ -11,16 +16,16 @@*/import type { AppRef } from '../data/schemas';-import { actionOf } from './catalog';-import { resolveValue, type UiState } from './expressions';+import type { ActionType } from './catalog';export interface ConnectCandidate {providerId: string;name: string;}-export interface SpecActionHandlers {- setValue: (path: string, value: unknown) => void;+/** What the buttons can make Home do. */+export interface HireActions {+ /** Start editing the draft from the composer. */refine: () => void;openConnectors: () => void;/** Open the connect dialog for a provider. */@@ -28,14 +33,16 @@ export interface SpecActionHandlers {hire: (params: Record<string, unknown>) => void;}-export interface SpecActionContext {- state: UiState;+export interface HireActionContext {/** Names the server resolved for this reply, lower-cased. */apps: Record<string, AppRef>;/** Connectable providers (the catalogue), for names the server did not see. */providers: readonly ConnectCandidate[];+ actions: HireActions;}+export type HireActionHandlers = Record<Exclude<ActionType, 'setState'>, (params: Record<string, unknown>) => void>;+const MIN_SUBSTRING = 3;/** The provider an app name refers to, by name: exact, then prefix (the@@ -61,47 +68,35 @@ function asRecord(value: unknown): Record<string, unknown> {return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : {};}-/** Run one button's action. `rawParams` are the button's params as- * written; they are resolved against the screen's current state here. */-export function runSpecAction(- action: unknown,- rawParams: unknown,- context: SpecActionContext,- handlers: SpecActionHandlers,-): void {- const name = actionOf(action);- const params = asRecord(resolveValue(rawParams ?? {}, context.state));- switch (name) {- case 'setState': {- if (typeof params.statePath === 'string') handlers.setValue(params.statePath, params.value);- return;- }- case 'refine':- handlers.refine();- return;- case 'open_connectors':- handlers.openConnectors();- return;- case 'connect_app': {- const appName = typeof params.app === 'string' ? params.app.trim() : '';- if (!appName) {- handlers.openConnectors();- return;- }- const known = context.apps[appName.toLowerCase()];- if (known && known.supported) {- handlers.connect(known.provider_id, known.name);- return;- }- const match = matchProvider(appName, context.providers);- if (match) handlers.connect(match.providerId, match.name);- else handlers.openConnectors();- return;- }- case 'hire_employee':- handlers.hire(params);- return;- default:- return;+function connectApp(params: Record<string, unknown>, context: HireActionContext): void {+ const appName = typeof params.app === 'string' ? params.app.trim() : '';+ if (!appName) {+ context.actions.openConnectors();+ return;+ }+ const known = Object.prototype.hasOwnProperty.call(context.apps, appName.toLowerCase())+ ? context.apps[appName.toLowerCase()]+ : undefined;+ if (known && known.supported) {+ context.actions.connect(known.provider_id, known.name);+ return;}+ const match = matchProvider(appName, context.providers);+ if (match) context.actions.connect(match.providerId, match.name);+ else context.actions.openConnectors();+}++/**+ * The handlers for a screen. `context` is read at each press, so the+ * handlers can be made once per screen (json-render's ActionProvider keeps+ * the handlers it first gets) while Home's callbacks and app lists change.+ */+export function hireActionHandlers(context: () => HireActionContext): HireActionHandlers {+ return {+ hire_employee: (params) => context().actions.hire(asRecord(params)),+ // A change is the owner's to write: whatever the button suggested is not sent.+ refine: () => context().actions.refine(),+ open_connectors: () => context().actions.openConnectors(),+ connect_app: (params) => connectApp(asRecord(params), context()),+ };}diff --git a/client/src/features/home/genui/catalog.ts b/client/src/features/home/genui/catalog.tsindex 1c36a080..887ba47e 100644--- a/client/src/features/home/genui/catalog.ts+++ b/client/src/features/home/genui/catalog.ts@@ -1,7 +1,8 @@/*** The setup screen's vocabulary: the components and actions a model may* use when it describes a new employee, and what each component's props- * look like once resolved.+ * look like once resolved. The screen is drawn by json-render; HIRE_CATALOG+ * below is this vocabulary in the shape its defineCatalog takes.** The server writes the model's prompt from server/config/genui_catalog.json;* tests/test_genui_catalog_sync.py reads the literal lists in this file off@@ -10,6 +11,8 @@** Prop schemas are forgiving by design: a model's odd value degrades that* one prop (a default, a clamped string) instead of failing the element.+ * A Toggle binds `checked`; a Button names its action in the element's+ * `on.press` (json-render's event binding), not in its props.*/import { z } from 'zod';@@ -162,7 +165,7 @@ export const PROP_SCHEMAS = {value: z.coerce.number().catch(0).transform((v) => Math.max(0, Math.min(100, Number.isFinite(v) ? v : 0))),tone,}),- Toggle: z.object({ label: line(), description: optionalLine(LIMITS.maxText), value: z.boolean().catch(false) }),+ Toggle: z.object({ label: line(), description: optionalLine(LIMITS.maxText), checked: z.boolean().catch(false) }),Choice: z.object({label: line(),options: listOf(line(40), LIMITS.maxOptions).transform((options) => [...new Set(options.filter(Boolean))]),@@ -173,10 +176,10 @@ export const PROP_SCHEMAS = {placeholder: optionalLine(),value: scalar.catch('').transform((s) => s.slice(0, LIMITS.maxInput)),}),+ // What it runs is the element's on.press, which json-render resolves at the press.Button: z.object({label: line(40),variant: z.enum(['primary', 'secondary']).catch('secondary'),- action: z.string().catch(''),}),Divider: z.object({}),} satisfies Record<ComponentType, z.ZodType>;@@ -198,6 +201,31 @@ export function isControl(type: ComponentType): boolean {/** The action a Button runs, with old names mapped; null when unknown. */export function actionOf(value: unknown): ActionType | null {if (typeof value !== 'string') return null;- const name = ACTION_ALIASES[value] ?? value;+ const name = Object.prototype.hasOwnProperty.call(ACTION_ALIASES, value) ? ACTION_ALIASES[value] : value;return (ACTION_TYPES as readonly string[]).includes(name) ? (name as ActionType) : null;}++// ----- the catalogue as json-render takes it -----++type HireCatalogComponents = {+ [T in ComponentType]: { props: (typeof PROP_SCHEMAS)[T]; slots?: string[] };+};++function catalogComponents(): HireCatalogComponents {+ const components: Partial<Record<ComponentType, { props: z.ZodType; slots?: string[] }>> = {};+ for (const type of COMPONENT_TYPES) {+ components[type] = isContainer(type) ? { props: PROP_SCHEMAS[type], slots: ['default'] } : { props: PROP_SCHEMAS[type] };+ }+ return components as HireCatalogComponents;+}++/**+ * What json-render's defineCatalog takes for the setup screen: every+ * component with its props schema, containers with their children (the+ * default slot). registry.ts defines the catalogue from it there, beside+ * the renderer, because this file is in Home's first chunk and json-render+ * loads only with the screen. No actions are declared: the screen's+ * handlers come from Home when it renders (actions.ts), and setState is+ * json-render's own.+ */+export const HIRE_CATALOG = { components: catalogComponents(), actions: {} };diff --git a/client/src/features/home/genui/expressions.ts b/client/src/features/home/genui/expressions.tsindex b7b6adc9..c5cbb329 100644--- a/client/src/features/home/genui/expressions.ts+++ b/client/src/features/home/genui/expressions.ts@@ -8,68 +8,44 @@* - conditions C (and an element's `visible`): `{"$state": "/path"}`, with* optional `"eq"` / `"neq"` and `"not": true`; an array means all of them.*- * Paths are `/`-separated keys. A path through `__proto__`, `constructor`- * or `prototype` is refused, so model-written paths can never reach an- * object's prototype. Writes copy along the path and keep arrays as- * arrays.+ * Paths are JSON Pointers ("/rules/askFirst"), the form json-render reads.+ * The path rule (lib/jsonRender/paths.ts, shared with json-render's side)+ * refuses a path through `__proto__`, `constructor` or `prototype`, so+ * model-written paths can never reach an object's prototype. Writes copy+ * along the path and keep arrays as arrays.+ *+ * json-render evaluates the screen as it renders; this evaluator is for+ * reading the screen outside it: the hire payload and the normaliser.*/+// The file, not the index: this module is in Home's first chunk.+import { isForbiddenSegment, parseStatePath, readPath, writePath } from '@/lib/jsonRender/paths';+export type UiState = Record<string, unknown>;-const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);const MAX_DEPTH = 8;-const MAX_PATH_KEYS = 6;export function isForbiddenKey(key: string): boolean {- return FORBIDDEN_KEYS.has(key);+ return isForbiddenSegment(key);}/** The keys of a path, or null when the path is not a usable string. */export function pathKeys(path: unknown): string[] | null {- if (typeof path !== 'string') return null;- const keys = path.split('/').filter(Boolean);- if (keys.length === 0 || keys.length > MAX_PATH_KEYS || keys.some(isForbiddenKey)) return null;- return keys;+ return parseStatePath(path);}function isRecord(value: unknown): value is Record<string, unknown> {return typeof value === 'object' && value !== null && !Array.isArray(value);}-function childOf(value: unknown, key: string): unknown {- if (Array.isArray(value)) {- const index = Number(key);- return Number.isInteger(index) && index >= 0 ? value[index] : undefined;- }- if (isRecord(value) && Object.prototype.hasOwnProperty.call(value, key)) return value[key];- return undefined;-}-export function getPath(state: unknown, path: unknown): unknown {- const keys = pathKeys(path);- if (!keys) return undefined;- return keys.reduce<unknown>((value, key) => childOf(value, key), state);+ return readPath(state, path);}/** A copy of `state` with `value` at `path`; `state` itself is unchanged.* An unusable path returns `state` as it was. */export function setPath(state: UiState, path: unknown, value: unknown): UiState {- const keys = pathKeys(path);- if (!keys) return state;- const write = (node: unknown, index: number): unknown => {- const key = keys[index];- const last = index === keys.length - 1;- if (Array.isArray(node)) {- const at = Number(key);- if (!Number.isInteger(at) || at < 0 || at > node.length) return node;- const copy = node.slice();- copy[at] = last ? value : write(node[at], index + 1);- return copy;- }- const base = isRecord(node) ? node : {};- return { ...base, [key]: last ? value : write(childOf(base, key), index + 1) };- };- return write(state, 0) as UiState;+ return writePath(state, path, value);}/** The path a control writes to (`{"$bindState": "/path"}`), or null. */diff --git a/client/src/features/home/genui/hirePayload.ts b/client/src/features/home/genui/hirePayload.tsindex ef71ce39..c7ad7383 100644--- a/client/src/features/home/genui/hirePayload.ts+++ b/client/src/features/home/genui/hirePayload.ts@@ -309,12 +309,13 @@ export function buildHirePayload({ spec, state, params, job, idempotencyKey, soufor (const id of spec.order) {const element = spec.elements[id];if (!element) continue;- const path = bindingPath(element.props.value);- if (element.type === 'Toggle' && path !== STATE_PATHS.askFirst) {- const key = keyUnder(path, STATE_PATHS.rules);+ // A Toggle binds `checked`; a Choice and an Input bind `value`.+ const path = bindingPath(element.type === 'Toggle' ? element.props.checked : element.props.value);+ if (element.type === 'Toggle') {+ const key = path === STATE_PATHS.askFirst ? null : keyUnder(path, STATE_PATHS.rules);const props = resolved('Toggle', element, state);if (key && props && rules.items.length < HIRE_LIMITS.items) {- rules.items.push({ key, label: props.label.slice(0, HIRE_LIMITS.label), value: props.value });+ rules.items.push({ key, label: props.label.slice(0, HIRE_LIMITS.label), value: props.checked });}} else if (element.type === 'Choice') {const key = keyUnder(path, STATE_PATHS.choices);diff --git a/client/src/features/home/genui/hireSpecContext.ts b/client/src/features/home/genui/hireSpecContext.tsnew file mode 100644index 00000000..d711155b--- /dev/null+++ b/client/src/features/home/genui/hireSpecContext.ts@@ -0,0 +1,18 @@+/**+ * What the setup screen's components need beyond their own props: the+ * state the screen was written with (the routine's "When" step is+ * rewritten only once the owner changes when they work) and the apps that+ * can start the work (Schedule offers only those). HireScreen provides it.+ */++import { createContext } from 'react';+import type { UiState } from './expressions';++export interface HireSpecContextValue {+ /** The screen's state as normalised, before the owner changed anything. */+ writtenState: UiState;+ /** Apps that can start the work: any name the reply used -> the app's own name. */+ triggerApps: Readonly<Record<string, string>>;+}++export const HireSpecContext = createContext<HireSpecContextValue>({ writtenState: {}, triggerApps: {} });diff --git a/client/src/features/home/genui/index.ts b/client/src/features/home/genui/index.tsindex 17ec757f..af3a1954 100644--- a/client/src/features/home/genui/index.ts+++ b/client/src/features/home/genui/index.ts@@ -1,10 +1,12 @@/*** The setup-screen pipeline, as pages see it. Everything else in this- * folder (the catalogue, parser, normalizer, renderer and store) is- * private to it; eslint.config.js refuses imports of those from outside.+ * folder (the catalogue, parser, normalizer, json-render registry and+ * store) is private to it; eslint.config.js refuses imports of those from+ * outside. The screen's renderer loads lazily (HireDraftPanel), so nothing+ * exported here brings json-render with it.*/export { HireDraftPanel } from './HireDraftPanel';-export { MessagePreview as DraftMessagePreview } from './render';+export { MessagePreview as DraftMessagePreview } from './MessagePreview';export { useHireComposer } from './useHireComposer';export { useStarterHire } from './useStarterHire';diff --git a/client/src/features/home/genui/normalize.ts b/client/src/features/home/genui/normalize.tsindex beda9b4a..b3839bc4 100644--- a/client/src/features/home/genui/normalize.ts+++ b/client/src/features/home/genui/normalize.ts@@ -1,10 +1,11 @@/*** Turning a model's setup-screen spec into one that is safe to render.*- * A spec is flat: `{root, state, elements: {id: {type, props, children,- * visible?}}}`. Models get it slightly wrong in predictable ways (props- * written beside `props`, children never listed, the hire button left out,- * a cycle), so this repairs rather than rejects. The result:+ * A spec is flat, in json-render's shape: `{root, state, elements: {id:+ * {type, props, children, visible?, on?}}}`. Models get it slightly wrong+ * in predictable ways (props written beside `props`, children never+ * listed, the hire button left out, a cycle), so this repairs rather than+ * rejects. The result:** - is a tree: the root is always a vertical Stack; each element has one* parent (the first one found, depth first), cycles are broken, and only@@ -12,6 +13,9 @@* - loses nothing a model placed badly: elements nobody lists are attached* where they belong (controls into the rules card, connect buttons into* the apps card, the hire and change buttons into the button row);+ * - gives every Button its action as `on.press` ({action, params}), whether+ * the model wrote that or the older `action` / `actionParams` props, and+ * every Toggle its value as `checked` (older replies say `value`);* - always has "Ask me before sending anything" bound to /rules/askFirst,* defaulting to on, and exactly one hire button and one change button;* - always says when they work: one Schedule, after the routine, bound to@@ -20,8 +24,11 @@* snapped to one the server builds exactly as it reads;* - has at most LIMITS.maxElements elements (the buttons, that toggle and* the Schedule are always kept);- * - cannot reach an object prototype (ids, prop keys and state keys named- * `__proto__`, `constructor` or `prototype` are dropped).+ * - cannot reach an object prototype: ids, prop keys and state keys named+ * `__proto__`, `constructor` or `prototype` are dropped, and so is any+ * expression whose path goes through one; `watch`, `repeat`, `slots`,+ * `$computed` and an action's `confirm` never get through+ * (lib/jsonRender/sanitize.ts).** `ask` buttons become plain `refine`: the owner writes the change, the* model's suggested wording is never sent on their behalf.@@ -31,6 +38,14 @@* (services/employees/setup_reply.py).*/+import type { VisibilityCondition } from '@json-render/core';+// The file, not the index: this module is in Home's first chunk.+import {+ DEFAULT_SANITIZE_LIMITS,+ sanitizeCondition,+ sanitizeExpressions,+ type SanitizeLimits,+} from '@/lib/jsonRender/sanitize';import {ASK_FIRST_LABEL,LIMITS,@@ -40,17 +55,27 @@ import {isComponentType,isContainer,isControl,+ type ActionType,type ComponentType,} from './catalog';import { bindingPath, getPath, isForbiddenKey, resolveValue, sanitizeState, setPath, type UiState } from './expressions';import { readTrigger, snapTrigger, type HireTrigger } from './hirePayload';+/** What pressing a Button runs: an action and its params (expressions+ * resolved against the screen's state at the press). */+export interface PressBinding {+ action: ActionType;+ params?: Record<string, unknown>;+}+export interface SpecElement {type: ComponentType;- /** Props as written (expressions unresolved). */+ /** Props as written (expressions unresolved), made safe to resolve. */props: Record<string, unknown>;children: string[];- visible?: unknown;+ visible?: VisibilityCondition;+ /** A Button's action. */+ on?: { press: PressBinding };}export interface NormalizedSpec {@@ -61,13 +86,21 @@ export interface NormalizedSpec {order: string[];}-const META_KEYS = new Set(['type', 'props', 'children', 'visible', 'watch', 'id']);+/** Element keys that are never props (everything else beside `props` is+ * hoisted into them). The server reads replies with the same list+ * (services/employees/setup_reply.py `_META_KEYS`). */+const META_KEYS = new Set(['type', 'props', 'children', 'visible', 'watch', 'id', 'on', 'repeat', 'slots']);const ID_PATTERN = /^[A-Za-z0-9_.:-]+$/;const MAX_RAW_ELEMENTS = 64;const RULES_TITLE = /rule|setting|prefer|control|how/i;const APPS_TITLE = /app|connect|need|check/i;const ASK_FIRST_WORDING = /\bask\b.*\b(before|first)\b/i;+/** How much of a prop the normaliser keeps (a Draft's body is the longest). */+const PROP_LIMITS: SanitizeLimits = { ...DEFAULT_SANITIZE_LIMITS, maxIdLength: LIMITS.maxIdLength, maxString: LIMITS.maxBody };+/** A button's params: shorter strings, shallower values. */+const PARAM_LIMITS: SanitizeLimits = { ...PROP_LIMITS, maxString: LIMITS.maxText, maxDepth: 4, maxArray: 20 };+type Elements = Map<string, SpecElement>;function isRecord(value: unknown): value is Record<string, unknown> {@@ -82,17 +115,54 @@ function text(value: unknown): string {return typeof value === 'string' || typeof value === 'number' ? String(value).trim() : '';}-/** Buttons need a label and a known action; an agent card needs a name. */-function keep(element: SpecElement): boolean {- if (element.type === 'Button') {- const action = actionOf(element.props.action);- if (!text(element.props.label) || !action) return false;- element.props.action = action;- if (action === 'refine') delete element.props.actionParams;- else if ('actionParams' in element.props) element.props.actionParams = sanitizeState(element.props.actionParams, LIMITS.maxText);+function pressBinding(action: ActionType, rawParams: unknown): PressBinding {+ if (action === 'refine') return { action };+ const params = sanitizeExpressions(rawParams ?? {}, PARAM_LIMITS, 1);+ return isRecord(params) && Object.keys(params).length > 0 ? { action, params } : { action };+}++/** The first binding under `on.press` (one, or a list) whose action is known. */+function pressOf(on: unknown): PressBinding | null {+ if (!isRecord(on)) return null;+ const bindings = Array.isArray(on.press) ? on.press : [on.press];+ for (const binding of bindings) {+ if (!isRecord(binding)) continue;+ const action = actionOf(binding.action);+ if (action) return pressBinding(action, binding.params);}- if (element.type === 'AgentCard' && !text(element.props.name)) return false;- return true;+ return null;+}++/** A Button's action: `on.press` beside its props (json-render's place), or+ * inside them, else the older `action` / `actionParams` props. */+function buttonPress(raw: Record<string, unknown>, written: Record<string, unknown>): PressBinding | null {+ const pressed = pressOf(raw.on) ?? pressOf(written.on);+ if (pressed) return pressed;+ const action = actionOf(written.action);+ return action ? pressBinding(action, written.actionParams) : null;+}++/** One element as the renderer will get it; null when it cannot be used: a+ * Button needs a label and a known action, an agent card a name. */+function shape(type: ComponentType, written: Record<string, unknown>, raw: Record<string, unknown>, children: string[]): SpecElement | null {+ const press = type === 'Button' ? buttonPress(raw, written) : null;+ if (type === 'Button' && (!text(written.label) || !press)) return null;+ if (type === 'AgentCard' && !text(written.name)) return null;+ delete written.on;+ if (type === 'Button') {+ delete written.action;+ delete written.actionParams;+ }+ if (type === 'Toggle') {+ if (!('checked' in written) && 'value' in written) written.checked = written.value;+ delete written.value;+ }+ const props = sanitizeExpressions(written, PROP_LIMITS);+ const element: SpecElement = { type, props: isRecord(props) ? props : {}, children };+ const visible = sanitizeCondition(raw.visible, PROP_LIMITS);+ if (visible !== undefined) element.visible = visible;+ if (press) element.on = { press };+ return element;}function collect(raw: Record<string, unknown>): Elements {@@ -100,21 +170,20 @@ function collect(raw: Record<string, unknown>): Elements {for (const [id, value] of Object.entries(raw)) {if (out.size >= MAX_RAW_ELEMENTS) break;if (!usableId(id) || !isRecord(value) || !isComponentType(value.type)) continue;- const props: Record<string, unknown> = {};+ const written: Record<string, unknown> = {};for (const key of Object.keys(value)) {- if (!META_KEYS.has(key) && !isForbiddenKey(key)) props[key] = value[key];+ if (!META_KEYS.has(key) && !isForbiddenKey(key)) written[key] = value[key];}if (isRecord(value.props)) {for (const key of Object.keys(value.props)) {- if (!isForbiddenKey(key)) props[key] = value.props[key];+ if (!isForbiddenKey(key)) written[key] = value.props[key];}}const children = Array.isArray(value.children)? value.children.filter((child): child is string => typeof child === 'string'): [];- const element: SpecElement = { type: value.type, props, children };- if ('visible' in value) element.visible = value.visible;- if (keep(element)) out.set(id, element);+ const element = shape(value.type, written, value, children);+ if (element) out.set(id, element);}return out;}@@ -132,8 +201,8 @@ function isHorizontalStack(element: SpecElement): boolean {return element.type === 'Stack' && element.props.direction === 'horizontal';}-function buttonAction(element: SpecElement | undefined): string | null {- return element?.type === 'Button' ? String(element.props.action) : null;+function buttonAction(element: SpecElement | undefined): ActionType | null {+ return element?.type === 'Button' ? (element.on?.press.action ?? null) : null;}/** Attach `id`'s subtree: keep only children that exist and are not yet@@ -180,7 +249,7 @@ function removeEverywhere(elements: Elements, id: string): void {function seedTrigger(elements: Elements, root: string, state: UiState): HireTrigger {const tree = depthFirst(elements, root).map((id) => elements.get(id)!);const hire = tree.find((element) => buttonAction(element) === 'hire_employee');- const params = resolveValue(hire?.props.actionParams, state);+ const params = resolveValue(hire?.on?.press.params, state);const given = readTrigger(isRecord(params) ? params.trigger : undefined);if (given && (given.kind !== 'app_event' || given.app)) return given;const plan = tree.find((element) => element.type === 'Plan');@@ -189,6 +258,19 @@ function seedTrigger(elements: Elements, root: string, state: UiState): HireTrigreturn snapTrigger(app ? { kind: 'app_event', app } : { kind: 'manual' });}+function hireButton(agent: SpecElement | undefined): SpecElement {+ const name = text(agent?.props.name);+ const role = text(agent?.props.role);+ const apps = Array.isArray(agent?.props.apps) ? agent!.props.apps.filter((app) => typeof app === 'string') : [];+ const params = { ...(name ? { name } : {}), ...(role ? { role } : {}), apps };+ return {+ type: 'Button',+ props: { label: name ? `Hire ${name}` : 'Hire them', variant: 'primary' },+ on: { press: { action: 'hire_employee', params } },+ children: [],+ };+}+export function normalizeSpec(spec: unknown): NormalizedSpec | null {if (!isRecord(spec) || !isRecord(spec.elements)) return null;const elements = collect(spec.elements);@@ -279,7 +361,7 @@ export function normalizeSpec(spec: unknown): NormalizedSpec | null {const order = depthFirst(elements, root);let askFirst = order.find((id) => {const element = elements.get(id)!;- return element.type === 'Toggle' && bindingPath(element.props.value) === STATE_PATHS.askFirst;+ return element.type === 'Toggle' && bindingPath(element.props.checked) === STATE_PATHS.askFirst;});if (!askFirst) {const worded = order.find((id) => {@@ -288,8 +370,8 @@ export function normalizeSpec(spec: unknown): NormalizedSpec | null {});if (worded) {const element = elements.get(worded)!;- const previous = getPath(state, bindingPath(element.props.value));- element.props.value = { $bindState: STATE_PATHS.askFirst };+ const previous = getPath(state, bindingPath(element.props.checked));+ element.props.checked = { $bindState: STATE_PATHS.askFirst };if (typeof previous === 'boolean') state = setPath(state, STATE_PATHS.askFirst, previous);askFirst = worded;}@@ -297,7 +379,6 @@ export function normalizeSpec(spec: unknown): NormalizedSpec | null {if (typeof getPath(state, STATE_PATHS.askFirst) !== 'boolean') state = setPath(state, STATE_PATHS.askFirst, true);const agent = order.map((id) => elements.get(id)!).find((element) => element.type === 'AgentCard');- const name = text(agent?.props.name);const hasHire = order.some((id) => buttonAction(elements.get(id)) === 'hire_employee');const hasChange = order.some((id) => buttonAction(elements.get(id)) === 'refine');const actionRow = () =>@@ -309,22 +390,17 @@ export function normalizeSpec(spec: unknown): NormalizedSpec | null {const added: string[] = [];if (!hasHire) {const id = freshId(elements, '__hire');- const apps = Array.isArray(agent?.props.apps) ? agent!.props.apps.filter((app) => typeof app === 'string') : [];- elements.set(id, {- type: 'Button',- props: {- label: name ? `Hire ${name}` : 'Hire them',- variant: 'primary',- action: 'hire_employee',- actionParams: { name: name || undefined, role: text(agent?.props.role) || undefined, apps },- },- children: [],- });+ elements.set(id, hireButton(agent));added.push(id);}if (!hasChange) {const id = freshId(elements, '__edit');- elements.set(id, { type: 'Button', props: { label: 'Change something', variant: 'secondary', action: 'refine' }, children: [] });+ elements.set(id, {+ type: 'Button',+ props: { label: 'Change something', variant: 'secondary' },+ on: { press: { action: 'refine' } },+ children: [],+ });added.push(id);}let host = actionRow();@@ -352,7 +428,7 @@ export function normalizeSpec(spec: unknown): NormalizedSpec | null {askFirst = freshId(elements, '__askFirst');elements.set(askFirst, {type: 'Toggle',- props: { label: ASK_FIRST_LABEL, value: { $bindState: STATE_PATHS.askFirst } },+ props: { label: ASK_FIRST_LABEL, checked: { $bindState: STATE_PATHS.askFirst } },children: [],});attach(host, [askFirst]);@@ -409,6 +485,7 @@ export function normalizeSpec(spec: unknown): NormalizedSpec | null {}}+ // No prototype: ids are looked up here as keys.const record: Record<string, SpecElement> = Object.create(null);for (const [id, element] of elements) record[id] = element;return { root, state, elements: record, order: depthFirst(elements, root) };diff --git a/client/src/features/home/genui/registry.ts b/client/src/features/home/genui/registry.tsnew file mode 100644index 00000000..d22597d9--- /dev/null+++ b/client/src/features/home/genui/registry.ts@@ -0,0 +1,61 @@+/**+ * The setup screen for json-render: the hire catalogue (catalog.ts's+ * HIRE_CATALOG) and its registry, a guarded component for each of the 18+ * types (views.tsx drawn through lib/jsonRender/guard.tsx, which reads each+ * element's props through the catalogue's forgiving schema first, so an odd+ * value degrades one prop rather than the element).+ *+ * The catalogue is defined here rather than in catalog.ts because this+ * module loads only with the screen (HireScreen), while catalog.ts is in+ * Home's first chunk; defining it there would bring json-render along.+ */++import { defineCatalog } from '@json-render/core';+import { defineRegistry, schema } from '@json-render/react';+import { guarded } from '@/lib/jsonRender';+import { HIRE_CATALOG, PROP_SCHEMAS } from './catalog';+import {+ AgentCardView,+ BadgeView,+ ButtonView,+ CardView,+ ChoiceView,+ DividerView,+ DraftView,+ GridView,+ HeadingView,+ InputView,+ ListView,+ MetricView,+ PlanView,+ ProgressView,+ ScheduleView,+ StackView,+ TextView,+ ToggleView,+} from './views';++export const hireCatalog = defineCatalog(schema, HIRE_CATALOG);++export const { registry: hireRegistry } = defineRegistry(hireCatalog, {+ components: {+ Stack: guarded('Stack', PROP_SCHEMAS.Stack, StackView),+ Grid: guarded('Grid', PROP_SCHEMAS.Grid, GridView),+ Card: guarded('Card', PROP_SCHEMAS.Card, CardView),+ Heading: guarded('Heading', PROP_SCHEMAS.Heading, HeadingView),+ Text: guarded('Text', PROP_SCHEMAS.Text, TextView),+ Metric: guarded('Metric', PROP_SCHEMAS.Metric, MetricView),+ Badge: guarded('Badge', PROP_SCHEMAS.Badge, BadgeView),+ Plan: guarded('Plan', PROP_SCHEMAS.Plan, PlanView),+ Schedule: guarded('Schedule', PROP_SCHEMAS.Schedule, ScheduleView),+ AgentCard: guarded('AgentCard', PROP_SCHEMAS.AgentCard, AgentCardView),+ List: guarded('List', PROP_SCHEMAS.List, ListView),+ Draft: guarded('Draft', PROP_SCHEMAS.Draft, DraftView),+ Progress: guarded('Progress', PROP_SCHEMAS.Progress, ProgressView),+ Toggle: guarded('Toggle', PROP_SCHEMAS.Toggle, ToggleView),+ Choice: guarded('Choice', PROP_SCHEMAS.Choice, ChoiceView),+ Input: guarded('Input', PROP_SCHEMAS.Input, InputView),+ Button: guarded('Button', PROP_SCHEMAS.Button, ButtonView),+ Divider: guarded('Divider', PROP_SCHEMAS.Divider, DividerView),+ },+});diff --git a/client/src/features/home/genui/useReveal.ts b/client/src/features/home/genui/useReveal.tsdeleted file mode 100644index 8decc272..00000000--- a/client/src/features/home/genui/useReveal.ts+++ /dev/null@@ -1,37 +0,0 @@-/**- * The setup screen appears one element at a time (design handoff: one- * every 90 ms, depth first), so a long screen reads as being written- * rather than dropped in. Everything shows at once under reduced motion or- * while the page is hidden. A new version starts again from nothing.- */--import { useEffect, useMemo, useState } from 'react';-import { motionSuppressed } from '@/lib/motion';--export const REVEAL_STEP_MS = 90;--export function useReveal(order: readonly string[], version: number): ReadonlySet<string> {- const [progress, setProgress] = useState({ version, count: 0 });- const count = progress.version === version ? progress.count : 0;- const total = order.length;-- useEffect(() => {- if (total === 0) return;- if (motionSuppressed()) {- setProgress({ version, count: total });- return;- }- const started = performance.now();- setProgress({ version, count: 1 });- const timer = window.setInterval(() => {- const next = motionSuppressed()- ? total- : Math.min(total, Math.floor((performance.now() - started) / REVEAL_STEP_MS) + 1);- setProgress({ version, count: next });- if (next >= total) window.clearInterval(timer);- }, REVEAL_STEP_MS);- return () => window.clearInterval(timer);- }, [version, total]);-- return useMemo(() => new Set(order.slice(0, count)), [order, count]);-}diff --git a/client/src/features/home/genui/render.tsx b/client/src/features/home/genui/views.tsxsimilarity index 62%rename from client/src/features/home/genui/render.tsxrename to client/src/features/home/genui/views.tsxindex a83395a8..c8b2f7a1 100644--- a/client/src/features/home/genui/render.tsx+++ b/client/src/features/home/genui/views.tsx@@ -1,42 +1,38 @@/**- * Draws a normalized setup screen. Every component here is private to the- * genui folder (lint keeps it that way); pages use HireDraftPanel.+ * The setup screen's 18 components, one per catalogue type, as json-render+ * draws them. registry.ts wraps each in the guard (lib/jsonRender/guard.tsx),+ * which reads the element's props through the catalogue's forgiving schema+ * first, so these get props already parsed, plus the ref that plays their+ * entrance. Private to the genui folder (lint keeps it that way), and+ * loaded only with the screen (HireScreen).*- * An element renders once the reveal reaches it and while its `visible`- * condition holds. Its props are resolved against the screen's state, then- * read through the catalogue's schema, so an odd value degrades one prop.- * Each element sits in its own error boundary: one that throws disappears- * and the rest of the screen stays.+ * Controls write through json-render's bindings: a Toggle's `checked`, a+ * Choice's and an Input's `value`, the Schedule's `value` (`/trigger`).+ * A Button presses its `on.press` binding (emit), which json-render+ * resolves against the screen's state and runs (actions.ts).** When they work (Schedule) reads as one plain sentence; Edit offers only* what the hire can build: the owner messaging them, a schedule at the* times it can run, or a new message in one of the apps the server says can* start the work. Once the owner changes it, the routine's "When" step- * follows.+ * follows (Plan reads the state at /trigger itself, beside its own props).*/-import {- Component,- createContext,- Fragment,- useCallback,- useContext,- useLayoutEffect,- useRef,- useState,- type ReactNode,-} from 'react';+import { Fragment, useContext, useLayoutEffect, useRef, useState, type ReactNode } from 'react';+import { useBoundProp, useStateValue } from '@json-render/react';import { ActionButton } from '@/components/ui/action-button';import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';import { Switch } from '@/components/ui/switch';import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';+import { useEntrance, type GuardedComponentProps } from '@/lib/jsonRender';import { animate } from '@/lib/motion';import { cn } from '@/lib/utils';import { MicroLabel } from '../ui/primitives';-import { PROP_SCHEMAS, STATE_PATHS, type ComponentType, type PropsOf, type StepRole, type Tone } from './catalog';-import { bindingPath, evalCondition, getPath, resolveValue, type UiState } from './expressions';+import { STATE_PATHS, type PROP_SCHEMAS, type PropsOf, type StepRole, type Tone } from './catalog';+import { getPath } from './expressions';+import { HireSpecContext } from './hireSpecContext';import {LAST_MONTH_DAY,SCHEDULE_EVERY,@@ -47,25 +43,9 @@ import {triggerSentence,type HireTrigger,} from './hirePayload';-import type { NormalizedSpec, SpecElement } from './normalize';--interface SpecContextValue {- spec: NormalizedSpec;- state: UiState;- revealed: ReadonlySet<string>;- onAction: (action: string, rawParams: unknown) => void;- onValue: (path: string, value: unknown) => void;- /** Apps that can start the work: any name the reply used -> the app's own name. */- triggerApps: Readonly<Record<string, string>>;-}+import { MessagePreview } from './MessagePreview';-const SpecContext = createContext<SpecContextValue | null>(null);--function useSpec(): SpecContextValue {- const value = useContext(SpecContext);- if (!value) throw new Error('Setup-screen components render inside SpecView');- return value;-}+type ViewProps<T extends keyof typeof PROP_SCHEMAS> = GuardedComponentProps<PropsOf<T>>;// ----- token maps (Tailwind scans these literals) -----@@ -142,35 +122,17 @@ const AGENT_STATUS = {paused: { label: 'Paused', dot: 'bg-status-paused-dot', ink: 'text-status-paused-ink' },} as const;-/** A soft entrance the first time an element appears. */-function useEnter<T extends HTMLElement>() {- const done = useRef(false);- return useCallback((node: T | null) => {- if (!node || done.current) return;- done.current = true;- animate(- node,- [- { opacity: 0, transform: 'translateY(8px) scale(.985)', filter: 'blur(3px)' },- { opacity: 1, transform: 'none', filter: 'blur(0)' },- ],- { duration: 440 },- );- }, []);-}-function Pip({ className }: { className?: string }) {return <span aria-hidden className={cn('size-1.75 shrink-0 rounded-full', className)} />;}// ----- components ------function StackView({ props, children }: { props: PropsOf<'Stack'>; children: ReactNode }) {- const enter = useEnter<HTMLDivElement>();+export function StackView({ props, children, enterRef }: ViewProps<'Stack'>) {const horizontal = props.direction === 'horizontal';return (<div- ref={enter}+ ref={enterRef}className={cn('flex min-w-0', STACK_GAP[props.gap], horizontal ? 'flex-row flex-wrap items-center' : 'flex-col')}>{children}@@ -178,11 +140,10 @@ function StackView({ props, children }: { props: PropsOf<'Stack'>; children: Rea);}-function GridView({ props, children }: { props: PropsOf<'Grid'>; children: ReactNode }) {- const enter = useEnter<HTMLDivElement>();+export function GridView({ props, children, enterRef }: ViewProps<'Grid'>) {return (<div- ref={enter}+ ref={enterRef}className={cn('grid gap-2.5',props.columns === 3 ? 'grid-cols-[repeat(auto-fit,minmax(150px,1fr))]' : 'grid-cols-[repeat(auto-fit,minmax(210px,1fr))]',@@ -193,10 +154,9 @@ function GridView({ props, children }: { props: PropsOf<'Grid'>; children: React);}-function CardView({ props, children }: { props: PropsOf<'Card'>; children: ReactNode }) {- const enter = useEnter<HTMLDivElement>();+export function CardView({ props, children, enterRef }: ViewProps<'Card'>) {return (- <div ref={enter} className={cn('flex flex-col gap-3 rounded-card border p-4', TONE_CARD[props.tone ?? 'neutral'])}>+ <div ref={enterRef} className={cn('flex flex-col gap-3 rounded-card border p-4', TONE_CARD[props.tone ?? 'neutral'])}>{(props.title || props.subtitle) && (<div className="flex flex-col gap-0.75">{props.title && <span className="text-lead font-semibold text-fg-default">{props.title}</span>}@@ -208,28 +168,25 @@ function CardView({ props, children }: { props: PropsOf<'Card'>; children: React);}-function HeadingView({ props }: { props: PropsOf<'Heading'> }) {- const enter = useEnter<HTMLHeadingElement>();+export function HeadingView({ props, enterRef }: ViewProps<'Heading'>) {return (- <h3 ref={enter} className="m-0 text-md font-semibold tracking-[-0.01em] text-fg-default">+ <h3 ref={enterRef} className="m-0 text-md font-semibold tracking-[-0.01em] text-fg-default">{props.text}</h3>);}-function TextView({ props }: { props: PropsOf<'Text'> }) {- const enter = useEnter<HTMLParagraphElement>();+export function TextView({ props, enterRef }: ViewProps<'Text'>) {return (- <p ref={enter} className={cn('m-0 text-base leading-relaxed text-pretty', props.muted ? 'text-fg-muted' : 'text-fg-default')}>+ <p ref={enterRef} className={cn('m-0 text-base leading-relaxed text-pretty', props.muted ? 'text-fg-muted' : 'text-fg-default')}>{props.text}</p>);}-function MetricView({ props }: { props: PropsOf<'Metric'> }) {- const enter = useEnter<HTMLDivElement>();+export function MetricView({ props, enterRef }: ViewProps<'Metric'>) {return (- <div ref={enter} className="flex flex-col gap-1 rounded-card border border-border-default bg-bg-elevated p-3.5">+ <div ref={enterRef} className="flex flex-col gap-1 rounded-card border border-border-default bg-bg-elevated p-3.5"><span className="text-xs text-fg-muted">{props.label}</span><span className={cn('text-xl font-semibold tracking-[-0.02em]', TONE_INK[props.tone ?? 'neutral'])}>{props.value}</span>{props.hint && <span className="text-xs text-fg-faint">{props.hint}</span>}@@ -237,11 +194,10 @@ function MetricView({ props }: { props: PropsOf<'Metric'> }) {);}-function BadgeView({ props }: { props: PropsOf<'Badge'> }) {- const enter = useEnter<HTMLSpanElement>();+export function BadgeView({ props, enterRef }: ViewProps<'Badge'>) {return (<span- ref={enter}+ ref={enterRef}className={cn('inline-flex h-5.5 items-center self-start rounded-pill border px-2.25 text-2xs font-medium whitespace-nowrap',TONE_BADGE[props.tone ?? 'neutral'],@@ -252,13 +208,12 @@ function BadgeView({ props }: { props: PropsOf<'Badge'> }) {);}-function DividerView() {- const enter = useEnter<HTMLDivElement>();- return <div ref={enter} className="h-px bg-border-default" />;+export function DividerView({ enterRef }: ViewProps<'Divider'>) {+ return <div ref={enterRef} className="h-px bg-border-default" />;}function PlanStep({ step }: { step: PropsOf<'Plan'>['steps'][number] }) {- const enter = useEnter<HTMLDivElement>();+ const enter = useEntrance<HTMLDivElement>();return (<divref={enter}@@ -280,14 +235,13 @@ function appNameOf(trigger: HireTrigger, triggerApps: Readonly<Record<string, streturn trigger.app ? (triggerApps[trigger.app.toLowerCase()] ?? trigger.app) : undefined;}-function PlanView({ props }: { props: PropsOf<'Plan'> }) {- const enter = useEnter<HTMLDivElement>();- const { spec, state, triggerApps } = useSpec();- const current = snapTrigger(getPath(state, STATE_PATHS.trigger));- const written = snapTrigger(getPath(spec.state, STATE_PATHS.trigger));+export function PlanView({ props, enterRef }: ViewProps<'Plan'>) {+ const { writtenState, triggerApps } = useContext(HireSpecContext);+ const current = snapTrigger(useStateValue<unknown>(STATE_PATHS.trigger));+ const written = snapTrigger(getPath(writtenState, STATE_PATHS.trigger));const steps = routineSteps(props.steps, written, current, appNameOf(current, triggerApps));return (- <div ref={enter} className="flex min-w-0 flex-col gap-3.5 rounded-card border border-border-default bg-bg-elevated p-4">+ <div ref={enterRef} className="flex min-w-0 flex-col gap-3.5 rounded-card border border-border-default bg-bg-elevated p-4"><div className="flex items-center gap-2"><span className="text-lead font-semibold text-fg-default">{props.title || 'Their routine'}</span><span className="ml-auto font-mono text-2xs text-fg-faint">@@ -346,28 +300,28 @@ function SchedulePicker({);}-function ScheduleView({ props, raw }: { props: PropsOf<'Schedule'>; raw: SpecElement['props'] }) {- const enter = useEnter<HTMLDivElement>();- const { onValue, triggerApps } = useSpec();+export function ScheduleView({ props, bindings, enterRef }: ViewProps<'Schedule'>) {+ const { triggerApps } = useContext(HireSpecContext);const [editing, setEditing] = useState(false);- const path = bindingPath(raw.value);+ const [, setValue] = useBoundProp<unknown>(props.value, bindings?.value);+ const bound = Boolean(bindings?.value);const trigger = snapTrigger(props.value);const appName = appNameOf(trigger, triggerApps);const apps = [...new Set(Object.values(triggerApps))];- const change = (next: HireTrigger) => path && onValue(path, snapTrigger(next));+ const change = (next: HireTrigger) => setValue(snapTrigger(next));const starts = trigger.kind === 'app_event' ? `app:${appName ?? ''}` : trigger.kind;const pickStart = (value: string) => {if (value === 'manual' || value === 'schedule') change({ kind: value });else change({ kind: 'app_event', app: value.slice('app:'.length) });};return (- <div ref={enter} className="flex flex-col gap-3 rounded-card border border-border-default bg-bg-elevated p-4">+ <div ref={enterRef} className="flex flex-col gap-3 rounded-card border border-border-default bg-bg-elevated p-4"><div className="flex items-center gap-3"><div className="flex min-w-0 flex-1 flex-col gap-1"><MicroLabel>When they work</MicroLabel><span className="text-base font-medium text-fg-default">{triggerSentence(trigger, appName)}</span></div>- {path && (+ {bound && (<Buttonvariant="quiet"aria-expanded={editing}@@ -378,7 +332,7 @@ function ScheduleView({ props, raw }: { props: PropsOf<'Schedule'>; raw: SpecEle</Button>)}</div>- {editing && path && (+ {editing && bound && (<div className="flex flex-col gap-3 border-t border-border-default pt-3"><ScheduleField label="What starts their work"><ToggleGroup@@ -456,11 +410,10 @@ function ScheduleView({ props, raw }: { props: PropsOf<'Schedule'>; raw: SpecEle);}-function AgentCardView({ props }: { props: PropsOf<'AgentCard'> }) {- const enter = useEnter<HTMLDivElement>();+export function AgentCardView({ props, enterRef }: ViewProps<'AgentCard'>) {const status = AGENT_STATUS[props.status];return (- <div ref={enter} className={cn('flex gap-3.5 rounded-card border p-4', TONE_CARD.agent)}>+ <div ref={enterRef} className={cn('flex gap-3.5 rounded-card border p-4', TONE_CARD.agent)}><spanaria-hiddenclassName="grid size-10.5 shrink-0 place-items-center rounded-full border-2 border-node-agent-edge bg-node-agent-fill text-md font-semibold text-node-agent-ink"@@ -494,10 +447,9 @@ function AgentCardView({ props }: { props: PropsOf<'AgentCard'> }) {);}-function ListView({ props }: { props: PropsOf<'List'> }) {- const enter = useEnter<HTMLDivElement>();+export function ListView({ props, enterRef }: ViewProps<'List'>) {return (- <div ref={enter} className="flex flex-col rounded-card border border-border-default bg-bg-elevated p-1.5">+ <div ref={enterRef} className="flex flex-col rounded-card border border-border-default bg-bg-elevated p-1.5">{props.items.map((item, index) => (<div key={index} className={cn('flex items-start gap-2.5 p-2.5', index > 0 && 'border-t border-border-default')}><Pip className={cn('mt-1.5', TONE_DOT[item.tone ?? 'neutral'])} />@@ -512,44 +464,15 @@ function ListView({ props }: { props: PropsOf<'List'> }) {);}-/** A message waiting to go out: the channel, who it is for, the text.- * Shared with the approval step, which shows drafts the same way. */-export function MessagePreview({- channel,- to,- subject,- body,- className,-}: {- channel?: string;- to?: string;- subject?: string;- body: string;- className?: string;-}) {+export function DraftView({ props, enterRef }: ViewProps<'Draft'>) {return (- <div className={cn('overflow-hidden rounded-card border border-border-default bg-bg-elevated', className)}>- <div className="flex items-center gap-2 border-b border-border-default bg-bg-panel px-3.5 py-2.5">- <MicroLabel className="text-node-model-ink">{channel || 'Draft'}</MicroLabel>- <span className="truncate text-sm text-fg-muted">to {to || '…'}</span>- </div>- {subject && <div className="px-3.5 pt-3 text-base font-semibold text-fg-default">{subject}</div>}- <div className="px-3.5 pt-2.5 pb-3.5 text-base leading-relaxed whitespace-pre-wrap text-fg-default">{body}</div>- </div>- );-}--function DraftView({ props }: { props: PropsOf<'Draft'> }) {- const enter = useEnter<HTMLDivElement>();- return (- <div ref={enter}>+ <div ref={enterRef}><MessagePreview channel={props.channel} to={props.to} subject={props.subject} body={props.body} /></div>);}-function ProgressView({ props }: { props: PropsOf<'Progress'> }) {- const enter = useEnter<HTMLDivElement>();+export function ProgressView({ props, enterRef }: ViewProps<'Progress'>) {const barRef = useRef<HTMLDivElement>(null);const shown = useRef<number | null>(null);useLayoutEffect(() => {@@ -558,7 +481,7 @@ function ProgressView({ props }: { props: PropsOf<'Progress'> }) {animate(barRef.current, [{ width: '0%' }, { width: `${props.value}%` }], { duration: 900, easing: 'spring', fill: 'none' });}, [props.value]);return (- <div ref={enter} className="flex flex-col gap-1.5">+ <div ref={enterRef} className="flex flex-col gap-1.5"><div className="flex text-sm text-fg-muted">{props.label}<span className="ml-auto font-mono text-xs">{Math.round(props.value)}%</span>@@ -575,41 +498,31 @@ function ProgressView({ props }: { props: PropsOf<'Progress'> }) {);}-function ToggleView({ props, raw }: { props: PropsOf<'Toggle'>; raw: SpecElement['props'] }) {- const enter = useEnter<HTMLDivElement>();- const { onValue } = useSpec();- const path = bindingPath(raw.value);+export function ToggleView({ props, bindings, enterRef }: ViewProps<'Toggle'>) {+ const [, setChecked] = useBoundProp<boolean>(props.checked, bindings?.checked);return (- <div ref={enter} className="flex items-center gap-3.5 py-1">+ <div ref={enterRef} className="flex items-center gap-3.5 py-1"><div className="flex flex-1 flex-col gap-0.5"><span className="text-base font-medium text-fg-default">{props.label}</span>{props.description && <span className="text-meta text-fg-muted">{props.description}</span>}</div>- <Switch- size="md"- tone="run"- aria-label={props.label}- checked={props.value}- onCheckedChange={(next) => path && onValue(path, next)}- />+ <Switch size="md" tone="run" aria-label={props.label} checked={props.checked} onCheckedChange={setChecked} /></div>);}-function ChoiceView({ props, raw }: { props: PropsOf<'Choice'>; raw: SpecElement['props'] }) {- const enter = useEnter<HTMLDivElement>();- const { onValue } = useSpec();- const path = bindingPath(raw.value);+export function ChoiceView({ props, bindings, enterRef }: ViewProps<'Choice'>) {+ const [, setValue] = useBoundProp<string>(props.value, bindings?.value);if (props.options.length === 0) return null;return (- <div ref={enter} className="flex flex-col gap-1.5">+ <div ref={enterRef} className="flex flex-col gap-1.5"><span className="text-xs font-medium text-fg-muted">{props.label}</span><ToggleGrouptype="single"variant="segmented"aria-label={props.label}value={props.value ?? ''}- onValueChange={(next) => next && path && onValue(path, next)}+ onValueChange={(next) => next && setValue(next)}className="flex-wrap self-start">{props.options.map((option) => (@@ -622,35 +535,31 @@ function ChoiceView({ props, raw }: { props: PropsOf<'Choice'>; raw: SpecElement);}-function InputView({ props, raw }: { props: PropsOf<'Input'>; raw: SpecElement['props'] }) {- const enter = useEnter<HTMLLabelElement>();- const { onValue } = useSpec();- const path = bindingPath(raw.value);+export function InputView({ props, bindings, enterRef }: ViewProps<'Input'>) {+ const [, setValue] = useBoundProp<string>(props.value, bindings?.value);return (- <label ref={enter} className="flex flex-col gap-1.5 text-xs font-medium text-fg-muted">+ <label ref={enterRef} className="flex flex-col gap-1.5 text-xs font-medium text-fg-muted">{props.label}<Inputvalue={props.value}placeholder={props.placeholder}maxLength={200}- disabled={!path}- onChange={(event) => path && onValue(path, event.target.value)}+ disabled={!bindings?.value}+ onChange={(event) => setValue(event.target.value)}className="h-9.5 rounded-lg bg-bg-app px-3 text-base font-normal text-fg-default md:text-base dark:bg-bg-app"/></label>);}-function ButtonView({ props, raw }: { props: PropsOf<'Button'>; raw: SpecElement['props'] }) {- const { onAction } = useSpec();- const enter = useEnter<HTMLButtonElement>();- const run = () => onAction(props.action, raw.actionParams);+export function ButtonView({ props, emit, enterRef }: ViewProps<'Button'>) {+ const press = () => emit('press');if (props.variant === 'primary') {return (<ActionButton- ref={enter}+ ref={enterRef}intent="run"- onClick={run}+ onClick={press}className="h-8.5 self-start rounded-lg px-4 whitespace-nowrap active:translate-y-px">{props.label}@@ -659,89 +568,12 @@ function ButtonView({ props, raw }: { props: PropsOf<'Button'>; raw: SpecElement}return (<Button- ref={enter}+ ref={enterRef}variant="quiet"- onClick={run}+ onClick={press}className="h-8.5 self-start rounded-lg border-border-strong px-3.5 font-semibold text-fg-default">{props.label}</Button>);}--// ----- tree -------class ElementBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {- state = { failed: false };- static getDerivedStateFromError() {- return { failed: true };- }- componentDidCatch(error: unknown) {- console.warn('[genui] a setup-screen element failed to render', error);- }- render() {- return this.state.failed ? null : this.props.children;- }-}--function renderLeaf(type: ComponentType, props: unknown, raw: SpecElement['props'], children: ReactNode): ReactNode {- switch (type) {- case 'Stack':- return <StackView props={props as PropsOf<'Stack'>}>{children}</StackView>;- case 'Grid':- return <GridView props={props as PropsOf<'Grid'>}>{children}</GridView>;- case 'Card':- return <CardView props={props as PropsOf<'Card'>}>{children}</CardView>;- case 'Heading':- return <HeadingView props={props as PropsOf<'Heading'>} />;- case 'Text':- return <TextView props={props as PropsOf<'Text'>} />;- case 'Metric':- return <MetricView props={props as PropsOf<'Metric'>} />;- case 'Badge':- return <BadgeView props={props as PropsOf<'Badge'>} />;- case 'Plan':- return <PlanView props={props as PropsOf<'Plan'>} />;- case 'Schedule':- return <ScheduleView props={props as PropsOf<'Schedule'>} raw={raw} />;- case 'AgentCard':- return <AgentCardView props={props as PropsOf<'AgentCard'>} />;- case 'List':- return <ListView props={props as PropsOf<'List'>} />;- case 'Draft':- return <DraftView props={props as PropsOf<'Draft'>} />;- case 'Progress':- return <ProgressView props={props as PropsOf<'Progress'>} />;- case 'Toggle':- return <ToggleView props={props as PropsOf<'Toggle'>} raw={raw} />;- case 'Choice':- return <ChoiceView props={props as PropsOf<'Choice'>} raw={raw} />;- case 'Input':- return <InputView props={props as PropsOf<'Input'>} raw={raw} />;- case 'Button':- return <ButtonView props={props as PropsOf<'Button'>} raw={raw} />;- case 'Divider':- return <DividerView />;- }-}--function SpecNode({ id }: { id: string }) {- const { spec, state, revealed } = useSpec();- const element = spec.elements[id];- if (!element || !revealed.has(id)) return null;- if (element.visible !== undefined && !evalCondition(element.visible, state)) return null;- const parsed = PROP_SCHEMAS[element.type].safeParse(resolveValue(element.props, state) ?? {});- if (!parsed.success) return null;- const children = element.children.map((child) => <SpecNode key={child} id={child} />);- return <ElementBoundary>{renderLeaf(element.type, parsed.data, element.props, children)}</ElementBoundary>;-}--export function SpecView({ spec, state, revealed, onAction, onValue, triggerApps }: SpecContextValue) {- return (- <SpecContext.Provider value={{ spec, state, revealed, onAction, onValue, triggerApps }}>- <div className="flex min-w-0 flex-col gap-3">- <SpecNode id={spec.root} />- </div>- </SpecContext.Provider>- );-}diff --git a/client/src/lib/jsonRender/SpecInspector.tsx b/client/src/lib/jsonRender/SpecInspector.tsxnew file mode 100644index 00000000..e92f8f29--- /dev/null+++ b/client/src/lib/jsonRender/SpecInspector.tsx@@ -0,0 +1,61 @@+/**+ * A developer's view of a generated UI: the spec as JSON, and the patch+ * stream that builds it (one JSON patch per line, as the chat protocol+ * streams it). Render it only in development builds+ * (`import.meta.env.DEV && <SpecInspector ... />`) so release builds drop it.+ */++import { Code } from 'lucide-react';+import { useMemo, useState } from 'react';+import type { Spec } from '@json-render/core';+import { Button } from '@/components/ui/button';+import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';+import { specToPatches } from './reveal';++const CODE_CLASS =+ 'm-0 max-h-70 overflow-auto rounded-row border border-border-default bg-bg-app px-3.5 py-3 font-mono text-2xs leading-normal whitespace-pre text-fg-muted';++export function SpecInspector({ spec, label = 'Layout JSON' }: { spec: Spec; label?: string }) {+ const [open, setOpen] = useState(false);+ const specJson = useMemo(() => JSON.stringify(spec, null, 2), [spec]);+ const patchLines = useMemo(+ () =>+ specToPatches(spec)+ .map((patch) => JSON.stringify(patch))+ .join('\n'),+ [spec],+ );+ return (+ <div className="flex flex-col gap-2">+ <Button+ variant="quiet"+ size="xs"+ onClick={() => setOpen((on) => !on)}+ title="See what the assistant generated"+ aria-expanded={open}+ className="gap-1.5 self-start font-mono text-2xs font-normal text-fg-faint hover:border-border-default hover:bg-transparent hover:text-fg-muted"+ >+ <Code aria-hidden />+ {open ? `Hide ${label}` : label}+ </Button>+ {open && (+ <Tabs defaultValue="spec" className="gap-2">+ <TabsList variant="line" className="h-7">+ <TabsTrigger value="spec" className="font-mono text-2xs">+ spec.json+ </TabsTrigger>+ <TabsTrigger value="patches" className="font-mono text-2xs">+ patches.jsonl+ </TabsTrigger>+ </TabsList>+ <TabsContent value="spec">+ <pre className={CODE_CLASS}>{specJson}</pre>+ </TabsContent>+ <TabsContent value="patches">+ <pre className={CODE_CLASS}>{patchLines}</pre>+ </TabsContent>+ </Tabs>+ )}+ </div>+ );+}diff --git a/client/src/lib/jsonRender/__tests__/guard.test.tsx b/client/src/lib/jsonRender/__tests__/guard.test.tsxnew file mode 100644index 00000000..c6a50ab4--- /dev/null+++ b/client/src/lib/jsonRender/__tests__/guard.test.tsx@@ -0,0 +1,157 @@+/**+ * The guard, rendered through json-render: props are read through the+ * component's schema with one bad prop degrading only itself, an element+ * that throws disappears alone (json-render's own boundary), a parent rule+ * holds, and the entrance plays once and only for a live UI.+ */++import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest';+import { act, render, screen } from '@testing-library/react';+import { defineCatalog, type Spec } from '@json-render/core';+import { JSONUIProvider, Renderer, defineRegistry, schema } from '@json-render/react';+import { z } from 'zod';+import { installWaapiStub } from '@/test/waapi';+import { LiveUiContext, guarded, parseProps, type GuardedComponentProps } from '../guard';+import { createUiStateStore } from '../uiState';++const Label = z.object({ title: z.string(), tone: z.enum(['calm', 'loud']).optional() });+const Box = z.object({});++function LabelView({ props, enterRef }: GuardedComponentProps<z.output<typeof Label>>) {+ return (+ <p ref={enterRef} data-tone={props.tone ?? 'none'}>+ {props.title}+ </p>+ );+}++function BoxView({ children, enterRef }: GuardedComponentProps<z.output<typeof Box>>) {+ return (+ <div ref={enterRef} data-testid="box">+ {children}+ </div>+ );+}++function Boom(): never {+ throw new Error('boom');+}++const catalog = defineCatalog(schema, {+ components: { Box: { props: Box }, Label: { props: Label }, Boom: { props: Box }, Nested: { props: Label } },+ actions: {},+});++const { registry } = defineRegistry(catalog, {+ components: {+ Box: guarded('Box', Box, BoxView),+ Label: guarded('Label', Label, LabelView),+ Boom: guarded('Boom', Box, Boom),+ Nested: guarded('Nested', Label, LabelView, { parents: ['Box'] }),+ },+});++function show(spec: Spec, live = false) {+ const store = createUiStateStore(spec.state ?? {});+ const view = render(+ <LiveUiContext.Provider value={live}>+ <JSONUIProvider registry={registry} store={store}>+ <Renderer spec={spec} registry={registry} />+ </JSONUIProvider>+ </LiveUiContext.Provider>,+ );+ return { ...view, store };+}++function box(children: Record<string, { type: string; props: Record<string, unknown> }>, state: Record<string, unknown> = {}): Spec {+ return { root: 'root', state, elements: { root: { type: 'Box', props: {}, children: Object.keys(children) }, ...children } };+}++describe('guarded', () => {+ let errors: MockInstance<typeof console.error>;++ beforeEach(() => {+ errors = vi.spyOn(console, 'error').mockImplementation(() => {});+ });++ afterEach(() => {+ errors.mockRestore();+ });++ it('degrades a bad prop to its default and drops an element missing a required one', () => {+ show(+ box({+ good: { type: 'Label', props: { title: 'Hello', tone: 'loud' } },+ odd: { type: 'Label', props: { title: 'Odd', tone: 'purple' } },+ bare: { type: 'Label', props: { tone: 'calm' } },+ }),+ );+ expect(screen.getByText('Hello')).toHaveAttribute('data-tone', 'loud');+ expect(screen.getByText('Odd')).toHaveAttribute('data-tone', 'none');+ expect(screen.getByTestId('box').children).toHaveLength(2);+ });++ it('reads props as json-render resolved them from state', () => {+ const { store } = show(box({ name: { type: 'Label', props: { title: { $state: '/name' } } } }, { name: 'Ana' }));+ expect(screen.getByText('Ana')).toBeInTheDocument();+ act(() => store.set('/name', 'Bo'));+ expect(screen.getByText('Bo')).toBeInTheDocument();+ });++ it('isolates an element that throws', () => {+ show(+ box({+ before: { type: 'Label', props: { title: 'Before' } },+ boom: { type: 'Boom', props: {} },+ after: { type: 'Label', props: { title: 'After' } },+ }),+ );+ expect(screen.getByText('Before')).toBeInTheDocument();+ expect(screen.getByText('After')).toBeInTheDocument();+ expect(errors).toHaveBeenCalled();+ });++ it('holds a component to the parents it may appear under', () => {+ show(box({ inside: { type: 'Nested', props: { title: 'Inside a box' } } }));+ expect(screen.getByText('Inside a box')).toBeInTheDocument();+ show({ root: 'alone', elements: { alone: { type: 'Nested', props: { title: 'At the root' } } } });+ expect(screen.queryByText('At the root')).not.toBeInTheDocument();+ });+});++describe('the entrance', () => {+ let waapi: ReturnType<typeof installWaapiStub>;++ beforeEach(() => {+ waapi = installWaapiStub();+ });++ afterEach(() => {+ waapi.restore();+ });++ it('plays once for each element of a live UI', () => {+ const { store } = show(box({ name: { type: 'Label', props: { title: { $state: '/name' } } } }, { name: 'Ana' }), true);+ expect(waapi.callsFor(screen.getByTestId('box'))).toHaveLength(1);+ expect(waapi.callsFor(screen.getByText('Ana'))).toHaveLength(1);+ expect(waapi.calls[0].options).toMatchObject({ duration: 420 });+ act(() => store.set('/name', 'Bo'));+ expect(waapi.calls).toHaveLength(2);+ });++ it('does not play for a UI shown again from history', () => {+ show(box({ name: { type: 'Label', props: { title: 'Old' } } }), false);+ expect(screen.getByText('Old')).toBeInTheDocument();+ expect(waapi.calls).toHaveLength(0);+ });+});++describe('parseProps', () => {+ it('reads all props at once when they pass, else one at a time', () => {+ expect(parseProps(Label, { title: 'A', tone: 'calm', extra: 1 })).toEqual({ title: 'A', tone: 'calm' });+ expect(parseProps(Label, { title: 'A', tone: 7 })).toEqual({ title: 'A' });+ expect(parseProps(Label, { tone: 'calm' })).toBeNull();+ expect(parseProps(Label, 'not props')).toBeNull();+ expect(parseProps(z.string(), 5)).toBeNull();+ });+});diff --git a/client/src/lib/jsonRender/__tests__/reveal.test.tsx b/client/src/lib/jsonRender/__tests__/reveal.test.tsxnew file mode 100644index 00000000..1ac4c31c--- /dev/null+++ b/client/src/lib/jsonRender/__tests__/reveal.test.tsx@@ -0,0 +1,130 @@+/**+ * The patch stream for a spec (root, state, then each element depth first,+ * ids escaped as RFC 6901 says), held line for line against the chat+ * fixtures, and its paced replay: one element every 90 ms, everything at+ * once under reduced motion, from nothing again for a new version.+ */++import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { act, renderHook } from '@testing-library/react';+import type { Spec } from '@json-render/core';+import { setReducedMotion } from '@/test/waapi';+import { REVEAL_STEP_MS, specFromPatches, specToPatches, useSpecReveal } from '../reveal';++const FIXTURES = join(__dirname, '..', '..', '..', 'features', 'chat', '__fixtures__');++function read(name: string): string {+ return readFileSync(join(FIXTURES, name), 'utf-8');+}++const SPEC: Spec = {+ root: 'r',+ state: { on: true },+ elements: {+ r: { type: 'Stack', props: {}, children: ['a', 'b/c', 'r'] },+ a: { type: 'Card', props: {}, children: ['a1', 'missing', 'a2'] },+ a1: { type: 'Text', props: { text: '1' } },+ a2: { type: 'Text', props: { text: '2' } },+ 'b/c': { type: 'Text', props: { text: 'slash' }, children: ['a1'] },+ 'x~y': { type: 'Text', props: { text: 'unreachable' } },+ },+};++describe('specToPatches', () => {+ it.each(['saturday-booking', 'reply-insights', 'reminders'])('matches %s.patches.jsonl line by line', (name) => {+ const spec = JSON.parse(read(`${name}.spec.json`)) as Spec;+ const lines = read(`${name}.patches.jsonl`)+ .split(/\r?\n/)+ .filter((line) => line.trim() !== '');+ const patches = specToPatches(spec).map((patch) => JSON.stringify(patch));+ expect(patches).toEqual(lines);+ });++ it('walks depth first from the root, each element once, escaping ids', () => {+ expect(specToPatches(SPEC).map((patch) => patch.path)).toEqual([+ '/root',+ '/state',+ '/elements/r',+ '/elements/a',+ '/elements/a1',+ '/elements/a2',+ '/elements/b~1c',+ ]);+ expect(specToPatches({ root: 'r', elements: {} })).toEqual([+ { op: 'add', path: '/root', value: 'r' },+ { op: 'add', path: '/state', value: {} },+ ]);+ });++ it('builds the spec back, a prefix at a time', () => {+ const patches = specToPatches(SPEC);+ expect(specFromPatches(patches)).toEqual({+ root: 'r',+ state: { on: true },+ elements: { r: SPEC.elements.r, a: SPEC.elements.a, a1: SPEC.elements.a1, a2: SPEC.elements.a2, 'b/c': SPEC.elements['b/c'] },+ });+ expect(Object.keys(specFromPatches(patches, 4).elements)).toEqual(['r', 'a']);+ });+});++describe('useSpecReveal', () => {+ let restoreMotion: () => void;++ beforeEach(() => {+ restoreMotion = setReducedMotion(false);+ vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval', 'performance'] });+ });++ afterEach(() => {+ vi.useRealTimers();+ restoreMotion();+ });++ const shownIds = (result: { current: ReturnType<typeof useSpecReveal> }) => Object.keys(result.current.spec?.elements ?? {});++ it('shows one element every REVEAL_STEP_MS, depth first', () => {+ const { result } = renderHook(() => useSpecReveal(SPEC, 1));+ expect(result.current.spec?.root).toBe('r');+ expect(shownIds(result)).toEqual(['r']);+ expect(result.current.revealing).toBe(true);+ act(() => {+ vi.advanceTimersByTime(REVEAL_STEP_MS);+ });+ expect(shownIds(result)).toEqual(['r', 'a']);+ act(() => {+ vi.advanceTimersByTime(REVEAL_STEP_MS * 2);+ });+ expect(shownIds(result)).toEqual(['r', 'a', 'a1', 'a2']);+ act(() => {+ vi.advanceTimersByTime(REVEAL_STEP_MS * 10);+ });+ expect(shownIds(result)).toEqual(['r', 'a', 'a1', 'a2', 'b/c']);+ expect(result.current.revealing).toBe(false);+ });++ it('starts again from nothing for a new version', () => {+ const { result, rerender } = renderHook(({ version }) => useSpecReveal(SPEC, version), { initialProps: { version: 1 } });+ act(() => {+ vi.advanceTimersByTime(REVEAL_STEP_MS * 10);+ });+ expect(shownIds(result)).toHaveLength(5);+ rerender({ version: 2 });+ expect(shownIds(result)).toEqual(['r']);+ expect(result.current.revealing).toBe(true);+ });++ it('shows everything at once under reduced motion', () => {+ restoreMotion();+ restoreMotion = setReducedMotion(true);+ const { result } = renderHook(() => useSpecReveal(SPEC, 1));+ expect(shownIds(result)).toEqual(['r', 'a', 'a1', 'a2', 'b/c']);+ expect(result.current.revealing).toBe(false);+ });++ it('has nothing to show without a spec', () => {+ const { result } = renderHook(() => useSpecReveal(null, 1));+ expect(result.current).toEqual({ spec: null, revealing: false });+ });+});diff --git a/client/src/lib/jsonRender/__tests__/sanitize.test.ts b/client/src/lib/jsonRender/__tests__/sanitize.test.tsnew file mode 100644index 00000000..18ee399b--- /dev/null+++ b/client/src/lib/jsonRender/__tests__/sanitize.test.ts@@ -0,0 +1,260 @@+/**+ * What reaches json-render: prototype keys and paths refused everywhere,+ * the features a model must not reach (watch, repeat, slots, $computed,+ * confirm, onSuccess / onError) stripped, patches limited to the places a+ * spec stream writes, and sizes capped.+ */++import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { describe, expect, it } from 'vitest';+import {+ DEFAULT_SANITIZE_LIMITS,+ MAX_PATCH_PATH,+ sanitizeActionBinding,+ sanitizeCondition,+ sanitizeElement,+ sanitizeExpressions,+ sanitizePatch,+ sanitizeSpec,+ sanitizeState,+} from '../sanitize';++const FIXTURES = join(__dirname, '..', '..', '..', 'features', 'chat', '__fixtures__');++function fixture(name: string): unknown {+ return JSON.parse(readFileSync(join(FIXTURES, `${name}.spec.json`), 'utf-8'));+}++describe('prototype keys', () => {+ it('drops them as object keys, element ids and state keys', () => {+ const raw = JSON.parse(+ '{"root":"r","state":{"__proto__":{"polluted":true},"ok":1,"constructor":{"prototype":{"x":1}}},' ++ '"elements":{"__proto__":{"type":"Text","props":{"text":"evil"}},"constructor":{"type":"Text","props":{}},' ++ '"r":{"type":"Stack","props":{"__proto__":{"polluted":true},"gap":"md","nested":{"prototype":1,"keep":2}},"children":["__proto__","a"]},' ++ '"a":{"type":"Text","props":{"text":"hi"}}}}',+ );+ const spec = sanitizeSpec(raw)!;+ expect(Object.keys(spec.elements)).toEqual(['r', 'a']);+ expect(Object.getPrototypeOf(spec.elements)).toBeNull();+ expect(spec.elements.r).toEqual({ type: 'Stack', props: { gap: 'md', nested: { keep: 2 } }, children: ['a'] });+ expect(spec.state).toEqual({ ok: 1 });+ expect(({} as Record<string, unknown>).polluted).toBeUndefined();+ });++ it('refuses a path through one in $state, $bindState, $template, visible and action params', () => {+ expect(sanitizeExpressions({ a: { $state: '/__proto__/x' }, b: { $bindState: '/x/constructor' }, c: { $state: '/ok' } })).toEqual({+ c: { $state: '/ok' },+ });+ expect(sanitizeExpressions({ $template: 'A ${/prototype/x} B ${ /name } C ${field}' })).toEqual({+ $template: 'A B ${/name} C ${/field}',+ });+ expect(sanitizeCondition({ $state: '/a/__proto__', eq: 1 })).toBe(false);+ expect(sanitizeCondition({ $state: '/ok', eq: { $state: '/constructor' } })).toEqual({ $state: '/ok', eq: null });+ expect(sanitizeActionBinding({ action: 'go', params: { to: { $state: '/__proto__' }, n: 1 } })).toEqual({+ action: 'go',+ params: { n: 1 },+ });+ // Escaped segments are read unescaped, as json-render reads them.+ expect(sanitizeExpressions({ $state: '/a~1b/c' })).toEqual({ $state: '/a~1b/c' });+ expect(sanitizeExpressions({ $state: '/prototype~0' })).toEqual({ $state: '/prototype~0' });+ });++ it('refuses them as action and event names', () => {+ expect(sanitizeActionBinding({ action: 'constructor' })).toBeNull();+ // JSON.parse makes "__proto__" an own key, as a model's reply would.+ const on = JSON.parse('{"__proto__":{"action":"go"},"press":{"action":"go"}}');+ expect(sanitizeElement({ type: 'Button', props: {}, on })).toEqual({+ type: 'Button',+ props: {},+ on: { press: { action: 'go' } },+ });+ });+});++describe('features a model must not reach', () => {+ it('strips watch, repeat and slots from an element, and keeps type, props, children, visible and on', () => {+ const element = sanitizeElement({+ type: 'Card',+ props: { title: 'T' },+ children: ['a'],+ visible: { $state: '/show' },+ on: { press: { action: 'go' } },+ watch: { '/x': { action: 'go' } },+ repeat: { statePath: '/items' },+ slots: { footer: ['b'] },+ key: 'k',+ });+ expect(element).toEqual({+ type: 'Card',+ props: { title: 'T' },+ children: ['a'],+ visible: { $state: '/show' },+ on: { press: { action: 'go' } },+ });+ });++ it('drops $computed, and $item, $index and $bindItem, which only work inside repeat', () => {+ expect(+ sanitizeExpressions({+ a: { $computed: 'secret', args: { x: 1 } },+ b: { $item: 'name' },+ c: { $index: true },+ d: { $bindItem: 'done' },+ e: [{ $computed: 'f' }, 'kept'],+ f: { $cond: { $state: '/x' }, $then: { $computed: 'f' }, $else: 'no' },+ }),+ ).toEqual({ e: ['kept'], f: { $cond: { $state: '/x' }, $then: null, $else: 'no' } });+ });++ it('keeps an action binding to its action and params', () => {+ expect(+ sanitizeActionBinding({+ action: 'save',+ params: { id: 1 },+ confirm: { title: 'Sure?', message: 'Really?' },+ onSuccess: { set: { '/__proto__/x': 1 } },+ onError: { action: 'other' },+ preventDefault: true,+ }),+ ).toEqual({ action: 'save', params: { id: 1 } });+ expect(sanitizeActionBinding({ action: '' })).toBeNull();+ expect(sanitizeActionBinding({ action: 'has space' })).toBeNull();+ });+});++describe('conditions', () => {+ it('canonicalizes what json-render reads differently', () => {+ expect(sanitizeCondition(undefined)).toBeUndefined();+ expect(sanitizeCondition(null)).toBeUndefined();+ expect(sanitizeCondition(true)).toBe(true);+ expect(sanitizeCondition([{ $state: '/a' }, { $state: 'b', not: 1 }])).toEqual({+ $and: [{ $state: '/a' }, { $state: '/b', not: true }],+ });+ expect(sanitizeCondition({ $or: [false, { $state: '/c', gt: 2, lt: { $state: '/d' } }] })).toEqual({+ $or: [false, { $state: '/c', gt: 2, lt: { $state: '/d' } }],+ });+ // Only meaningful inside repeat, or no shape at all: hidden.+ expect(sanitizeCondition({ $item: 'done' })).toBe(false);+ expect(sanitizeCondition({ eq: 1 })).toBe(false);+ expect(sanitizeCondition({ $and: 'nope' })).toBe(false);+ });+});++describe('sanitizeSpec', () => {+ it('needs a usable root and an elements object', () => {+ expect(sanitizeSpec(null)).toBeNull();+ expect(sanitizeSpec({ root: 'a', elements: [] })).toBeNull();+ expect(sanitizeSpec({ root: '__proto__', elements: {} })).toBeNull();+ expect(sanitizeSpec({ root: 'r', elements: {} })).toEqual({ root: 'r', state: {}, elements: {} });+ });++ it('caps elements, children, strings, arrays and depth', () => {+ const elements: Record<string, Record<string, unknown>> = Object.fromEntries(+ Array.from({ length: 80 }, (_, i) => [`e${i}`, { type: 'Text', props: { text: 'x'.repeat(5000) }, children: [] }]),+ );+ elements.e0.children = Array.from({ length: 100 }, (_, i) => `c${i}`);+ let deep: unknown = 'leaf';+ for (let i = 0; i < 20; i++) deep = { next: deep };+ elements.e1.props = { list: Array.from({ length: 80 }, (_, i) => i), deep };+ const spec = sanitizeSpec({ root: 'e0', elements })!;+ expect(Object.keys(spec.elements)).toHaveLength(DEFAULT_SANITIZE_LIMITS.maxElements);+ expect(spec.elements.e0.children).toHaveLength(DEFAULT_SANITIZE_LIMITS.maxChildren);+ expect(String(spec.elements.e2.props.text)).toHaveLength(DEFAULT_SANITIZE_LIMITS.maxString);+ expect(spec.elements.e1.props.list).toHaveLength(DEFAULT_SANITIZE_LIMITS.maxArray);+ expect(JSON.stringify(spec.elements.e1.props.deep).match(/next/g)!.length).toBeLessThan(20);+ });++ it('keeps the chat fixtures as they are, adding only empty props', () => {+ for (const name of ['saturday-booking', 'reply-insights', 'reminders']) {+ const raw = fixture(name) as { elements: Record<string, Record<string, unknown>> };+ const spec = sanitizeSpec(raw)!;+ expect(Object.keys(spec.elements)).toEqual(Object.keys(raw.elements));+ for (const [id, element] of Object.entries(raw.elements)) {+ expect(spec.elements[id]).toEqual({ props: {}, ...element });+ }+ }+ });+});++describe('sanitizePatch', () => {+ const element = { type: 'Text', props: { text: 'hi' } };++ it('takes add, replace and remove at the places a spec stream writes', () => {+ expect(sanitizePatch({ op: 'add', path: '/root', value: 'root' })).toEqual({ op: 'add', path: '/root', value: 'root' });+ expect(sanitizePatch({ op: 'add', path: '/state', value: JSON.parse('{"a":1,"__proto__":{"polluted":true}}') })).toEqual({+ op: 'add',+ path: '/state',+ value: { a: 1 },+ });+ expect(sanitizePatch({ op: 'replace', path: '/state/form/name', value: 'Ana' })).toEqual({+ op: 'replace',+ path: '/state/form/name',+ value: 'Ana',+ });+ expect(sanitizePatch({ op: 'add', path: '/elements/a', value: { ...element, watch: {} } })).toEqual({+ op: 'add',+ path: '/elements/a',+ value: element,+ });+ expect(sanitizePatch({ op: 'replace', path: '/elements/a/props/text', value: { $state: '/__proto__' } })).toBeNull();+ expect(sanitizePatch({ op: 'replace', path: '/elements/a/props/text', value: { $state: '/t' } })).toEqual({+ op: 'replace',+ path: '/elements/a/props/text',+ value: { $state: '/t' },+ });+ expect(sanitizePatch({ op: 'add', path: '/elements/a/children/-', value: 'b' })).toEqual({+ op: 'add',+ path: '/elements/a/children/-',+ value: 'b',+ });+ expect(sanitizePatch({ op: 'replace', path: '/elements/a/visible', value: [{ $state: '/x' }] })).toEqual({+ op: 'replace',+ path: '/elements/a/visible',+ value: { $and: [{ $state: '/x' }] },+ });+ expect(sanitizePatch({ op: 'add', path: '/elements/a/on/press', value: { action: 'go', confirm: {} } })).toEqual({+ op: 'add',+ path: '/elements/a/on/press',+ value: { action: 'go' },+ });+ expect(sanitizePatch({ op: 'remove', path: '/elements/a' })).toEqual({ op: 'remove', path: '/elements/a' });+ });++ it('refuses every other op, place and prototype path', () => {+ const refused = [+ { op: 'move', from: '/elements/a', path: '/elements/b' },+ { op: 'copy', from: '/elements/a', path: '/elements/b' },+ { op: 'test', path: '/root', value: 'r' },+ { op: 'add', path: '/foo', value: 1 },+ { op: 'add', path: 'root', value: 'r' },+ { op: 'remove', path: '/root' },+ { op: 'add', path: '/root', value: 'bad id' },+ { op: 'add', path: '/state/__proto__/polluted', value: true },+ { op: 'add', path: '/state/a/constructor', value: true },+ { op: 'add', path: '/elements/__proto__', value: element },+ { op: 'add', path: '/elements/a/props/constructor/prototype', value: 1 },+ { op: 'add', path: '/elements/a/watch', value: {} },+ { op: 'add', path: '/elements/a/repeat', value: { statePath: '/x' } },+ { op: 'add', path: '/elements/a/slots/footer', value: ['b'] },+ { op: 'add', path: '/elements/a/type', value: 'Text' },+ { op: 'add', path: '/elements/a/visible/0', value: true },+ { op: 'add', path: '/elements/a/children/x', value: 'b' },+ { op: 'add', path: '/elements/a/children/0/y', value: 'b' },+ { op: 'add', path: '/elements/a/on/constructor', value: { action: 'go' } },+ { op: 'add', path: '/elements/a', value: { type: 'not a name' } },+ { op: 'add', path: '/elements//props', value: {} },+ { op: 'add', path: `/state/${'a/'.repeat(10)}b`, value: 1 },+ { op: 'add', path: `/elements/${'a'.repeat(MAX_PATCH_PATH)}`, value: element },+ ];+ for (const patch of refused) expect(sanitizePatch(patch), JSON.stringify(patch).slice(0, 80)).toBeNull();+ expect(({} as Record<string, unknown>).polluted).toBeUndefined();+ });+});++describe('sanitizeState', () => {+ it('is plain JSON, always an object', () => {+ expect(sanitizeState([1, 2])).toEqual({});+ expect(sanitizeState({ n: Number.NaN, f: () => 1, s: 'x', ok: [true, null] })).toEqual({ s: 'x', ok: [true, null] });+ });+});diff --git a/client/src/lib/jsonRender/__tests__/uiState.test.ts b/client/src/lib/jsonRender/__tests__/uiState.test.tsnew file mode 100644index 00000000..3daeef25--- /dev/null+++ b/client/src/lib/jsonRender/__tests__/uiState.test.ts@@ -0,0 +1,82 @@+/**+ * The generated UI's state store: writes copy along the path and notify,+ * a forbidden path is refused (json-render's own store would walk into+ * `__proto__`), and every change reaches onChange in canonical form.+ */++import { describe, expect, it, vi } from 'vitest';+import { createUiStateStore } from '../uiState';++describe('createUiStateStore', () => {+ it('reads and writes by JSON Pointer, immutably, and tells listeners and onChange', () => {+ const onChange = vi.fn();+ const store = createUiStateStore({ rules: { askFirst: true }, list: ['a', 'b'] }, onChange);+ const listener = vi.fn();+ store.subscribe(listener);+ const before = store.getSnapshot();++ store.set('/rules/askFirst', false);+ expect(store.get('/rules/askFirst')).toBe(false);+ expect(store.getSnapshot()).not.toBe(before);+ expect(before).toEqual({ rules: { askFirst: true }, list: ['a', 'b'] });+ expect(store.getSnapshot().list).toBe(before.list);+ expect(listener).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenCalledWith([{ path: '/rules/askFirst', value: false }]);++ store.set('list/1', 'z');+ expect(store.get('/list')).toEqual(['a', 'z']);+ expect(onChange).toHaveBeenLastCalledWith([{ path: '/list/1', value: 'z' }]);+ });++ it('does nothing when the value is already there', () => {+ const onChange = vi.fn();+ const store = createUiStateStore({ a: 1 }, onChange);+ const listener = vi.fn();+ store.subscribe(listener);+ store.set('/a', 1);+ store.update({ '/a': 1 });+ expect(listener).not.toHaveBeenCalled();+ expect(onChange).not.toHaveBeenCalled();+ });++ it('refuses a path through __proto__, constructor or prototype', () => {+ const onChange = vi.fn();+ const store = createUiStateStore({ a: {} }, onChange);+ const before = store.getSnapshot();+ store.set('/__proto__/x', true);+ store.set('/a/constructor/prototype/polluted', true);+ store.set('/a/prototype', 1);+ store.update({ '/__proto__/y': 1, '/constructor': 2 });+ expect(store.getSnapshot()).toBe(before);+ expect(({} as Record<string, unknown>).x).toBeUndefined();+ expect(({} as Record<string, unknown>).polluted).toBeUndefined();+ expect(Object.getPrototypeOf(store.getSnapshot())).toBe(Object.prototype);+ expect(store.get('/__proto__')).toBeUndefined();+ expect(store.get('/a/constructor')).toBeUndefined();+ expect(onChange).not.toHaveBeenCalled();+ });++ it('applies an update as one change, skipping the paths it refuses', () => {+ const onChange = vi.fn();+ const store = createUiStateStore({}, onChange);+ const listener = vi.fn();+ store.subscribe(listener);+ store.update({ '/form/name': 'Ana', '/__proto__/x': 1, '/form/age': 30 });+ expect(store.getSnapshot()).toEqual({ form: { name: 'Ana', age: 30 } });+ expect(listener).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenCalledWith([+ { path: '/form/name', value: 'Ana' },+ { path: '/form/age', value: 30 },+ ]);+ });++ it('stops telling a listener once it unsubscribes', () => {+ const store = createUiStateStore();+ const listener = vi.fn();+ const unsubscribe = store.subscribe(listener);+ unsubscribe();+ store.set('/a', 1);+ expect(listener).not.toHaveBeenCalled();+ expect(store.getServerSnapshot?.()).toEqual({ a: 1 });+ });+});diff --git a/client/src/lib/jsonRender/guard.tsx b/client/src/lib/jsonRender/guard.tsxnew file mode 100644index 00000000..9edea036--- /dev/null+++ b/client/src/lib/jsonRender/guard.tsx@@ -0,0 +1,137 @@+/* eslint-disable react-refresh/only-export-components -- the guard element, its contexts and the entrance hook travel together; renderers use guarded()'s result, never this file's component. */+/**+ * The wrapper every generated-UI component goes through.+ *+ * json-render hands a component the element's props resolved but+ * unchecked: defineRegistry passes `element.props` straight through,+ * whatever the catalog's schema says. `guarded` reads them with the+ * component's schema first. Schemas here are forgiving (a `.catch` per+ * prop), so a model's odd value degrades that one prop; with a stricter+ * schema each prop is still read on its own, and only a prop with no+ * usable value at all (not even its default) drops the element. It can+ * also hold a component to the parents it may appear under, and gives each+ * element one entrance the first time it appears, but only when it appears+ * live (inside `LiveUiContext` set to true), so a UI shown again from+ * history does not animate.+ *+ * Error isolation needs nothing here: json-render renders every element+ * inside its own error boundary, so one that throws renders nothing and the+ * rest of the UI stays.+ *+ * No json-render import at run time (types only), so this module costs+ * Home's first chunk nothing.+ */++import { createContext, useCallback, useContext, useMemo, useRef, type ComponentType, type ReactNode } from 'react';+import { z } from 'zod';+import type { BaseComponentProps } from '@json-render/react';+import { animate } from '@/lib/motion';++/** True where a generated UI is arriving now (it animates in); false or+ * absent for one shown again (history). */+export const LiveUiContext = createContext(false);++/** The type of the element a component renders inside; null at the root. */+const ParentTypeContext = createContext<string | null>(null);++/** What a guarded component receives: json-render's arguments with the+ * props read through the schema, minus slots (sanitize.ts strips them),+ * plus the ref that plays its entrance. */+export type GuardedComponentProps<P> = Omit<BaseComponentProps<P>, 'slots'> & {+ /** Attach to the element's outermost node. */+ enterRef: (node: HTMLElement | null) => void;+};++export interface GuardOptions {+ /** The parent types this component may appear under (null: the root).+ * Anywhere else it renders nothing. Default: anywhere. */+ parents?: readonly (string | null)[];+}++interface GuardConfig {+ type: string;+ schema: z.ZodType;+ Component: ComponentType<GuardedComponentProps<any>>;+ parents?: readonly (string | null)[];+}++const ENTER_KEYFRAMES: Keyframe[] = [+ { opacity: 0, transform: 'translateY(8px) scale(.985)', filter: 'blur(3px)' },+ { opacity: 1, transform: 'none', filter: 'blur(0)' },+];++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++/** Props read through `schema`: all at once when they pass, otherwise one+ * prop at a time, each falling back to its default; null when a prop has+ * neither a usable value nor a default. */+export function parseProps<S extends z.ZodType>(schema: S, raw: unknown): z.output<S> | null {+ const input = isRecord(raw) ? raw : {};+ const whole = schema.safeParse(input);+ if (whole.success) return whole.data;+ if (!(schema instanceof z.ZodObject)) return null;+ const out: Record<string, unknown> = {};+ for (const [key, field] of Object.entries(schema.shape as Record<string, z.ZodType>)) {+ const own = field.safeParse(input[key]);+ const result = own.success ? own : field.safeParse(undefined);+ if (!result.success) return null;+ if (result.data !== undefined) out[key] = result.data;+ }+ return out as z.output<S>;+}++/** A ref that plays the generated-UI entrance on the node it first gets,+ * once, when the UI is live. */+export function useEntrance<T extends Element = HTMLElement>(): (node: T | null) => void {+ const live = useContext(LiveUiContext);+ const entered = useRef(false);+ return useCallback(+ (node: T | null) => {+ if (!node || entered.current) return;+ entered.current = true;+ if (live) animate(node, ENTER_KEYFRAMES, { duration: 'genui-enter', easing: 'spring' });+ },+ [live],+ );+}++function Guard({ config, ctx }: { config: GuardConfig; ctx: BaseComponentProps<unknown> }) {+ const parent = useContext(ParentTypeContext);+ const enterRef = useEntrance<HTMLElement>();+ const props = useMemo(() => parseProps(config.schema, ctx.props), [config.schema, ctx.props]);+ if (props === null) return null;+ if (config.parents && !config.parents.includes(parent)) return null;+ const { Component } = config;+ return (+ <ParentTypeContext.Provider value={config.type}>+ <Component+ props={props}+ emit={ctx.emit}+ on={ctx.on}+ bindings={ctx.bindings}+ loading={ctx.loading}+ enterRef={enterRef}+ >+ {ctx.children}+ </Component>+ </ParentTypeContext.Provider>+ );+}++/**+ * A json-render component function for defineRegistry: `Component` drawn+ * with its props read through `schema`.+ */+export function guarded<S extends z.ZodType>(+ type: string,+ schema: S,+ Component: ComponentType<GuardedComponentProps<z.output<S>>>,+ options: GuardOptions = {},+): (ctx: BaseComponentProps<unknown>) => ReactNode {+ const config: GuardConfig = { type, schema, Component, parents: options.parents };+ // defineRegistry calls this as a plain function inside its own component,+ // so it renders the guard rather than running hooks itself.+ return (ctx) => <Guard config={config} ctx={ctx} />;+}diff --git a/client/src/lib/jsonRender/index.ts b/client/src/lib/jsonRender/index.tsnew file mode 100644index 00000000..e18cfdff--- /dev/null+++ b/client/src/lib/jsonRender/index.ts@@ -0,0 +1,53 @@+/**+ * The glue between json-render (@json-render/core, @json-render/react) and+ * the app, shared by every generated UI: Home's hire setup screen+ * (features/home/genui) and the chat's generated replies.+ *+ * - paths.ts: the state-path rule (no prototype keys) and safe reads/writes+ * - sanitize.ts: specs and streamed patches made safe for json-render+ * - guard.tsx: props read through the component's schema, parent rules,+ * the one-time live entrance+ * - reveal.ts: the patch stream for a spec, and its paced reveal+ * - uiState.ts: a StateStore that refuses forbidden paths and reports changes+ * - SpecInspector.tsx: the development view of a spec and its patches+ *+ * None of these imports json-render at run time; only a renderer does+ * (registry and Renderer), and that one is loaded lazily, so json-render+ * stays out of the chunks a page loads first. Modules a page loads eagerly+ * import the file they need (paths, sanitize) rather than this index.+ */++export {+ FORBIDDEN_SEGMENTS,+ MAX_PATH_SEGMENTS,+ canonicalStatePath,+ escapePointer,+ isForbiddenSegment,+ joinStatePath,+ parseStatePath,+ readPath,+ unescapePointer,+ writePath,+} from './paths';+export {+ DEFAULT_SANITIZE_LIMITS,+ MAX_PATCH_PATH,+ isUsableId,+ isUsableName,+ sanitizeActionBinding,+ sanitizeChildren,+ sanitizeCondition,+ sanitizeElement,+ sanitizeExpressions,+ sanitizeJson,+ sanitizeOn,+ sanitizePatch,+ sanitizeSpec,+ sanitizeState,+ type SanitizeLimits,+ type SpecPatch,+} from './sanitize';+export { LiveUiContext, guarded, parseProps, useEntrance, type GuardOptions, type GuardedComponentProps } from './guard';+export { REVEAL_STEP_MS, specFromPatches, specToPatches, useSpecReveal, type SpecReveal } from './reveal';+export { createUiStateStore, type UiStateChange } from './uiState';+export { SpecInspector } from './SpecInspector';diff --git a/client/src/lib/jsonRender/paths.ts b/client/src/lib/jsonRender/paths.tsnew file mode 100644index 00000000..87f8068c--- /dev/null+++ b/client/src/lib/jsonRender/paths.ts@@ -0,0 +1,105 @@+/**+ * State paths in a generated UI: JSON Pointers (RFC 6901) such as+ * "/rules/askFirst", the form json-render reads.+ *+ * json-render 0.21 reads a path with plain property access and writes with+ * a setByPath that descends into `__proto__`, so a path written by a model+ * could reach an object's prototype. Every path a spec, a patch or a+ * control uses goes through `parseStatePath` first. It refuses+ * `__proto__`, `constructor` and `prototype` segments (after unescaping+ * `~1` and `~0`), paths with no segments, and paths deeper than+ * MAX_PATH_SEGMENTS; empty segments ("/a//b/") are skipped, as the setup+ * screen always has. `readPath` and `writePath` apply the same rule, read+ * own properties only, and copy along the path on a write, keeping arrays+ * as arrays.+ *+ * Nothing here imports json-render at run time, so modules Home loads+ * eagerly can use it without pulling the renderer into Home's first chunk.+ */++export const FORBIDDEN_SEGMENTS: ReadonlySet<string> = new Set(['__proto__', 'constructor', 'prototype']);++/** The deepest state path a generated UI may use. */+export const MAX_PATH_SEGMENTS = 6;++export function isForbiddenSegment(segment: string): boolean {+ return FORBIDDEN_SEGMENTS.has(segment);+}++export function unescapePointer(token: string): string {+ return token.replace(/~1/g, '/').replace(/~0/g, '~');+}++export function escapePointer(token: string): string {+ return token.replace(/~/g, '~0').replace(/\//g, '~1');+}++/** The segments of a usable state path, unescaped; null when it is not one.+ * The leading "/" is optional, as it is for json-render. */+export function parseStatePath(path: unknown, maxSegments: number = MAX_PATH_SEGMENTS): string[] | null {+ if (typeof path !== 'string') return null;+ const segments = path+ .split('/')+ .filter(Boolean)+ .map(unescapePointer);+ if (segments.length === 0 || segments.length > maxSegments || segments.some(isForbiddenSegment)) return null;+ return segments;+}++/** A usable state path in its one canonical form ("/a/b"), or null. */+export function canonicalStatePath(path: unknown, maxSegments: number = MAX_PATH_SEGMENTS): string | null {+ const segments = parseStatePath(path, maxSegments);+ return segments ? joinStatePath(segments) : null;+}++export function joinStatePath(segments: readonly string[]): string {+ return `/${segments.map(escapePointer).join('/')}`;+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function childOf(value: unknown, key: string): unknown {+ if (Array.isArray(value)) {+ const index = Number(key);+ return Number.isInteger(index) && index >= 0 ? value[index] : undefined;+ }+ if (isRecord(value) && Object.prototype.hasOwnProperty.call(value, key)) return value[key];+ return undefined;+}++/** The value at a path (own properties only); undefined when the path is+ * unusable or leads nowhere. */+export function readPath(state: unknown, path: unknown): unknown {+ const segments = parseStatePath(path);+ if (!segments) return undefined;+ return segments.reduce<unknown>((value, key) => childOf(value, key), state);+}++/** A copy of `state` with `value` at `path`; `state` itself is unchanged.+ * An unusable path, or an array index past the end, returns `state` as it+ * was. */+export function writePath<T extends Record<string, unknown>>(state: T, path: unknown, value: unknown): T {+ const segments = parseStatePath(path);+ if (!segments) return state;+ let refused = false;+ const write = (node: unknown, index: number): unknown => {+ const key = segments[index];+ const last = index === segments.length - 1;+ if (Array.isArray(node)) {+ const at = Number(key);+ if (!Number.isInteger(at) || at < 0 || at > node.length) {+ refused = true;+ return node;+ }+ const copy = node.slice();+ copy[at] = last ? value : write(node[at], index + 1);+ return copy;+ }+ const base = isRecord(node) ? node : {};+ return { ...base, [key]: last ? value : write(childOf(base, key), index + 1) };+ };+ const next = write(state, 0) as T;+ return refused ? state : next;+}diff --git a/client/src/lib/jsonRender/reveal.ts b/client/src/lib/jsonRender/reveal.tsnew file mode 100644index 00000000..06693373--- /dev/null+++ b/client/src/lib/jsonRender/reveal.ts@@ -0,0 +1,105 @@+/**+ * A generated UI arrives as JSON patches (docs-internal/chat_protocol.md,+ * "Generated UI"): `add /root`, `add /state`, then one `add+ * /elements/<id>` per element, depth first from the root, ids escaped as+ * RFC 6901 says. `specToPatches` writes that stream for a whole spec; the+ * chat fixtures (features/chat/__fixtures__) hold it line for line.+ *+ * `useSpecReveal` replays the stream on screen for a spec that arrived+ * whole: the root and state at once, then one element every REVEAL_STEP_MS+ * (design handoff), so a screen reads as being written rather than dropped+ * in. Everything shows at once under reduced motion or while the page is+ * hidden (motionSuppressed). A new version starts again from nothing.+ */++import { useEffect, useMemo, useState } from 'react';+import type { Spec, UIElement } from '@json-render/core';+import { motionSuppressed } from '@/lib/motion';+import { escapePointer, unescapePointer } from './paths';+import type { SpecPatch } from './sanitize';++export const REVEAL_STEP_MS = 90;++/** `add /root` and `add /state`, ahead of the elements. */+const HEAD = 2;+const ELEMENTS_PREFIX = '/elements/';++function ownElement(spec: Spec, id: string): UIElement | undefined {+ return Object.prototype.hasOwnProperty.call(spec.elements, id) ? spec.elements[id] : undefined;+}++/** The patch stream that builds `spec`: root, state, then every element+ * reachable from the root, depth first, each once. */+export function specToPatches(spec: Spec): SpecPatch[] {+ const patches: SpecPatch[] = [+ { op: 'add', path: '/root', value: spec.root },+ { op: 'add', path: '/state', value: spec.state ?? {} },+ ];+ const seen = new Set<string>();+ const walk = (id: string) => {+ const element = ownElement(spec, id);+ if (!element || seen.has(id)) return;+ seen.add(id);+ patches.push({ op: 'add', path: `${ELEMENTS_PREFIX}${escapePointer(id)}`, value: element });+ element.children?.forEach(walk);+ };+ walk(spec.root);+ return patches;+}++/** The spec the first `count` patches of such a stream build. Only the+ * three kinds specToPatches writes are applied. */+export function specFromPatches(patches: readonly SpecPatch[], count: number = patches.length): Spec {+ let root = '';+ let state: Record<string, unknown> = {};+ // No prototype: ids are looked up here as keys.+ const elements: Record<string, UIElement> = Object.create(null);+ for (const patch of patches.slice(0, count)) {+ if (patch.op !== 'add') continue;+ if (patch.path === '/root' && typeof patch.value === 'string') root = patch.value;+ else if (patch.path === '/state' && patch.value && typeof patch.value === 'object') state = patch.value as Record<string, unknown>;+ else if (patch.path.startsWith(ELEMENTS_PREFIX)) {+ const token = patch.path.slice(ELEMENTS_PREFIX.length);+ if (token && !token.includes('/') && patch.value && typeof patch.value === 'object') {+ elements[unescapePointer(token)] = patch.value as UIElement;+ }+ }+ }+ return { root, state, elements };+}++export interface SpecReveal {+ /** The part of the spec shown so far (null while there is no spec). */+ spec: Spec | null;+ /** Elements are still arriving: render with `loading` so json-render does+ * not warn about children that are on their way. */+ revealing: boolean;+}++export function useSpecReveal(spec: Spec | null, version: number): SpecReveal {+ const patches = useMemo(() => (spec ? specToPatches(spec) : []), [spec]);+ const total = Math.max(0, patches.length - HEAD);+ const [progress, setProgress] = useState({ version, count: 0 });+ const count = progress.version === version ? progress.count : 0;++ useEffect(() => {+ if (total === 0) return;+ if (motionSuppressed()) {+ setProgress({ version, count: total });+ return;+ }+ const started = performance.now();+ setProgress({ version, count: 1 });+ const timer = window.setInterval(() => {+ const next = motionSuppressed()+ ? total+ : Math.min(total, Math.floor((performance.now() - started) / REVEAL_STEP_MS) + 1);+ setProgress({ version, count: next });+ if (next >= total) window.clearInterval(timer);+ }, REVEAL_STEP_MS);+ return () => window.clearInterval(timer);+ }, [version, total]);++ const shown = useMemo(() => (spec ? specFromPatches(patches, HEAD + count) : null), [spec, patches, count]);+ return { spec: shown, revealing: count < total };+}diff --git a/client/src/lib/jsonRender/sanitize.ts b/client/src/lib/jsonRender/sanitize.tsnew file mode 100644index 00000000..58a8babe--- /dev/null+++ b/client/src/lib/jsonRender/sanitize.ts@@ -0,0 +1,362 @@+/**+ * Making a generated UI safe to hand to json-render.+ *+ * json-render 0.21 does not guard state paths (its setByPath descends into+ * `__proto__`), does not check props against the catalog, and runs element+ * features a model should never reach: `watch` (actions fired by state+ * changes), `repeat`, `slots`, `$computed`, and an action binding's+ * `confirm`, `onSuccess` and `onError` (the last two set state or run+ * further actions). So before a spec or a patch reaches the renderer:+ *+ * - an element keeps its `type`, `props`, `children`, `visible` and `on`+ * only, and an action binding its `action` and `params` only;+ * - `__proto__`, `constructor` and `prototype` are refused everywhere: as+ * ids, object keys, and segments of `$state` / `$bindState` paths,+ * `$template` placeholders, `visible` conditions, action params and+ * patch paths (paths.ts holds the rule); every path that survives is+ * rewritten in one canonical form;+ * - `$computed` is dropped, and so are `$item`, `$index` and `$bindItem`,+ * which mean nothing once `repeat` is gone;+ * - sizes are capped: elements, children, nesting depth, keys, array and+ * string lengths.+ *+ * What an expression that is refused becomes: a prop or param is dropped+ * (as if never written); a condition reads as false (the element hides).+ * Conditions written as an array become `{"$and": [...]}`, which+ * json-render evaluates the same way but also accepts plain booleans in.+ *+ * Props are not checked against the catalog here: the renderer's guard+ * reads each one with the component's own schema (guard.tsx). Unknown+ * component types are the caller's to drop, as is building the tree.+ */++import type { ActionBinding, Spec, UIElement, VisibilityCondition } from '@json-render/core';+import { MAX_PATH_SEGMENTS, canonicalStatePath, isForbiddenSegment, joinStatePath, unescapePointer } from './paths';++export interface SanitizeLimits {+ /** Elements kept from a spec, in the order written. */+ maxElements: number;+ /** Child ids kept per element. */+ maxChildren: number;+ maxIdLength: number;+ /** How deep a value nests before the rest is dropped. */+ maxDepth: number;+ /** Items kept per array, keys per object. */+ maxArray: number;+ maxKeys: number;+ /** Characters kept per string. */+ maxString: number;+ maxPathSegments: number;+}++export const DEFAULT_SANITIZE_LIMITS: SanitizeLimits = {+ maxElements: 64,+ maxChildren: 64,+ maxIdLength: 40,+ maxDepth: 8,+ maxArray: 50,+ maxKeys: 40,+ maxString: 4000,+ maxPathSegments: MAX_PATH_SEGMENTS,+};++/** A spec patch json-render can apply: add or replace a value, or remove one. */+export interface SpecPatch {+ op: 'add' | 'replace' | 'remove';+ path: string;+ value?: unknown;+}++/** Longest patch path accepted. */+export const MAX_PATCH_PATH = 512;++const ID_PATTERN = /^[A-Za-z0-9_.:-]+$/;+const NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;+const NAME_MAX = 64;+/** Expressions that only work inside `repeat` or call app code. */+const DROPPED_EXPRESSIONS = ['$computed', '$item', '$index', '$bindItem'] as const;+const COMPARISONS = ['eq', 'neq'] as const;+const ORDERINGS = ['gt', 'gte', 'lt', 'lte'] as const;+/** Bindings kept per event. */+const MAX_BINDINGS = 4;+/** Element fields a patch may write below an element. */+const PATCHABLE_FIELDS = new Set(['props', 'children', 'visible', 'on']);++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++/** An element id the renderer can key on: short, plain characters, never a prototype key. */+export function isUsableId(id: unknown, limits: SanitizeLimits = DEFAULT_SANITIZE_LIMITS): id is string {+ return typeof id === 'string' && id.length <= limits.maxIdLength && ID_PATTERN.test(id) && !isForbiddenSegment(id);+}++/** A component type, action or event name: an identifier, never a prototype key. */+export function isUsableName(name: unknown): name is string {+ return typeof name === 'string' && name.length <= NAME_MAX && NAME_PATTERN.test(name) && !isForbiddenSegment(name);+}++function clip(text: string, limits: SanitizeLimits): string {+ return text.length > limits.maxString ? text.slice(0, limits.maxString) : text;+}++/** Plain JSON data (initial state, a state write): prototype keys dropped,+ * sizes capped, non-JSON values (NaN, functions) dropped. */+export function sanitizeJson(value: unknown, limits: SanitizeLimits = DEFAULT_SANITIZE_LIMITS, depth = 0): unknown {+ if (depth > limits.maxDepth) return undefined;+ if (value === null || typeof value === 'boolean') return value;+ if (typeof value === 'number') return Number.isFinite(value) ? value : undefined;+ if (typeof value === 'string') return clip(value, limits);+ if (Array.isArray(value)) {+ const out: unknown[] = [];+ for (const item of value.slice(0, limits.maxArray)) {+ const clean = sanitizeJson(item, limits, depth + 1);+ if (clean !== undefined) out.push(clean);+ }+ return out;+ }+ if (!isRecord(value)) return undefined;+ const out: Record<string, unknown> = {};+ for (const key of Object.keys(value).slice(0, limits.maxKeys)) {+ if (isForbiddenSegment(key)) continue;+ const clean = sanitizeJson(value[key], limits, depth + 1);+ if (clean !== undefined) out[key] = clean;+ }+ return out;+}++/** A spec's initial state: always an object. */+export function sanitizeState(raw: unknown, limits: SanitizeLimits = DEFAULT_SANITIZE_LIMITS): Record<string, unknown> {+ const clean = sanitizeJson(raw, limits);+ return isRecord(clean) ? clean : {};+}++function pathExpression(key: '$state' | '$bindState', path: unknown, limits: SanitizeLimits) {+ const canonical = canonicalStatePath(path, limits.maxPathSegments);+ return canonical ? { [key]: canonical } : undefined;+}++/** `${path}` placeholders rewritten canonically; one that reads a refused+ * path becomes empty text, as an unset value would. */+function sanitizeTemplate(template: string, limits: SanitizeLimits): string {+ return clip(template, limits).replace(/\$\{([^}]+)\}/g, (_match, raw: string) => {+ const path = canonicalStatePath(raw.trim(), limits.maxPathSegments);+ return path ? `\${${path}}` : '';+ });+}++/** A value that may hold json-render expressions (props, action params). */+export function sanitizeExpressions(value: unknown, limits: SanitizeLimits = DEFAULT_SANITIZE_LIMITS, depth = 0): unknown {+ if (depth > limits.maxDepth) return undefined;+ if (Array.isArray(value)) {+ const out: unknown[] = [];+ for (const item of value.slice(0, limits.maxArray)) {+ const clean = sanitizeExpressions(item, limits, depth + 1);+ if (clean !== undefined) out.push(clean);+ }+ return out;+ }+ if (!isRecord(value)) return sanitizeJson(value, limits, depth);+ if ('$state' in value) return pathExpression('$state', value.$state, limits);+ if ('$bindState' in value) return pathExpression('$bindState', value.$bindState, limits);+ if (DROPPED_EXPRESSIONS.some((key) => key in value)) return undefined;+ if ('$cond' in value) {+ const branch = (raw: unknown) => sanitizeExpressions(raw, limits, depth + 1) ?? null;+ return {+ $cond: sanitizeCondition(value.$cond, limits, depth + 1) ?? true,+ $then: branch(value.$then),+ $else: branch(value.$else),+ };+ }+ if ('$template' in value) {+ return typeof value.$template === 'string' ? { $template: sanitizeTemplate(value.$template, limits) } : undefined;+ }+ const out: Record<string, unknown> = {};+ for (const key of Object.keys(value).slice(0, limits.maxKeys)) {+ if (isForbiddenSegment(key)) continue;+ const clean = sanitizeExpressions(value[key], limits, depth + 1);+ if (clean !== undefined) out[key] = clean;+ }+ return out;+}++function comparisonValue(value: unknown, limits: SanitizeLimits, depth: number): unknown {+ if (isRecord(value) && '$state' in value) return pathExpression('$state', value.$state, limits) ?? null;+ return sanitizeJson(value, limits, depth + 1) ?? null;+}++/**+ * A `visible` condition (or a `$cond`). undefined means "no condition"+ * (always shown). One that reads a refused path, or that only works inside+ * `repeat` ($item, $index), or that has no recognisable shape, reads as+ * false.+ */+export function sanitizeCondition(+ condition: unknown,+ limits: SanitizeLimits = DEFAULT_SANITIZE_LIMITS,+ depth = 0,+): VisibilityCondition | undefined {+ if (condition === undefined || condition === null) return undefined;+ if (typeof condition === 'boolean') return condition;+ if (depth > limits.maxDepth) return false;+ const all = (items: unknown[]) =>+ items.slice(0, limits.maxArray).map((item) => sanitizeCondition(item, limits, depth + 1) ?? true);+ if (Array.isArray(condition)) return { $and: all(condition) };+ if (!isRecord(condition)) return Boolean(condition);+ if ('$and' in condition) return Array.isArray(condition.$and) ? { $and: all(condition.$and) } : false;+ if ('$or' in condition) return Array.isArray(condition.$or) ? { $or: all(condition.$or) } : false;+ if (!('$state' in condition)) return false;+ const path = canonicalStatePath(condition.$state, limits.maxPathSegments);+ if (!path) return false;+ const out: Record<string, unknown> = { $state: path };+ for (const op of COMPARISONS) {+ if (condition[op] !== undefined) out[op] = comparisonValue(condition[op], limits, depth);+ }+ for (const op of ORDERINGS) {+ const value = condition[op];+ if (typeof value === 'number' && Number.isFinite(value)) out[op] = value;+ else if (isRecord(value) && '$state' in value) {+ const bound = pathExpression('$state', value.$state, limits);+ if (bound) out[op] = bound;+ }+ }+ if (condition.not) out.not = true;+ return out as VisibilityCondition;+}++/** An action binding: a usable action name and its params, nothing else. */+export function sanitizeActionBinding(raw: unknown, limits: SanitizeLimits = DEFAULT_SANITIZE_LIMITS): ActionBinding | null {+ if (!isRecord(raw) || !isUsableName(raw.action)) return null;+ const binding: ActionBinding = { action: raw.action };+ if (raw.params !== undefined) {+ const params = sanitizeExpressions(raw.params, limits, 1);+ if (isRecord(params) && Object.keys(params).length > 0) binding.params = params;+ }+ return binding;+}++function sanitizeBindings(raw: unknown, limits: SanitizeLimits): ActionBinding | ActionBinding[] | undefined {+ if (!Array.isArray(raw)) return sanitizeActionBinding(raw, limits) ?? undefined;+ const list = raw+ .slice(0, MAX_BINDINGS)+ .map((binding) => sanitizeActionBinding(binding, limits))+ .filter((binding): binding is ActionBinding => binding !== null);+ return list.length > 0 ? list : undefined;+}++/** An element's `on`: event name -> binding(s). */+export function sanitizeOn(+ raw: unknown,+ limits: SanitizeLimits = DEFAULT_SANITIZE_LIMITS,+): Record<string, ActionBinding | ActionBinding[]> | undefined {+ if (!isRecord(raw)) return undefined;+ const out: Record<string, ActionBinding | ActionBinding[]> = {};+ for (const event of Object.keys(raw).slice(0, limits.maxKeys)) {+ if (!isUsableName(event)) continue;+ const bindings = sanitizeBindings(raw[event], limits);+ if (bindings) out[event] = bindings;+ }+ return Object.keys(out).length > 0 ? out : undefined;+}++/** Child ids: usable, each once, capped. */+export function sanitizeChildren(raw: unknown, limits: SanitizeLimits = DEFAULT_SANITIZE_LIMITS): string[] {+ if (!Array.isArray(raw)) return [];+ const out: string[] = [];+ for (const child of raw) {+ if (out.length >= limits.maxChildren) break;+ if (isUsableId(child, limits) && !out.includes(child)) out.push(child);+ }+ return out;+}++/** One element: type, props, children, visible and on; null when its type+ * is not a usable name. */+export function sanitizeElement(raw: unknown, limits: SanitizeLimits = DEFAULT_SANITIZE_LIMITS): UIElement | null {+ if (!isRecord(raw) || !isUsableName(raw.type)) return null;+ const props = isRecord(raw.props) ? sanitizeExpressions(raw.props, limits) : {};+ const element: UIElement = { type: raw.type, props: isRecord(props) ? props : {} };+ if (raw.children !== undefined) element.children = sanitizeChildren(raw.children, limits);+ const visible = sanitizeCondition(raw.visible, limits);+ if (visible !== undefined) element.visible = visible;+ const on = sanitizeOn(raw.on, limits);+ if (on) element.on = on;+ return element;+}++/** A whole flat spec `{root, state, elements}`; null when it has no usable+ * root id or no elements object. Elements keep the order written. */+export function sanitizeSpec(raw: unknown, limits: SanitizeLimits = DEFAULT_SANITIZE_LIMITS): Spec | null {+ if (!isRecord(raw) || !isRecord(raw.elements) || !isUsableId(raw.root, limits)) return null;+ // No prototype: ids are looked up here as keys.+ const elements: Record<string, UIElement> = Object.create(null);+ let count = 0;+ for (const id of Object.keys(raw.elements)) {+ if (count >= limits.maxElements) break;+ if (!isUsableId(id, limits)) continue;+ const element = sanitizeElement(raw.elements[id], limits);+ if (!element) continue;+ elements[id] = element;+ count++;+ }+ return { root: raw.root, state: sanitizeState(raw.state, limits), elements };+}++/** The value an add or replace may write at `segments` (already checked by+ * patchSegments); undefined when there is nothing usable to write. */+function patchValue(segments: readonly string[], value: unknown, limits: SanitizeLimits): unknown {+ // ['root'] | ['state', ...path] | ['elements', id] | ['elements', id, field, ...rest]+ const [area, , field, ...rest] = segments;+ if (area === 'root') return isUsableId(value, limits) ? value : undefined;+ if (area === 'state') return segments.length === 1 ? sanitizeState(value, limits) : sanitizeJson(value, limits, 1);+ if (field === undefined) return sanitizeElement(value, limits) ?? undefined;+ if (field === 'props') {+ if (rest.length > 0) return sanitizeExpressions(value, limits, rest.length);+ const props = sanitizeExpressions(value, limits);+ return isRecord(props) ? props : undefined;+ }+ if (field === 'children') {+ if (rest.length > 0) return isUsableId(value, limits) ? value : undefined;+ return Array.isArray(value) ? sanitizeChildren(value, limits) : undefined;+ }+ if (field === 'visible') return sanitizeCondition(value, limits);+ return rest.length > 0 ? sanitizeBindings(value, limits) : sanitizeOn(value, limits);+}++/** Where a patch may write: `/root`, `/state` and below, `/elements/<id>`,+ * and an element's props, children, visible or on. */+function patchSegments(path: string, limits: SanitizeLimits): string[] | null {+ if (path.length > MAX_PATCH_PATH || !path.startsWith('/')) return null;+ const segments = path.slice(1).split('/').map(unescapePointer);+ if (segments.some((segment) => segment === '' || isForbiddenSegment(segment))) return null;+ const [area, id, field, ...rest] = segments;+ if (area === 'root') return segments.length === 1 ? segments : null;+ if (area === 'state') return segments.length - 1 <= limits.maxPathSegments ? segments : null;+ if (area !== 'elements' || !isUsableId(id, limits)) return null;+ if (field === undefined) return segments;+ if (!PATCHABLE_FIELDS.has(field)) return null;+ if (field === 'visible' && rest.length > 0) return null;+ if ((field === 'children' || field === 'on') && rest.length > 1) return null;+ if (field === 'children' && rest.length === 1 && !/^(\d+|-)$/.test(rest[0])) return null;+ if (field === 'on' && rest.length === 1 && !isUsableName(rest[0])) return null;+ if (field === 'props' && rest.length > limits.maxDepth) return null;+ return segments;+}++/**+ * One patch of a streamed spec, or null when it is refused: only `add`,+ * `replace` and `remove`, only at the paths above, and with a value+ * sanitized for where it lands (a whole element as sanitizeElement does,+ * state as plain JSON, props as expressions). `/root` cannot be removed.+ */+export function sanitizePatch(raw: unknown, limits: SanitizeLimits = DEFAULT_SANITIZE_LIMITS): SpecPatch | null {+ if (!isRecord(raw) || typeof raw.path !== 'string') return null;+ const op = raw.op;+ if (op !== 'add' && op !== 'replace' && op !== 'remove') return null;+ const segments = patchSegments(raw.path, limits);+ if (!segments) return null;+ const path = joinStatePath(segments);+ if (op === 'remove') return segments[0] === 'root' ? null : { op, path };+ const value = patchValue(segments, raw.value, limits);+ return value === undefined ? null : { op, path, value };+}diff --git a/client/src/lib/jsonRender/uiState.ts b/client/src/lib/jsonRender/uiState.tsnew file mode 100644index 00000000..628dca1c--- /dev/null+++ b/client/src/lib/jsonRender/uiState.ts@@ -0,0 +1,73 @@+/**+ * The state one generated UI reads and writes: a json-render StateStore+ * (pass it to JSONUIProvider as `store`) with the forbidden-path guard on+ * every write.+ *+ * json-render's own createStateStore writes through any path, `__proto__`+ * included. This one refuses whatever paths.ts refuses, copies along the+ * path on a write (snapshots stay immutable, as useSyncExternalStore+ * needs), keeps arrays as arrays, and reports every change to `onChange`+ * with its path in canonical form. json-render's StateProvider reports+ * nothing for a store it is handed, so this is where a host learns what the+ * owner changed (a draft to keep, a chat message's state to send).+ *+ * Create one per spec, and a new one for a new version of it.+ */++import type { StateModel, StateStore } from '@json-render/core';+import { joinStatePath, parseStatePath, readPath, writePath } from './paths';++export interface UiStateChange {+ path: string;+ value: unknown;+}++export function createUiStateStore(+ initialState: StateModel = {},+ onChange?: (changes: UiStateChange[]) => void,+): StateStore {+ let state: StateModel = { ...initialState };+ const listeners = new Set<() => void>();++ /** The state with one more write applied, and the change it made (none+ * when the path is refused or the value is already there). */+ const apply = (from: StateModel, path: string, value: unknown): [StateModel, UiStateChange | null] => {+ const segments = parseStatePath(path);+ if (!segments || readPath(from, path) === value) return [from, null];+ const next = writePath(from, path, value);+ return next === from ? [from, null] : [next, { path: joinStatePath(segments), value }];+ };++ const commit = (next: StateModel, changes: UiStateChange[]) => {+ if (changes.length === 0) return;+ state = next;+ for (const listener of listeners) listener();+ onChange?.(changes);+ };++ return {+ get: (path) => readPath(state, path),+ set(path, value) {+ const [next, change] = apply(state, path, value);+ commit(next, change ? [change] : []);+ },+ update(updates) {+ let next = state;+ const changes: UiStateChange[] = [];+ for (const [path, value] of Object.entries(updates)) {+ const [written, change] = apply(next, path, value);+ next = written;+ if (change) changes.push(change);+ }+ commit(next, changes);+ },+ getSnapshot: () => state,+ getServerSnapshot: () => state,+ subscribe(listener) {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+ },+ };+}diff --git a/client/vite.config.js b/client/vite.config.jsindex ea865780..d0070117 100644--- a/client/vite.config.js+++ b/client/vite.config.js@@ -181,14 +181,21 @@ export default defineConfig(({ mode }) => {// vendor-query — TanStack Query + persistence// vendor-markdown — markdown rendering stack (chat / docs panels)// vendor-three — WebGL for Normal mode's orb, loaded on demand+ // vendor-genui — json-render, for generated UIs (the hire+ // setup screen), loaded with the first one// vendor-misc — small but heavyweight utilities// Anything not listed falls into the default route/entry chunks.+ // A listed module's unlisted dependencies join its chunk, so zod+ // (json-render's one dependency, used eagerly by forms and+ // stores) is listed with the form runtime: left out, it would+ // move into vendor-genui and drag that chunk into the first load.manualChunks: {'vendor-react': ['react','react-dom','react-hook-form','@hookform/resolvers',+ 'zod',],'vendor-flow': ['reactflow'],'vendor-radix': ['radix-ui'],@@ -208,6 +215,7 @@ export default defineConfig(({ mode }) => {'@uiw/react-json-view',],'vendor-three': ['three'],+ 'vendor-genui': ['@json-render/core', '@json-render/react'],'vendor-misc': ['idb-keyval','fuzzysort',diff --git a/docs-internal/chat_protocol.md b/docs-internal/chat_protocol.mdindex e9b1fcd6..cd68a792 100644--- a/docs-internal/chat_protocol.md+++ b/docs-internal/chat_protocol.md@@ -213,10 +213,14 @@ Approvals are joined live from the approvals store; the part only names them.whose turn carries `[ui-event]{…}[/ui-event]`.- **Sanitising.** json-render 0.21 does not guard state paths (`setByPath` descends into `__proto__`), does notvalidate props against the catalog, and supports `watch` (actions fired by state changes), `repeat`, `$computed`- and `confirm`. Both sides therefore:+ and an action binding's `confirm`, `onSuccess` and `onError` (the last two set state or run further actions).+ Both sides therefore (the client in `client/src/lib/jsonRender/`):- refuse `__proto__`, `constructor` and `prototype` path segments everywhere (`$state`, `$bindState`, `$template`,- `visible`, action params, patch paths);- - strip `watch`, `repeat`, `slots`, `$computed` and `confirm`;+ `visible`, action params, patch paths); an expression that reads such a path is dropped, and a `visible`+ condition that reads one is false;+ - keep only an element's `type`, `props`, `children`, `visible` and `on`, and only an action binding's `action`+ and `params`: `watch`, `repeat`, `slots`, `confirm`, `onSuccess`, `onError` and `preventDefault` go;+ - drop `$computed`, and `$item`, `$index` and `$bindItem`, which mean nothing without `repeat`;- validate every element's props (the client degrades one bad prop at a time with forgiving zod schemas);- drop unknown component types before rendering.diff --git a/docs-internal/frontend_architecture.md b/docs-internal/frontend_architecture.mdindex c6889330..bd66d81a 100644--- a/docs-internal/frontend_architecture.md+++ b/docs-internal/frontend_architecture.md@@ -210,6 +210,10 @@ client/src/│ │ # 1 ms under reduced motion or a hidden page, no loops then│ ├── pageActivity.ts / useReducedMotion.ts # Whether anyone can see the page; the motion preference│ ├── debouncedInvalidate.ts # Trailing-edge query invalidation (broadcast bursts)+│ ├── jsonRender/ # Generated-UI glue around json-render (hire setup screen, chat replies):+│ │ # sanitize (no prototype paths; no watch/repeat/slots/$computed/confirm),+│ │ # guard (props through the catalogue schema, live-only entrance),+│ │ # reveal (spec -> patch stream, paced), uiState (guarded store)│ └── utils.ts # cn() = clsx + tailwind-merge (shadcn convention)├── schemas/workflowSchema.ts # Structural pre-flight for workflow export (backend is the schema authority)├── stores/diff --git a/docs-internal/normal_mode.md b/docs-internal/normal_mode.mdindex e7682422..8d098561 100644--- a/docs-internal/normal_mode.md+++ b/docs-internal/normal_mode.md@@ -239,22 +239,33 @@ still holds that job as written, the chip shows as picked with the starter'ssummary and **Hire now** (see [One-click starters](#one-click-starters)).While the model writes, the draft panel shows one honest line, "Writing theirsetup…", with the time so far and Cancel, and after `SLOW_AFTER_SECONDS` a-note that some models take a few minutes. The screen's layout JSON is shown-in development builds only.--The reply is a flat JSON UI spec. The client parses, repairs and normalises it-and renders it from a fixed component catalogue-([genui/](../client/src/features/home/genui/): `catalog.ts`, `parse.ts`,-`normalize.ts`, `expressions.ts`, `render.tsx`). The normaliser keeps the-root a vertical stack, enforces a tree, guarantees one Hire button, one-change button, the "Ask me before sending anything" toggle (on by default)-and one `Schedule` (below), and caps sizes. The server mirrors the catalogue in+note that some models take a few minutes. Development builds also show the+screen's spec and its patch stream (`spec.json` / `patches.jsonl`).++The reply is a flat JSON UI spec in json-render's shape (catalogue+`spec_version` 2): a Toggle binds `checked`, and a Button names its action in+the element's `on.press` (`{action, params}`). The client parses, repairs and+normalises it ([genui/](../client/src/features/home/genui/): `catalog.ts`,+`parse.ts`, `normalize.ts`, `expressions.ts`) and json-render draws it from a+fixed component catalogue (`registry.ts`, `views.tsx`, `HireScreen.tsx`,+loaded lazily so json-render stays out of Home's first chunk). The normaliser+still reads the older shape a model may write (a Toggle's `value`, a+Button's `action` / `actionParams` props), keeps the root a vertical stack,+enforces a tree, guarantees one Hire button, one change button, the "Ask me+before sending anything" toggle (on by default) and one `Schedule` (below),+caps sizes, and drops what json-render does not guard: any path through+`__proto__`, `constructor` or `prototype`, and `watch`, `repeat`, `slots`,+`$computed` and an action's `confirm`. That glue is shared with the chat's+generated replies in [lib/jsonRender/](../client/src/lib/jsonRender/)+(sanitising, the per-element guard that reads props through the catalogue's+forgiving schema, the paced reveal, the guarded state store). The server+mirrors the catalogue in[config/genui_catalog.json](../server/config/genui_catalog.json);`server/tests/test_genui_catalog_sync.py` keeps the two in step, and a shared-corpus of bad model replies (`genui/__fixtures__/replies.json`) is parsed the-same way on both sides. Only what `genui/index.ts` exports (`HireDraftPanel`,-`useHireComposer`, `DraftMessagePreview`) leaves the folder: ESLint refuses-imports of its internal modules.+corpus of model replies in both shapes (`genui/__fixtures__/replies.json`) is+parsed the same way on both sides. Only what `genui/index.ts` exports+(`HireDraftPanel`, `useHireComposer`, `useStarterHire`, `DraftMessagePreview`)+leaves the folder: ESLint refuses imports of its internal modules.**When they work.** Every screen shows one `Schedule` after the routine. Thenormaliser inserts it (the catalogue marks it `inserted`, so the model is@@ -267,7 +278,7 @@ a weekday or day of the month. It reads as one sentence ("Every weekday at08:00"). Edit offers the owner messaging them, a schedule,or a new message in any app whose `can_trigger` is true; a change rewrites theroutine's "When" step, and the hire payload reads `/trigger` before the-button's params. `render.tsx` labels the routine "Their routine" and its steps+button's params. `views.tsx` labels the routine "Their routine" and its stepsin plain words (When, They, Using, Then).### 2. Hirediff --git a/server/config/genui_catalog.json b/server/config/genui_catalog.jsonindex e17d5ee6..e6220d5a 100644--- a/server/config/genui_catalog.json+++ b/server/config/genui_catalog.json@@ -1,6 +1,6 @@{- "_comment": "Normal mode's setup-screen vocabulary: what a model may use when it writes a new employee's setup screen. The prompt (services/employees/setup_prompt.py) is generated from this file; the client's renderer (client/src/features/home/genui/catalog.ts, hirePayload.ts) must list the same components, actions, tones, roles, state paths, limits and trigger lists, which tests/test_genui_catalog_sync.py checks. A component marked `inserted` is added by the client's normalizer, never by the model, so the prompt leaves it out. `trigger.times` are the times a schedule can run at (services/employees/builder.py SCHEDULE_TIMES).",- "spec_version": 1,+ "_comment": "Normal mode's setup-screen vocabulary: what a model may use when it writes a new employee's setup screen. The prompt (services/employees/setup_prompt.py) is generated from this file; the client's renderer (client/src/features/home/genui/catalog.ts, hirePayload.ts) must list the same components, actions, tones, roles, state paths, limits and trigger lists, which tests/test_genui_catalog_sync.py checks. A component marked `inserted` is added by the client's normalizer, never by the model, so the prompt leaves it out. `trigger.times` are the times a schedule can run at (services/employees/builder.py SCHEDULE_TIMES). spec_version 2 is json-render's shape: a Toggle binds `checked`, and a Button's action is the element's `on.press` ({action, params}); the client still reads the older `value` and `action`/`actionParams` a model may write.",+ "spec_version": 2,"components": {"Stack": {"props": "{direction:\"vertical\"|\"horizontal\", gap:\"sm\"|\"md\"|\"lg\"}",@@ -56,7 +56,7 @@"description": "Progress or usage bar."},"Toggle": {- "props": "{label, description?, value:{\"$bindState\":\"/rules/<key>\"}}",+ "props": "{label, description?, checked:{\"$bindState\":\"/rules/<key>\"}}","description": "On/off ground rule, bound to state under /rules."},"Choice": {@@ -68,8 +68,8 @@"description": "Short text field, bound to state under /inputs."},"Button": {- "props": "{label, variant:\"primary\"|\"secondary\", action, actionParams?}",- "description": "Runs an action."+ "props": "{label, variant:\"primary\"|\"secondary\"}",+ "description": "Runs an action, named beside its props: \"on\":{\"press\":{\"action\", \"params\"?}}."},"Divider": {"props": "{}",diff --git a/server/services/employees/setup_prompt.py b/server/services/employees/setup_prompt.pyindex 3f9966ba..6414c927 100644--- a/server/services/employees/setup_prompt.py+++ b/server/services/employees/setup_prompt.py@@ -13,7 +13,10 @@ additions:with a schedule's time one of the catalogue's ``trigger.times``) and``sendsVia`` (the app they answer or report through). No kind of triggeris preferred: every employee can be talked to on Home, so one that works- when the owner messages them is as good as any.+ when the owner messages them is as good as any;+- the spec is in json-render's shape (catalogue ``spec_version`` 2): a+ Toggle binds ``checked``, and a Button names its action in the element's+ ``on.press`` (``{"action", "params"}``) beside its props.The component and action lines come from config/genui_catalog.json, whichthe client's renderer is held to; a component the client inserts itself@@ -61,21 +64,25 @@ def catalog_prompt(catalog: Optional[Dict[str, Any]] = None) -> str:'2) Plan titled "Their routine" with 3-5 steps; the first step has role "trigger" (e.g. "When a message ''arrives", "Every weekday at 08:00"). Step titles are short present-tense actions. A step that uses an app ''names it in "app".',- f'3) Card titled "Ground rules" containing 2-3 Toggles bound to state under "{paths["rules"]}" (always '- f'include "{ask_first}" bound to "{paths["askFirst"]}", true in "state") and optionally one Choice bound '- f'under "{paths["choices"]}" (e.g. how often to report).',- '4) If a needed app is not connected: a Card with tone "trigger" saying so, with a Button (connect_app).',- '5) A horizontal Stack with Button "Hire {name}" (primary, action hire_employee, actionParams {name, role, '- 'apps, trigger, sendsVia}) and Button "Change something" (secondary, action refine).',+ f'3) Card titled "Ground rules" containing 2-3 Toggles bound to state under "{paths["rules"]}" through '+ f'"checked" (always include "{ask_first}" bound to "{paths["askFirst"]}", true in "state") and optionally '+ f'one Choice bound under "{paths["choices"]}" (e.g. how often to report).',+ '4) If a needed app is not connected: a Card with tone "trigger" saying so, with a Button whose on.press '+ "runs connect_app.",+ '5) A horizontal Stack with Button "Hire {name}" (primary, on.press {"action": "hire_employee", "params": '+ '{name, role, apps, trigger, sendsVia}}) and Button "Change something" (secondary, on.press {"action": '+ '"refine"}).',f'"trigger" is {{"kind": {kinds}, "app"?, "every"?: {every}, "at"?: {times}, "day"?}}: ''"app_event" when a new message or email in an app starts the work, "schedule" for routine work at set ''times, "manual" when the owner gives them work by messaging them. "at" is the owner\'s local time; "day" ''is a weekday name for "week", or a day of the month from 1 to 28 for "month". "sendsVia" is the app they '"answer or report through.",'UISpec is flat: {"root": id, "state": {initial values}, "elements": {id: {"type", "props", "children": '- '[ids], "visible"?: condition}}}. Max 12 elements. Every child id must exist.',+ '[ids], "visible"?: condition, "on"?: {"press": {"action", "params"?}}}}}. Max 12 elements. Every child id '+ "must exist.",'Each element looks like {"type":"Text","props":{"text":"…"},"children":[]} — all component props go '- 'INSIDE "props".',+ 'INSIDE "props". A Button\'s action goes in "on", beside "props": '+ '{"type":"Button","props":{"label":"…"},"on":{"press":{"action":"refine"}},"children":[]}.','Every Stack and Card MUST list its child ids in "children" — elements not listed as someone\'s child are '"not shown.",'Keep it compact: single-line minified JSON, no code fences, short ids ("a","b","c"…), every string under '@@ -93,7 +100,7 @@ def catalog_prompt(catalog: Optional[Dict[str, Any]] = None) -> str:'{"$cond":{"$state":"/x","eq":"y"},"$then":a,"$else":b}. Conditions: {"$state":"/path"} with optional ''"eq" or "not":true.')- lines.append("Button actions:")+ lines.append('Actions (the "action" of a Button\'s on.press, with these "params"):')lines += [f"- {name} {description}" for name, description in c["actions"].items()]lines.append("When asked to change the setup, return the full updated JSON in the same format.")return "\n".join(lines)diff --git a/server/services/employees/setup_reply.py b/server/services/employees/setup_reply.pyindex f2fc2d4e..99a9ddd2 100644--- a/server/services/employees/setup_reply.py+++ b/server/services/employees/setup_reply.py@@ -14,7 +14,10 @@ The rules, as the client applies them: take the first ``{`` to the lastopen. A reply is renderable when its ``spec`` has an ``elements`` objectwith at least one usable element: a known component with a usable id,where a Button needs a label and a known action and an AgentCard needs a-name.+name. A Button's action is read as the client reads it: the element's+``on.press`` (one binding, or the first of a list with a known action),+else ``on`` written inside its props, else the older ``action`` /+``actionParams`` props."""from __future__ import annotations@@ -22,7 +25,7 @@ from __future__ import annotationsimport jsonimport refrom dataclasses import dataclass-from typing import Any, Dict, Iterable, List, Optional+from typing import Any, Dict, Iterable, List, Optional, Tuplefrom services.employees.genui_catalog import canonical_action, component_types, limit@@ -30,7 +33,8 @@ _FENCE = re.compile(r"```(?:json)?", re.IGNORECASE)_QUOTED_TEXT = re.compile(r'"text"\s*:\s*"((?:[^"\\]|\\.)*)"')_ID = re.compile(r"^[A-Za-z0-9_.:-]+$")_FORBIDDEN_KEYS = frozenset({"__proto__", "constructor", "prototype"})-_META_KEYS = frozenset({"type", "props", "children", "visible", "watch", "id"})+# Element keys that are never props; the client's normalize.ts META_KEYS.+_META_KEYS = frozenset({"type", "props", "children", "visible", "watch", "id", "on", "repeat", "slots"})_MAX_REPAIR_CUTS = 80_MAX_RAW_ELEMENTS = 64@@ -183,8 +187,36 @@ def _props(element: Dict[str, Any]) -> Dict[str, Any]:return props+def _pressed(on: Any) -> Optional[Tuple[str, Dict[str, Any]]]:+ """The first binding under ``on.press`` (one, or a list) whose action is known."""+ if not isinstance(on, dict):+ return None+ press = on.get("press")+ for binding in press if isinstance(press, list) else [press]:+ if isinstance(binding, dict):+ action = canonical_action(binding.get("action"))+ if action:+ params = binding.get("params")+ return action, params if isinstance(params, dict) else {}+ return None+++def button_press(element: Dict[str, Any], props: Dict[str, Any]) -> Optional[Tuple[str, Dict[str, Any]]]:+ """A Button's action and params: ``on.press`` beside its props, or+ inside them, else the older ``action`` / ``actionParams`` props."""+ pressed = _pressed(element.get("on")) or _pressed(props.get("on"))+ if pressed:+ return pressed+ action = canonical_action(props.get("action"))+ if action is None:+ return None+ params = props.get("actionParams")+ return action, params if isinstance(params, dict) else {}++def usable_elements(spec: Any) -> List[Dict[str, Any]]:- """The elements the client would keep, with their props merged."""+ """The elements the client would keep, with their props merged (and a+ Button's ``press``: its action and params)."""if not isinstance(spec, dict) or not isinstance(spec.get("elements"), dict):return []known = component_types()@@ -198,11 +230,15 @@ def usable_elements(spec: Any) -> List[Dict[str, Any]]:if kind not in known:continueprops = _props(element)- if kind == "Button" and (not _text(props.get("label")) or canonical_action(props.get("action")) is None):- continue+ usable: Dict[str, Any] = {"type": kind, "props": props}+ if kind == "Button":+ press = button_press(element, props)+ if not _text(props.get("label")) or press is None:+ continue+ usable["press"] = pressif kind == "AgentCard" and not _text(props.get("name")):continue- kept.append({"type": kind, "props": props})+ kept.append(usable)return kept@@ -242,8 +278,7 @@ def app_names(raw: Any) -> List[str]:if isinstance(step, dict):add(step.get("app"))elif element["type"] == "Button":- action = canonical_action(props.get("action"))- params = props.get("actionParams") if isinstance(props.get("actionParams"), dict) else {}+ action, params = element["press"]if action == "connect_app":add(params.get("app"))elif action == "hire_employee":@@ -256,4 +291,4 @@ def app_names(raw: Any) -> List[str]:return list(seen.values())-__all__ = ["ParsedReply", "app_names", "is_salvageable", "parse_reply", "repair_json", "usable_elements"]+__all__ = ["ParsedReply", "app_names", "button_press", "is_salvageable", "parse_reply", "repair_json", "usable_elements"]diff --git a/server/tests/services/employees/test_setup_prompt.py b/server/tests/services/employees/test_setup_prompt.pyindex 9be5f2d9..bd8e417e 100644--- a/server/tests/services/employees/test_setup_prompt.py+++ b/server/tests/services/employees/test_setup_prompt.py@@ -55,13 +55,22 @@ def test_catalogue_prompt_lists_every_component_and_action():def test_prompt_carries_the_additions():prompt = catalog_prompt()assert '"Ask me before sending anything" bound to "/rules/askFirst", true in "state"' in prompt- assert 'Toggles bound to state under "/rules"' in prompt+ assert 'Toggles bound to state under "/rules" through "checked"' in promptassert 'one Choice bound under "/choices"' in prompt- assert "actionParams {name, role, apps, trigger, sendsVia}" in prompt+ assert 'on.press {"action": "hire_employee", "params": {name, role, apps, trigger, sendsVia}}' in promptassert '"kind": "app_event"|"schedule"|"manual"' in promptassert 'names it in "app"' in prompt+def test_prompt_asks_for_json_renders_shape():+ # A Button's action is the element's on.press, never a prop.+ prompt = catalog_prompt()+ assert '"on"?: {"press": {"action", "params"?}}' in prompt+ assert '{"type":"Button","props":{"label":"…"},"on":{"press":{"action":"refine"}},"children":[]}' in prompt+ assert "actionParams" not in prompt+ assert "- Toggle {label, description?, checked:" in prompt++def test_the_schedule_times_offered_are_the_ones_it_can_run():times = "|".join(f'"{value}"' for value in load_genui_catalog()["trigger"]["times"])assert f'"at"?: {times}' in catalog_prompt()diff --git a/server/tests/services/employees/test_setup_salvage_parity.py b/server/tests/services/employees/test_setup_salvage_parity.pyindex c4c09628..4076747d 100644--- a/server/tests/services/employees/test_setup_salvage_parity.py+++ b/server/tests/services/employees/test_setup_salvage_parity.py@@ -38,6 +38,18 @@ def test_app_names_come_from_every_place_a_reply_names_an_app():assert app_names(clean["reply"]) == ["WhatsApp", "Google Calendar"]+def test_app_names_read_a_buttons_on_press_too():+ shaped = next(case for case in _cases() if case["name"] == "json-render shape: on.press and checked")+ assert app_names(shaped["reply"]) == ["WhatsApp", "Google Calendar"]+ connect = (+ '{"text":"x","spec":{"root":"b","elements":{"b":{"type":"Button","props":{"label":"Connect"},'+ '"on":{"press":[{"action":"wave"},{"action":"connect_app","params":{"app":"Stripe"}}]}},'+ '"h":{"type":"Button","props":{"label":"Hire","on":{"press":{"action":"hire_employee",'+ '"params":{"trigger":{"kind":"app_event","app":"Gmail"},"sendsVia":"Slack"}}}}}}}}'+ )+ assert app_names(connect) == ["Stripe", "Gmail", "Slack"]++def test_repair_closes_what_is_open():assert repair_json('{"a":{"b":[1,2') == {"a": {"b": [1]}}assert repair_json('{"a":"unterminated') is Nonediff --git a/server/tests/test_genui_catalog_sync.py b/server/tests/test_genui_catalog_sync.pyindex 80816360..c71edf77 100644--- a/server/tests/test_genui_catalog_sync.py+++ b/server/tests/test_genui_catalog_sync.py@@ -116,6 +116,27 @@ def test_every_component_has_a_prop_schema(catalog_ts):assert declared == set(_string_list(catalog_ts, "COMPONENT_TYPES"))+def _prop_schema(catalog_ts: str, name: str) -> str:+ """One component's schema in PROP_SCHEMAS, up to the next component."""+ schemas = re.search(r"export const PROP_SCHEMAS = \{(.*)\} satisfies", catalog_ts, re.DOTALL)+ assert schemas, "could not find PROP_SCHEMAS"+ match = re.search(rf"^ {name}: z\.(.*?)(?=^ \w+: z\.|\Z)", schemas.group(1), re.MULTILINE | re.DOTALL)+ assert match, f"could not find the {name} schema"+ return match.group(1)+++def test_the_spec_is_in_json_renders_shape_on_both_sides(manifest, catalog_ts):+ """spec_version 2: a Toggle binds `checked`, and a Button's action is+ the element's on.press, never a prop. The prompt says so and the+ renderer reads the same props."""+ assert "checked:" in manifest["components"]["Toggle"]["props"]+ assert re.search(r"\bchecked:", _prop_schema(catalog_ts, "Toggle"))+ assert not re.search(r"\bvalue:", _prop_schema(catalog_ts, "Toggle"))+ assert "action" not in manifest["components"]["Button"]["props"]+ assert '"on":{"press":' in manifest["components"]["Button"]["description"]+ assert not re.search(r"\baction(Params)?:", _prop_schema(catalog_ts, "Button"))++def test_manifest_is_plain_json():raw = (Path(__file__).resolve().parents[1] / "config" / "genui_catalog.json").read_text(encoding="utf-8")- assert json.loads(raw)["spec_version"] == 1+ assert json.loads(raw)["spec_version"] == 2