A Design workspace in Claude Code: see design options for a UI as images, select one, ask for more, ask for a change with a note and hand an option off to be…

Open a Design workspace in Claude Code: a pane that shows design options for an app or a website as images. Select the one you like, ask for more options, ask for a change to an option with a note, and hand an option off to be built.
Your agent runs the 12ui command line once per request, which draws every option at once with your own Codex sign-in and image generation, and adds each option to the workspace as it finishes. Your agent never draws in the conversation. Drawing, editing, branching and Build this need no 12ui account: branching plans and draws the new screens with your own Codex too, and a workspace is reached through a private handle held in your session. Images are stored for up to 30 days and removed after 14 days without use.
Works in Claude Code on a computer with Node.js; your agent installs the 12ui command line once. Drawing needs Codex signed in with ChatGPT on the same computer; without it nothing is drawn and each option shows the reason. The pane needs Claude Code 2.1.287 or later, in the terminal or the Desktop app's Code tab. The draw command reaches design.12ui.com, and Claude Code asks you to approve it.
Version 0.2.130. Install with claude plugin marketplace add just-every/12ui-plugin, then claude plugin install 12ui-design@12ui-plugin.
npx -y @12ui/design cli install.12ui auth login).12ui-design). It runs npx -y @12ui/design cli install once, from npm and unpinned, then 12ui commands. Those commands reach https://12ui.com (hosted draft, branch, conversion, the design corpus and improve kits) and https://design.12ui.com (workspace plans, image upload and download), and run codex exec locally when Codex is ready. The skill also saves one workspace image from design.12ui.com.https://design.12ui.com/mcp: anonymous. It stores the brief and images; images are kept up to 30 days and removed after 14 days without use.The mod is the Design workspace pane. It runs inside Claude Code as plain readable source in hooks/.
https://design.12ui.com/mcp, this plugin's own MCP server. The address is written as fixed text at the mod's one network call, and the request cannot be sent anywhere else.design_slate_create and design_slate_show, for the workspace handle, and what you click and type in the pane. It reads nothing else from the conversation. The one file it reads is the picture whose path you type in the Sketches tab, when you press Add.{label} is an option's letter, {request} and {handle} are ids). Your own words are never put in a prompt; Claude reads them from the workspace.The user asked for new options in the Design workspace (request {request}, runDir {handle}). Please confirm it with design.slate.data, then carry it out.The user asked for more like {label} in the Design workspace (request {request}, runDir {handle}). Please confirm it with design.slate.data, then carry it out.The user asked to edit {label} in the Design workspace (request {request}, runDir {handle}). Please confirm it with design.slate.data, then carry it out.The user asked to simplify {label} in the Design workspace (request {request}, runDir {handle}). Please confirm it with design.slate.data, then carry it out.The user asked to draw option {label} again in the Design workspace (request {request}, runDir {handle}). Please confirm it with design.slate.data, then carry it out.The user asked for more options of one group in the Design workspace (request {request}, runDir {handle}). Please confirm it with design.slate.data, then carry it out.The user asked for the full page of {label} in the Design workspace (request {request}, runDir {handle}). Please confirm it with design.slate.data, then carry it out.The user asked for more pages of {label} in the Design workspace (request {request}, runDir {handle}). Please confirm it with design.slate.data, then carry it out.The user chose design {label} to build in the Design workspace (runDir {handle}). Please read its selection with design.slate.data, then build that design as the user's request asks.Hooks it registers, each with what it is for:
tool.call{tool=mcp__plugin_12ui-design_12ui-workspace__design_slate_create|mcp__plugin_12ui-design_12ui-workspace__design_slate_show}: observes only this plugin's own create and show tools: reads the workspace handle from the result and opens the pane; it never changes or blocks the call, and reads nothing elseui.render{component=Pane}: draws the Design workspace pane and passes every other plugin's pane on untouchedui.render{component=AbovePrompt}: while the pane waits for room on a narrow terminal, shows one line with an Open button above the prompt; otherwise passes on untouchedCalls it makes, each with its purpose:
$.clock.after: schedules the next workspace refresh, the follow-up check after a click, and one redraw for pictures that land together or for what changed during your presses$.clock.now: reads the time to pace the workspace refreshes and redraws, and to refresh when the start countdown ends$.fs.read: reads the one picture file whose path you type in the Sketches tab when you press Add, to send it as your own sketch; it reads no other file$.http.fetch: reads the workspace and records your clicks at https://design.12ui.com/mcp$.prompt.submit: tells Claude, in one fixed line, what you clicked in the pane (new options, more like an option, an edit, a simplify, a retry, a branch, Build this); never your own words$.ui.blit: asks whether the terminal shows pictures, to switch to colour cells where it cannot$.ui.invalidate: redraws the pane when the workspace changes$.ui.log: writes diagnostic lines to Claude Code's debug log$.ui.open: opens the Design workspace pane, and again when you press Open above the prompt$.ui.panes: checks whether the Design workspace pane is still open, and stops polling once you have closed it$.ui.resolve: reads the elements the surface draws with$.ui.toast: says the workspace is ready when the terminal is too narrow to show the paneclaude -p or Chat.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC is set.| Name | Version | License | Source |
|---|---|---|---|
| jpeg-js decoder | 0.4.4 | Apache-2.0 (file header); BSD-3-Clause (package) | https://github.com/jpeg-js/jpeg-js |
The 12ui-design skill as a Codex plugin. The skill uses the 12ui command line for local work. The hosted service and its documentation live at 12ui.com.
This repository is generated from the private 12ui implementation at the exact @12ui/design release revision. Version 0.2.130 matches the npm package.
Add this repository as the 12ui-plugin marketplace, then install the 12ui-design plugin from it:
codex plugin marketplace add just-every/12ui-plugin
codex plugin add 12ui-design@12ui-plugin
The marketplace metadata is generated at /.agents/plugins/marketplace.json, and the plugin manifest is at /.codex-plugin/plugin.json.
The cross-agent installer supports Codex, Claude Code, Grok, Cursor, Antigravity, and GitHub Copilot:
npx -y @12ui/design skill install
That installer places only 12ui-design; recognized historical design bundles are retired, while locally modified copies are preserved.
12ui-design is installed byte-identically for every supported client. Run 12ui capabilities to see what the installed command line supports before a run.
Each GitHub release attaches 12ui-design-0.2.130.zip, the validated plugin with the manifest and skill at the archive root, and 12ui-design-0.2.130-openai.zip, its skills-only form for the OpenAI Plugins Directory manual upload flow.
Every release is generated from a fixed allowlist, validated for exact skill, icon, manifest, and marketplace parity, packaged as a zip, tagged design-v0.2.130, and published only after the matching npm release completes. Do not edit generated files directly; changes must originate in the 12ui release source.
MIT. See LICENSE.
hooks/register.mjs 930 lines1/**
2 * The 12ui Design workspace pane for Claude Code: the glue that wires the hooks to the modules in ./workspace.
3 *
4 * Hooks:
5 * this plugin's own create and show tools reads the workspace handle from their result, opens the pane
6 * drawing the Pane draws the workspace in its own pane; passes every other pane on
7 * drawing above the prompt while the pane waits for room, one Open button; otherwise passes on
8 * closing the pane stops polling
9 *
10 * Every `$` call lives in this file, because the engine follows `$` only into functions declared in the hooks module
11 * itself. The one network request is the fetch in `rpc`, its address and options written at the call: the plugin's
12 * own MCP server. It sends workspace handles, ids, picks and the words typed in the pane, never the conversation.
13 * `$.prompt.submit` tells Claude, in one fixed line, what the person clicked; `$.ui.*` draws, `$.clock.*` polls and
14 * counts down. `$.fs.read` reads one picture file, and only when the person types its path in the Sketches tab and presses
15 * Add. Nothing else: the mod reads nothing else from the computer, runs nothing and touches no other tool's calls.
16 */
17
18import { SELECTION_MAX, actionError as refusal, continueArgs, convertHandoffArgs, holdArgs, inspirationArgs, inspireArgs, isActionError, pickArgs, runBranchArgs, runEditArgs, runKeepArgs, runNewArgs, runRetryArgs, runSimplifyArgs } from './workspace/actions.mjs';
19import { uuidV4 } from './workspace/bytes.mjs';
20import { LOADING, NO_WORKSPACE, PANE_ID, PANE_TITLE, READY_TOAST, RECORDED_RUNNER, SENT, SKETCHES_NONE } from './workspace/copy.mjs';
21import { PER_ROUND, SEARCH_COUNT, inspirationIds, openingTab, perRoundOf, pickLimit, picksOf, referenceSize, sameList, selectedOf, siteItems, tabThumbs, togglePick, twelveDraws, viewThumbs, waitingRound } from './workspace/gallery.mjs';
22import { handleFromCall } from './workspace/handles.mjs';
23import { afterRun, buildMessage, judgeRunner, runMessage } from './workspace/messages.mjs';
24import { bandTree, paneTree } from './workspace/pane.mjs';
25import { pictureMaxRows, tileGrid } from './workspace/layout.mjs';
26import { SVG_MAX_CHARS, blitSaysAlt, decodeThumb, desktopPictureSize, imageSource, imageTreeBudget, pictureKind, rasterCells, svgPicture, tileBox, useCellsFor } from './workspace/picture.mjs';
27import { nextStep, pollDelay, retriesFirstRead, wantsPolling } from './workspace/poll.mjs';
28import { drawnSignature, pictureRedrawDelay, pressQuietDelay } from './workspace/redraw.mjs';
29import { designSections } from './workspace/sections.mjs';
30import { isSketchId, sketchName, sketchSize, sketchUpload, sketchesDrawing, sketchesOf, typedPath } from './workspace/sketches.mjs';
31import { TOOLS, errorLine, imageBlock, isWorkspaceError, mendsOnRetry, readRpc, rpcBody, workspaceError } from './workspace/transport.mjs';
32import { briefLine, countdownLine, countdownOf, findOp, hasRunning, isView, labelOfVersion, opWaitsOnPerson, tilesOf } from './workspace/view.mjs';
33
34// ---- the session's state: module memory, as the hosted screen keeps it (a reload starts over) ----
35let current = null;
36// True while the pane is open but waits undrawn (opened unasked on a narrow terminal): the band above the prompt offers Open.
37let paneWaits = false;
38const views = new Map();
39// Thumbnails, request-id drafts and clicks in flight are kept per workspace: the server mints option and version ids per
40// workspace (every workspace's first option is `r1_a` / `v_r1_a`), so an id alone names nothing across workspaces.
41const thumbs = new Map();
42const drafts = new Map();
43const inFlight = new Set();
44const runnerWatch = new Map();
45// What the person is doing in the pane: the tab (`openedFor`: the workspace whose opening tab was chosen), the prompt
46// line, the waiting round's picks, the large view.
47const ui = { tab: 'inspiration', autoTab: false, openedFor: null, prompt: '', promptEdited: false, chosen: null, chosenOp: null, heldOp: null, pauseOp: null, lv: null, perRound: null, keep: {}, sketchPath: '' };
48// The selection the next round draws from while no round waits (references, websites and sketches, at most eight): the
49// person's toggles not yet answered (`ids`, null when the view's own stands), written whole by one request at a time.
50const selection = { ids: null, sending: false };
51const poll = { timer: null, step: 0, busy: false, isOpen: false, failedRetryably: false };
52const blit = { altDrawn: false, toggled: null, probed: false, lastAnswer: null };
53// The pane's own redraws (redraw.mjs): what the last drawing showed (`shows`: the workspace whose view it drew) and for
54// which surface and props, when the pane last asked for one on its own, the batch of pictures waiting to be drawn
55// together (when it began, its timer), the person's last press and the redraw waiting for the pause after it.
56const redraw = { drawn: null, shows: null, surface: null, props: null, lastSelfAtMs: null, batchStartAtMs: null, timer: null, lastPressAtMs: null, quietTimer: null };
57let pollError = '';
58let actionError = '';
59let noticeText = '';
60
61// ---- the wire ----
62/** One JSON-RPC `tools/call` to the plugin's own MCP server: the mod's one network request, its address fixed here. */
63async function rpc($, name, args) {
64 const response = await $.http.fetch('https://design.12ui.com/mcp', {
65 method: 'POST',
66 headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', 'mcp-protocol-version': '2025-06-18' },
67 body: rpcBody(name, args),
68 });
69 return readRpc(response);
70}
71
72function viewOf(runDir) {
73 const entry = runDir ? views.get(runDir) : null;
74 return entry ? entry.view : null;
75}
76
77/** The slot of anything kept per workspace and per item: the workspace handle, then the item's own parts. */
78function workspaceSlot(runDir, ...parts) {
79 return [runDir, ...parts].join('\u0000');
80}
81
82function draftId(slot) {
83 if (!drafts.has(slot)) drafts.set(slot, uuidV4());
84 return drafts.get(slot);
85}
86
87// ---- the view, the pictures and the polling ----
88async function applyView($, runDir, view) {
89 views.set(runDir, { view, receivedAtMs: await $.clock.now() });
90 if (runDir !== current) return;
91 followPause(runDir, view, views.get(runDir).receivedAtMs);
92 fetchThumbs($, runDir);
93 // A view whose shown tab still waits on pictures (ones it brings, or ones already being read) is drawn once, together
94 // with them: it joins their batch (redraw.mjs PICTURE_WAIT_MS at most) instead of drawing its tiles loading and then
95 // again with their pictures. That holds for the first view too: until it draws, the pane says it is loading and has
96 // no tabs to press. A view with every picture in is drawn at once.
97 if (thumbsOut() > 0) await joinPictureBatch($);
98 else await redrawIfChanged($);
99}
100
101/** Reads every thumbnail of the view the pane does not hold yet, the shown tab's first (gallery.mjs `viewThumbs`). */
102function fetchThumbs($, runDir) {
103 const view = viewOf(runDir);
104 if (!view || runDir !== current) return;
105 for (const want of viewThumbs(view, ui.tab)) {
106 const slot = workspaceSlot(runDir, want.slot);
107 if (thumbs.has(slot)) continue;
108 void fetchThumb($, slot, want.kind === 'version' ? TOOLS.image : TOOLS.reference, { runDir, ...want.args, size: 'thumb' });
109 }
110}
111
112/** Whether the shown tab of the shown workspace draws the thumbnail kept under `slot`. */
113function isShown(slot) {
114 const view = viewOf(current);
115 return Boolean(view) && tabThumbs(view, ui.tab).some((want) => workspaceSlot(current, want.slot) === slot);
116}
117
118/** How many of the shown tab's thumbnails are still being read. */
119function thumbsOut() {
120 const view = viewOf(current);
121 if (!view) return 0;
122 return tabThumbs(view, ui.tab).filter((want) => {
123 const thumb = thumbs.get(workspaceSlot(current, want.slot));
124 return thumb && thumb.state === 'loading';
125 }).length;
126}
127
128/**
129 * The tab a workspace opens on (gallery.mjs `openingTab`): Inspiration with its picks preselected while a round waits on
130 * the person, else Designs once it has options. A round that starts waiting later moves the pane to Inspiration; when
131 * the wait ends (Continue, or the countdown ran out) a pane the round put on Inspiration moves to Designs, as the screen
132 * does.
133 */
134function followPause(runDir, view, receivedAtMs) {
135 const countdown = countdownOf(view, receivedAtMs);
136 const opening = ui.openedFor !== runDir;
137 ui.openedFor = runDir;
138 if (opening && !countdown) {
139 ui.tab = openingTab(view, false);
140 ui.autoTab = false;
141 } else if (countdown && ui.pauseOp !== countdown.opId) {
142 ui.pauseOp = countdown.opId;
143 ui.chosen = null;
144 ui.chosenOp = null;
145 if (ui.tab !== 'inspiration') ui.tab = 'inspiration';
146 ui.autoTab = true;
147 } else if (!countdown && ui.pauseOp) {
148 ui.pauseOp = null;
149 if (ui.autoTab) ui.tab = 'designs';
150 ui.autoTab = false;
151 }
152}
153
154async function fetchThumb($, slot, tool, args) {
155 thumbs.set(slot, { state: 'loading' });
156 try {
157 const { content, structured } = await rpc($, tool, args);
158 const block = imageBlock(content);
159 if (block) thumbs.set(slot, { state: 'ready', jpeg: block.data, mimeType: block.mimeType, cache: new Map() });
160 // A model sketch answers its SVG text, not an image (the reference tool, workers/api/src/slate/mcp/handlers/images.ts).
161 else if (structured && typeof structured.svg === 'string') thumbs.set(slot, { state: 'ready', svg: structured.svg, cache: new Map() });
162 else throw workspaceError('No picture came back.');
163 } catch (error) {
164 thumbs.set(slot, { state: 'failed', reason: errorLine(error) });
165 }
166 // Another tab's picture, or another workspace's, changes nothing drawn: it waits in `thumbs` for that tab's drawing.
167 if (isShown(slot)) await joinPictureBatch($);
168}
169
170/**
171 * A shown picture landed, or a view that waits on some: drawn with the others of the shown tab, in one redraw once the
172 * last is in, or when the batch has waited PICTURE_WAIT_MS (redraw.mjs `pictureRedrawDelay`).
173 */
174async function joinPictureBatch($) {
175 const now = await $.clock.now();
176 if (redraw.batchStartAtMs === null) redraw.batchStartAtMs = now;
177 // The once-a-second pace is between drawings of one workspace's view: a workspace's first view (the pane says it is
178 // loading) draws as soon as its pictures are in.
179 const paced = redraw.lastSelfAtMs !== null && redraw.shows === current;
180 const delay = pictureRedrawDelay({
181 sinceLastSelfMs: paced ? now - redraw.lastSelfAtMs : null,
182 sinceBatchStartMs: now - redraw.batchStartAtMs,
183 outstanding: thumbsOut(),
184 });
185 if (redraw.timer) redraw.timer.cancel();
186 redraw.timer = $.clock.after(delay, () => {
187 redraw.timer = null;
188 redraw.batchStartAtMs = null;
189 void redrawIfChanged($);
190 });
191}
192
193/** What `thumbs` holds for a slot, as a drawing would show it, without decoding or encoding a picture. */
194function thumbFact(thumbSlot) {
195 const thumb = thumbs.get(thumbSlot);
196 if (!thumb) return null;
197 if (thumb.state === 'loading') return { kind: 'loading' };
198 if (thumb.state === 'failed') return { kind: 'failed', reason: thumb.reason };
199 return { kind: 'ready' };
200}
201
202/**
203 * A redraw the pane asks for on its own (a view, pictures, a poll's error): only when what it would draw differs from
204 * what is drawn (redraw.mjs `drawnSignature`), and only once the person has paused pressing (`pressQuietDelay`).
205 * Presses redraw directly.
206 */
207async function redrawIfChanged($) {
208 const now = await $.clock.now();
209 const quiet = pressQuietDelay(redraw.lastPressAtMs === null ? null : now - redraw.lastPressAtMs);
210 if (quiet > 0) {
211 if (!redraw.quietTimer) redraw.quietTimer = $.clock.after(quiet, () => { redraw.quietTimer = null; void redrawIfChanged($); });
212 return;
213 }
214 if (redraw.drawn !== null) {
215 const { model } = paneModel(redraw.surface, redraw.props, thumbFact);
216 const signature = drawnSignature(model);
217 if (signature === redraw.drawn) return;
218 redraw.drawn = signature;
219 }
220 redraw.lastSelfAtMs = now;
221 $.ui.invalidate('ui.render');
222}
223
224function stopPolling() {
225 if (poll.timer) poll.timer.cancel();
226 poll.timer = null;
227}
228
229/** Whether the Design workspace pane is still on screen: the person closing it raises nothing a hook sees, so this asks. */
230async function paneIsUp($) {
231 return (await $.ui.panes()).some((pane) => pane.id === PANE_ID);
232}
233
234/** The pane is gone: nothing polls or waits for it any more. */
235function paneGone() {
236 poll.isOpen = false;
237 paneWaits = false;
238 stopPolling();
239}
240
241async function schedulePoll($) {
242 stopPolling();
243 const entry = views.get(current);
244 const running = wantsPolling({ isOpen: poll.isOpen, hasWorkspace: Boolean(entry), isRunning: Boolean(entry && hasRunning(entry.view)) });
245 const retrying = retriesFirstRead({ isOpen: poll.isOpen, hasView: Boolean(entry), failedRetryably: poll.failedRetryably });
246 if (!running && !retrying) return;
247 const delay = pollDelay(poll.step, entry ? countdownOf(entry.view, entry.receivedAtMs) : null, await $.clock.now());
248 poll.timer = $.clock.after(delay, () => { void refresh($); });
249}
250
251/** Read the shown workspace now, once the current turn of the clock is through (a pane in sight only). */
252function readSoon($) {
253 if (poll.isOpen && current) $.clock.after(0, () => { void refresh($); });
254}
255
256/**
257 * One status read for the shown workspace (the screen in sight), then the next one if anything still runs or a first
258 * read failed in a way a retry can mend. A read only ever lands on the workspace it asked about: when the person
259 * switched workspaces while it was out, its answer is dropped and the workspace now shown is read instead (the read
260 * the switch asked for found this one still out and was dropped).
261 */
262async function refresh($) {
263 if (!(await paneIsUp($))) {
264 paneGone();
265 return;
266 }
267 const runDir = current;
268 if (!runDir || poll.busy) return;
269 poll.busy = true;
270 let changed = false;
271 try {
272 const known = viewOf(runDir);
273 const { structured } = await rpc($, TOOLS.status, known ? { runDir, since: known.stamp } : { runDir });
274 if (isView(structured) && runDir === current) {
275 changed = true;
276 pollError = '';
277 poll.failedRetryably = false;
278 await applyView($, runDir, structured);
279 }
280 } catch (error) {
281 if (runDir === current) {
282 pollError = errorLine(error);
283 poll.failedRetryably = mendsOnRetry(error);
284 await redrawIfChanged($);
285 }
286 } finally {
287 poll.busy = false;
288 }
289 if (runDir !== current) {
290 if (poll.isOpen) await refresh($);
291 return;
292 }
293 poll.step = nextStep(poll.step, changed);
294 await schedulePoll($);
295}
296
297/**
298 * Show `runDir` in the pane. A different workspace starts over and, with the pane open, is read at once (an open pane
299 * reads nothing else for a workspace it holds no view of). The workspace already shown is read again only while the
300 * pane holds no view of it, as after a first read the server refused: that is how showing it again asks once more.
301 */
302function showWorkspace($, runDir) {
303 if (runDir === current) {
304 if (!views.has(runDir)) readSoon($);
305 return;
306 }
307 current = runDir;
308 stopPolling();
309 poll.step = 0;
310 poll.failedRetryably = false;
311 pollError = '';
312 actionError = '';
313 noticeText = '';
314 ui.lv = null;
315 ui.pauseOp = null;
316 ui.promptEdited = false;
317 ui.keep = {};
318 ui.sketchPath = '';
319 selection.ids = null;
320 // Presses on the last workspace's drawing hold back no redraw of this one: what they pressed on is gone.
321 redraw.lastPressAtMs = null;
322 // No redraw here: its one caller opens the pane next, and that open redraws it.
323 readSoon($);
324}
325
326/**
327 * Open the pane. Opened unasked (Claude opened a workspace) a narrow terminal keeps it waiting undrawn: the toast says
328 * so and the band above the prompt offers Open, which the person presses, so that open is asked and placed at any width.
329 */
330async function openPane($, asked) {
331 const opened = await $.ui.open(asked ? { id: PANE_ID, title: PANE_TITLE, focus: true } : { id: PANE_ID, title: PANE_TITLE });
332 paneWaits = !opened.isPlaced;
333 if (paneWaits && !asked) $.ui.toast(READY_TOAST);
334 $.ui.invalidate('ui.render');
335 return opened;
336}
337
338// ---- telling Claude ----
339function tell($, text) {
340 $.prompt.submit({ text }).catch((error) => {
341 actionError = `Recorded, but Claude Code did not take the message: ${error && error.message ? error.message : String(error)}`;
342 $.ui.invalidate('ui.render');
343 });
344 noticeText = SENT;
345}
346
347async function runnerCheck($, runDir, opId) {
348 const watch = runnerWatch.get(opId);
349 if (!watch) return;
350 try {
351 const { structured } = await rpc($, TOOLS.status, { runDir });
352 if (isView(structured)) await applyView($, runDir, structured);
353 } catch {
354 // The check judges on the last view the pane holds, as the hosted screen does.
355 }
356 const view = viewOf(runDir);
357 const op = view ? findOp(view, opId) : null;
358 const verdict = judgeRunner(op, view ? opWaitsOnPerson(view, op) : false, watch);
359 if (verdict.drop) {
360 runnerWatch.delete(opId);
361 return;
362 }
363 if (verdict.tell) {
364 runnerWatch.delete(opId);
365 tell($, watch.message);
366 $.ui.invalidate('ui.render');
367 return;
368 }
369 watch.waited = verdict.waited;
370 $.clock.after(verdict.waitMs, () => { void runnerCheck($, runDir, opId); });
371}
372
373function afterRunRecorded($, runDir, opId, message, runner) {
374 const first = afterRun(runner);
375 if (first.tell) {
376 tell($, message);
377 return;
378 }
379 noticeText = RECORDED_RUNNER;
380 runnerWatch.set(opId, { message, waited: false });
381 $.clock.after(first.waitMs, () => { void runnerCheck($, runDir, opId); });
382}
383
384// ---- the clicks ----
385async function record($, slot, work) {
386 if (inFlight.has(slot)) return;
387 inFlight.add(slot);
388 // A press whose drawing would be the one already drawn asks for none: every fresh drawing retires the buttons the person
389 // may press next (redraw.mjs), so only a stale error or notice, which the press clears, is drawn away now.
390 const staleWords = Boolean(actionError || noticeText);
391 actionError = '';
392 noticeText = '';
393 if (staleWords) $.ui.invalidate('ui.render');
394 try {
395 await work();
396 drafts.delete(slot);
397 } catch (error) {
398 actionError = isActionError(error) ? error.message : errorLine(error);
399 // A request the server answered and refused is done with: the next try is a new request. One that may not have
400 // reached it (no answer, or a retryable status) keeps its id, so trying again cannot record it twice.
401 if (isWorkspaceError(error) && !error.retryable) drafts.delete(slot);
402 } finally {
403 inFlight.delete(slot);
404 $.ui.invalidate('ui.render');
405 }
406}
407
408async function recordRun($, slot, args) {
409 const runDir = args.runDir;
410 const { structured } = await rpc($, TOOLS.run, args);
411 const view = structured && isView(structured.view) ? structured.view : viewOf(runDir);
412 const message = runMessage(runDir, args.opId, args.action, (versionId) => (view ? labelOfVersion(view, versionId) : null));
413 if (structured && isView(structured.view)) await applyView($, runDir, structured.view);
414 afterRunRecorded($, runDir, args.opId, message, structured ? structured.runner : null);
415 poll.step = 0;
416 await schedulePoll($);
417}
418
419/** The waiting round's op, its picks and whether the person changed them, for the shown workspace. */
420function pauseNow() {
421 const entry = views.get(current);
422 const countdown = entry ? countdownOf(entry.view, entry.receivedAtMs) : null;
423 if (!entry || !countdown) return null;
424 const round = waitingRound(entry.view);
425 const picks = picksOf(entry.view, ui.chosenOp === countdown.opId ? ui.chosen : null);
426 return { view: entry.view, countdown, round, picks, changed: Boolean(round && ui.chosenOp === countdown.opId && ui.chosen && !sameList(ui.chosen, round.referenceIds || [])) };
427}
428
429/** The screen holds a waiting round's countdown once the person touches it; the pane does the same on the first pick. */
430function holdOnce($) {
431 const pause = pauseNow();
432 if (!pause || pause.countdown.state !== 'countdown' || ui.heldOp === pause.countdown.opId) return;
433 ui.heldOp = pause.countdown.opId;
434 const runDir = current;
435 rpc($, TOOLS.run, holdArgs(runDir, pause.countdown.opId)).then(async ({ structured }) => {
436 if (structured && isView(structured.view) && runDir === current) await applyView($, runDir, structured.view);
437 }, (error) => { actionError = errorLine(error); $.ui.invalidate('ui.render'); });
438}
439
440/**
441 * A pick. While a round waits it is that round's pick (and holds its countdown); otherwise it is a toggle of the
442 * selection the next round draws from, written whole to the server one request at a time.
443 */
444function togglePickOf($, id) {
445 const pause = pauseNow();
446 if (!pause) {
447 toggleSelection($, id);
448 return;
449 }
450 const next = togglePick(pause.picks, id, pickLimit(pause.view));
451 if (next.refused) noticeText = `At most ${pickLimit(pause.view)} picks.`;
452 else noticeText = '';
453 ui.chosen = next.picks;
454 ui.chosenOp = pause.countdown.opId;
455 holdOnce($);
456 $.ui.invalidate('ui.render');
457}
458
459/** The selection as the pane shows it now: the person's unanswered toggles, else the view's. */
460function selectionNow() {
461 const view = viewOf(current);
462 return view ? selectedOf(view, selection.ids) : [];
463}
464
465function toggleSelection($, id) {
466 const next = togglePick(selectionNow(), id, SELECTION_MAX);
467 noticeText = next.refused ? `At most ${SELECTION_MAX} picks.` : '';
468 if (!next.refused) selection.ids = next.picks;
469 $.ui.invalidate('ui.render');
470 if (!next.refused) void flushSelection($);
471}
472
473/** Writes the selection whole, one request in flight; a toggle made meanwhile is sent next, so the last click wins. */
474async function flushSelection($) {
475 if (selection.sending) return;
476 selection.sending = true;
477 const runDir = current;
478 try {
479 while (selection.ids !== null && runDir === current) {
480 const sent = selection.ids;
481 const { structured } = await rpc($, TOOLS.inspiration, inspirationArgs(runDir, sent));
482 if (runDir !== current) break;
483 if (selection.ids !== null && sameList(selection.ids, sent)) selection.ids = null;
484 if (structured && isView(structured.view)) await applyView($, runDir, structured.view);
485 }
486 } catch (error) {
487 selection.ids = null;
488 actionError = errorLine(error);
489 $.ui.invalidate('ui.render');
490 } finally {
491 selection.sending = false;
492 }
493}
494
495/** Retry: a failed option drawn again through its failed round's own request. */
496function retryOption($, tile) {
497 if (!tile.retryOpId) return Promise.resolve();
498 const runDir = current;
499 const slot = workspaceSlot(runDir, 'retry', tile.retryOpId, tile.optionLabel);
500 return record($, slot, () => recordRun($, slot, runRetryArgs(runDir, tile.retryOpId, tile.optionLabel)));
501}
502
503/** Whether an option is kept now: the person's unanswered click, else the view's heart. */
504function keptNow(candidateId) {
505 const mine = ui.keep[candidateId];
506 if (mine) return mine.kept;
507 const view = viewOf(current);
508 const candidate = view ? view.candidates.find((entry) => entry.candidateId === candidateId) : null;
509 return Boolean(candidate && candidate.kept === true);
510}
511
512/** Keep: the heart toggles at once and is sent; it waits for nobody, so the agent is not told. The last click settles it. */
513function toggleKeep($, tile) {
514 const runDir = current;
515 const id = tile.candidateId;
516 const kept = !keptNow(id);
517 const seq = (ui.keep[id] ? ui.keep[id].seq : 0) + 1;
518 ui.keep[id] = { kept, seq };
519 $.ui.invalidate('ui.render');
520 rpc($, TOOLS.run, runKeepArgs(runDir, uuidV4(), tile.optionLabel, kept)).then(async ({ structured }) => {
521 const now = ui.keep[id];
522 // A later click is still on its way: its own answer settles the heart.
523 if (runDir !== current || !now || now.seq !== seq || !structured || !isView(structured.view)) return;
524 delete ui.keep[id];
525 await applyView($, runDir, structured.view);
526 }, (error) => {
527 const now = ui.keep[id];
528 if (runDir === current && now && now.seq === seq) delete ui.keep[id];
529 actionError = errorLine(error);
530 $.ui.invalidate('ui.render');
531 });
532}
533
534/** Simplify the large view's design, `standard` or `high`; the request is the agent's to draw, as an edit is. */
535function simplifyDesign($, level) {
536 const tile = largeTile();
537 if (!tile || !tile.versionId) return Promise.resolve();
538 const runDir = current;
539 const slot = workspaceSlot(runDir, 'simplify', tile.versionId, level);
540 return record($, slot, async () => {
541 await recordRun($, slot, runSimplifyArgs(runDir, draftId(slot), tile.versionId, level));
542 ui.lv = null;
543 });
544}
545
546/** More on one group of a mixed round: a round of that technique only, at the person's 6 or 12. */
547function moreOfGroup($, group) {
548 const view = viewOf(current);
549 if (!view || !group || hasRunning(view)) return Promise.resolve();
550 const runDir = current;
551 const slot = workspaceSlot(runDir, 'more', group);
552 return record($, slot, () => recordRun($, slot, runNewArgs(runDir, draftId(slot), { count: perRoundOf(view, ui.perRound), group })));
553}
554
555/** Add the person's own sketch: the picture file at the typed path, read here and sent with the selection, which it joins. */
556function addSketch($, text) {
557 ui.sketchPath = String(text ?? ui.sketchPath);
558 const runDir = current;
559 const path = typedPath(ui.sketchPath);
560 return record($, workspaceSlot(runDir, 'sketch-add'), async () => {
561 if (!path) throw refusal('Type the path of a JPEG, PNG or WebP file first.');
562 let read;
563 try {
564 read = await $.fs.read(path, { as: 'bytes' });
565 } catch (error) {
566 throw refusal(`Could not read ${path}: ${error && error.message ? error.message : String(error)}`);
567 }
568 const sketch = sketchUpload(read.base64);
569 const sent = selectionNow();
570 const { structured } = await rpc($, TOOLS.inspiration, inspirationArgs(runDir, sent, { sketch }));
571 ui.sketchPath = '';
572 ui.tab = 'sketches';
573 // The added sketch is a pick too: of the round that waits on the person, else of the selection.
574 const added = structured && Array.isArray(structured.selected) ? structured.selected.filter((id) => isSketchId(id) && !sent.includes(id))[0] : null;
575 if (structured && isView(structured.view)) await applyView($, runDir, structured.view);
576 if (!added) return;
577 const pause = pauseNow();
578 if (pause) {
579 if (!pause.picks.includes(added)) togglePickOf($, added);
580 } else if (selection.ids !== null && !selection.ids.includes(added)) selection.ids = [...selection.ids, added];
581 });
582}
583
584/** Remove one of the person's own sketches: off the tab and out of the selection, or of the waiting round's picks. */
585function removeSketch($, id) {
586 const runDir = current;
587 return record($, workspaceSlot(runDir, 'sketch-remove', id), async () => {
588 const pause = pauseNow();
589 if (pause && pause.picks.includes(id)) togglePickOf($, id);
590 if (selection.ids !== null) selection.ids = selection.ids.filter((entry) => entry !== id);
591 const keep = selectionNow().filter((entry) => entry !== id);
592 const { structured } = await rpc($, TOOLS.inspiration, inspirationArgs(runDir, keep, { removeSketch: id }));
593 if (structured && isView(structured.view)) await applyView($, runDir, structured.view);
594 });
595}
596
597function continueRound($) {
598 const pause = pauseNow();
599 if (!pause) return Promise.resolve();
600 const runDir = current;
601 const opId = pause.countdown.opId;
602 const brief = ui.promptEdited ? ui.prompt : '';
603 return record($, workspaceSlot(runDir, 'continue', opId), async () => {
604 const { structured } = await rpc($, TOOLS.run, continueArgs(runDir, opId, { referenceIds: pause.changed ? pause.picks : null, brief }));
605 ui.tab = 'designs';
606 ui.autoTab = false;
607 if (structured && isView(structured.view)) await applyView($, runDir, structured.view);
608 poll.step = 0;
609 await schedulePoll($);
610 });
611}
612
613function searchPrompt($, words) {
614 const runDir = current;
615 ui.prompt = String(words ?? ui.prompt);
616 ui.promptEdited = true;
617 holdOnce($);
618 return record($, workspaceSlot(runDir, 'inspire', ui.prompt), async () => {
619 const { structured } = await rpc($, TOOLS.inspire, inspireArgs(runDir, ui.prompt, SEARCH_COUNT));
620 ui.tab = 'inspiration';
621 if (structured && isView(structured.view)) await applyView($, runDir, structured.view);
622 else await refresh($);
623 });
624}
625
626function setPerRound($, n) {
627 const view = viewOf(current);
628 ui.perRound = n;
629 $.ui.invalidate('ui.render');
630 if (n !== 12 || !view || !twelveDraws(view, hasRunning(view))) return Promise.resolve();
631 const runDir = current;
632 const slot = workspaceSlot(runDir, 'more');
633 return record($, slot, () => recordRun($, slot, runNewArgs(runDir, draftId(slot), { count: 12 })));
634}
635
636function largeTile() {
637 const view = viewOf(current);
638 const tile = view && ui.lv ? tilesOf(view).find((entry) => entry.candidateId === ui.lv.candidateId) ?? null : null;
639 return tile ? { ...tile, kept: keptNow(tile.candidateId) } : null;
640}
641
642/** Build this: record the pick, record the Convert-to-HTML hand-off (the request Claude builds from), then tell Claude. */
643function buildThis($) {
644 const tile = largeTile();
645 if (!tile || !tile.versionId) return Promise.resolve();
646 const runDir = current;
647 const slot = workspaceSlot(runDir, 'build', tile.versionId);
648 return record($, slot, async () => {
649 const { structured } = await rpc($, TOOLS.pick, pickArgs(runDir, tile.versionId));
650 if (structured && isView(structured.view)) await applyView($, runDir, structured.view);
651 // One handoff id per version, kept until the whole click succeeded, so a retry never records a second request.
652 const handoff = await rpc($, TOOLS.handoff, convertHandoffArgs(runDir, draftId(slot), tile.versionId));
653 if (handoff.structured && isView(handoff.structured.view)) await applyView($, runDir, handoff.structured.view);
654 const label = structured && structured.pick && structured.pick.label ? structured.pick.label : tile.label;
655 tell($, buildMessage(runDir, label));
656 });
657}
658
659function editDesign($, words) {
660 const tile = largeTile();
661 if (!tile || !tile.versionId) return Promise.resolve();
662 const runDir = current;
663 const slot = workspaceSlot(runDir, 'edit', tile.versionId);
664 return record($, slot, async () => {
665 await recordRun($, slot, runEditArgs(runDir, draftId(slot), tile.versionId, words));
666 ui.lv = null;
667 });
668}
669
670function branchDesign($, scope, pagesText) {
671 const tile = largeTile();
672 if (!tile || !tile.versionId) return Promise.resolve();
673 const runDir = current;
674 // One draft per version and scope: a Full page retry cannot repeat as More pages, nor the reverse.
675 const slot = workspaceSlot(runDir, 'branch', tile.versionId, scope);
676 return record($, slot, async () => {
677 await recordRun($, slot, runBranchArgs(runDir, draftId(slot), tile.versionId, scope, pagesText));
678 ui.lv = null;
679 });
680}
681
682// ---- drawing ----
683async function probeBlit($, slot, source) {
684 if (blit.probed) return;
685 blit.probed = true;
686 const answer = await $.ui.blit({ requestId: PANE_ID, key: slot, source });
687 blit.lastAnswer = answer;
688 $.ui.log(`blit probe: ${JSON.stringify(answer)}`, { to: 'debug' });
689 if (blitSaysAlt(answer)) {
690 blit.altDrawn = true;
691 $.ui.invalidate('ui.render');
692 }
693}
694
695/**
696 * New thumbnail decodes one render may run. The JPEG and WebP decoders are pure JS on the hooks worker, which must
697 * answer the engine's heartbeat within 5 s or the engine unloads the mod (seen live 2026-10-02: one render decoding a
698 * page of references wedged the worker and the pane vanished). The rest show as loading and the next render takes them.
699 */
700const DECODES_PER_RENDER = 2;
701const decodes = { left: DECODES_PER_RENDER, deferred: false };
702
703/** The picture of one thumbnail (a design version or a reference) for a box `tileColumns` wide. */
704function pictureFor(surface, thumbSlot, size, useCells, tileColumns, maxRows) {
705 const thumb = thumbs.get(thumbSlot);
706 if (!thumb) return null;
707 if (thumb.state === 'loading') return { kind: 'loading' };
708 if (thumb.state === 'failed') return { kind: 'failed', reason: thumb.reason };
709 // A model sketch is vector text: the desktop draws it as it is; the terminal has no Svg element.
710 if (thumb.svg !== undefined) {
711 if (surface === 'terminal' || thumb.svg.length > SVG_MAX_CHARS) return { kind: 'text', text: 'A layout sketch. Sketch pictures show in the Claude app.' };
712 return { kind: 'svg', source: thumb.svg, ...desktopPictureSize(tileBox(tileColumns, size.width, size.height, maxRows), size.width, size.height) };
713 }
714 const kind = pictureKind(surface, { useCells });
715 if (kind !== 'svg' && !thumb.decoded) {
716 if (decodes.left <= 0) {
717 decodes.deferred = true;
718 return { kind: 'loading' };
719 }
720 decodes.left -= 1;
721 }
722 const box = tileBox(tileColumns, size.width, size.height, maxRows);
723 const cacheSlot = `${kind}:${box.columns}x${box.rows}`;
724 if (thumb.cache.has(cacheSlot)) return thumb.cache.get(cacheSlot);
725 let picture;
726 try {
727 if (kind === 'svg') {
728 const width = size.width || 480;
729 const height = size.height || 270;
730 const svg = svgPicture({ jpegBase64: thumb.jpeg, width, height, mimeType: thumb.mimeType }, () => decodedOf(thumb));
731 picture = { kind, source: svg.source, ...desktopPictureSize(box, width, height) };
732 } else if (kind === 'raster') {
733 picture = { kind, ...rasterCells(decodedOf(thumb), box.columns, box.rows) };
734 } else {
735 picture = { kind, source: imageSource(decodedOf(thumb), box), columns: box.columns, rows: box.rows };
736 }
737 } catch (error) {
738 picture = { kind: 'failed', reason: error && error.message ? error.message : String(error) };
739 }
740 thumb.cache.set(cacheSlot, picture);
741 return picture;
742}
743
744function decodedOf(thumb) {
745 if (!thumb.decoded) thumb.decoded = decodeThumb(thumb.jpeg, thumb.mimeType);
746 return thumb.decoded;
747}
748
749/** A reference's size: the corpus record, else the decoded picture's own once it is in. */
750function refSize(view, id) {
751 const thumb = thumbs.get(workspaceSlot(current, `ref:${id}`));
752 if (thumb && thumb.state === 'ready' && thumb.decoded) return { width: thumb.decoded.width, height: thumb.decoded.height };
753 return referenceSize(view, id);
754}
755
756/** The pane's handlers, each noting the press first, so the pane's own redraws wait for the pause after it (redraw.mjs). */
757function pressHandlers($, handlers) {
758 const noted = {};
759 for (const [name, handler] of Object.entries(handlers)) {
760 noted[name] = (...args) => {
761 void $.clock.now().then((now) => { redraw.lastPressAtMs = now; });
762 return handler(...args);
763 };
764 }
765 return noted;
766}
767
768/**
769 * What the pane draws for `surface` and its `props`, as a plain model (pane.mjs draws it). `pictureOf(thumbSlot, size,
770 * tileColumns, maxRows)` gives each picture: the render's real ones, or redrawIfChanged's facts without pixels.
771 */
772function paneModel(surface, props, pictureOf) {
773 const bodyColumns = props && typeof props.bodyColumns === 'number' ? props.bodyColumns : 80;
774 const maxRows = pictureMaxRows(props && props.scroll ? props.scroll.bodyRows : undefined);
775 const grid = tileGrid(bodyColumns);
776 const tileColumns = Math.max(8, grid.columns - 2);
777 const entry = current ? views.get(current) : null;
778 const view = entry ? entry.view : null;
779 let probe = null;
780 const budget = imageTreeBudget();
781 const remember = (slot, picture) => {
782 const admitted = budget.admit(picture);
783 if (admitted && admitted.kind === 'image' && !probe) probe = { slot: 'picture:' + slot, source: admitted.source };
784 return admitted;
785 };
786 const model = {
787 surface,
788 workspace: current,
789 emptyText: current ? LOADING : NO_WORKSPACE,
790 isLoading: !view,
791 prompt: ui.prompt,
792 tab: ui.tab,
793 noticeText,
794 errorText: actionError || pollError,
795 tileColumns,
796 items: [],
797 sections: [],
798 selectable: ui.tab !== 'designs',
799 sketches: ui.tab === 'sketches' ? { drawing: false, path: ui.sketchPath } : null,
800 lv: null,
801 tray: null,
802 selectedCount: 0,
803 emptyLine: '',
804 perRound: 6,
805 perRoundOptions: PER_ROUND,
806 };
807 if (!view) return { model, probe };
808 if (!ui.promptEdited) model.prompt = ui.prompt = briefLine(view);
809 const pause = pauseNow();
810 // What is picked: the waiting round's picks, else the selection the next round draws from.
811 const picks = pause ? pause.picks : selectionNow();
812 model.selectedCount = ui.tab !== 'designs' || pause ? picks.length : (view.pick ? 1 : 0);
813 if (pause) {
814 model.tray = { words: `${picks.length} picked · ${countdownLine(pause.countdown)}`, canContinue: picks.length > 0 };
815 }
816 if (ui.tab === 'designs') {
817 model.perRound = perRoundOf(view, ui.perRound);
818 if (ui.lv) {
819 const tile = largeTile();
820 if (tile) {
821 const lvColumns = Math.max(16, bodyColumns - 4);
822 const picture = tile.versionId ? pictureOf(workspaceSlot(current, tile.versionId), { width: tile.width, height: tile.height }, lvColumns, Math.max(maxRows, 30)) : null;
823 model.lv = { tile, picture: remember(`lv:${tile.candidateId}`, picture), mode: ui.lv.mode, scope: ui.lv.scope, pages: ui.lv.pages };
824 } else ui.lv = null;
825 }
826 const tiles = tilesOf(view).map((tile) => ({
827 ...tile,
828 kept: keptNow(tile.candidateId),
829 picture: tile.versionId ? remember(tile.candidateId, pictureOf(workspaceSlot(current, tile.versionId), { width: tile.width, height: tile.height }, tileColumns, maxRows)) : null,
830 }));
831 model.sections = designSections(view, tiles);
832 } else {
833 let ids;
834 let sizeOf = (id) => refSize(view, id);
835 if (ui.tab === 'sketches') {
836 ids = sketchesOf(view).map((sketch) => ({ id: sketch.id, title: sketchName(view, sketch.id), own: sketch.own }));
837 sizeOf = () => sketchSize(view);
838 model.sketches = { drawing: sketchesDrawing(view), path: ui.sketchPath };
839 model.emptyLine = SKETCHES_NONE;
840 } else {
841 ids = ui.tab === 'references' ? siteItems(view) : inspirationIds(view).map((id) => ({ id, title: '' }));
842 model.emptyLine = ui.tab === 'references' ? (pause ? 'Finding live sites.' : 'No website references yet.') : 'No inspiration yet.';
843 }
844 model.items = ids.map((item) => ({
845 ...item,
846 selected: picks.includes(item.id),
847 picture: remember(item.id, pictureOf(workspaceSlot(current, `ref:${item.id}`), sizeOf(item.id), tileColumns, maxRows)),
848 }));
849 }
850 return { model, probe };
851}
852
853export function register(on) {
854 on('tool.call', { tool: ['mcp__plugin_12ui-design_12ui-workspace__design_slate_create', 'mcp__plugin_12ui-design_12ui-workspace__design_slate_show'] }, async ($, e, next) => {
855 const result = await next(e);
856 const handle = handleFromCall(e, result);
857 if (handle) {
858 showWorkspace($, handle);
859 // The tool's result is the model's whatever the pane does: a pane that cannot open is logged, never thrown.
860 try {
861 await openPane($, false);
862 } catch (error) {
863 $.ui.log(`the Design workspace pane did not open: ${error && error.message ? error.message : String(error)}`, { to: 'debug' });
864 }
865 }
866 return result;
867 });
868
869 // Matched on every Pane, as design 3.7 spells the hook; only this mod's own pane is drawn here, and any other pane goes
870 // on down the chain untouched.
871 on('ui.render', { component: 'Pane' }, async ($, e, next) => {
872 if (e.requestId !== PANE_ID) return next(e);
873 if (paneWaits) {
874 // Drawn after waiting (the terminal widened): the band's Open goes away.
875 paneWaits = false;
876 $.ui.invalidate('ui.render');
877 }
878 const els = $.ui.resolve(e);
879 if (!poll.isOpen) {
880 poll.isOpen = true;
881 readSoon($);
882 }
883 const useCells = useCellsFor({ toggled: blit.toggled, altDrawn: blit.altDrawn });
884 decodes.left = DECODES_PER_RENDER;
885 decodes.deferred = false;
886 const { model, probe } = paneModel(e.surface, e.props, (thumbSlot, size, tileColumns, maxRows) => pictureFor(e.surface, thumbSlot, size, useCells, tileColumns, maxRows));
887 redraw.drawn = drawnSignature(model);
888 redraw.shows = current && views.has(current) ? current : null;
889 redraw.surface = e.surface;
890 redraw.props = e.props;
891 if (decodes.deferred) $.clock.after(50, () => { $.ui.invalidate('ui.render'); });
892 if (probe && !blit.probed) $.clock.after(250, () => { void probeBlit($, probe.slot, probe.source); });
893 model.handlers = pressHandlers($, {
894 promptInput: (value) => { ui.prompt = String(value ?? ''); ui.promptEdited = true; },
895 promptSubmit: (value) => { void searchPrompt($, value); },
896 tab: (name) => { ui.tab = name; ui.autoTab = false; ui.lv = null; fetchThumbs($, current); $.ui.invalidate('ui.render'); },
897 toggle: (id) => { togglePickOf($, id); },
898 continueRound: () => { void continueRound($); },
899 perRound: (n) => { void setPerRound($, n); },
900 open: (tile) => { ui.lv = { candidateId: tile.candidateId, mode: null, scope: null, pages: '' }; $.ui.invalidate('ui.render'); },
901 close: () => { ui.lv = null; $.ui.invalidate('ui.render'); },
902 edit: () => { if (ui.lv) { ui.lv.mode = ui.lv.mode === 'edit' ? null : 'edit'; ui.lv.scope = null; } $.ui.invalidate('ui.render'); },
903 editSubmit: (words) => { void editDesign($, words); },
904 branch: () => { if (ui.lv) { ui.lv.mode = ui.lv.mode === 'branch' ? null : 'branch'; ui.lv.scope = null; } $.ui.invalidate('ui.render'); },
905 branchScope: (scope) => {
906 if (scope === 'page') void branchDesign($, 'page', '');
907 else if (ui.lv) { ui.lv.scope = 'site'; $.ui.invalidate('ui.render'); }
908 },
909 branchPagesInput: (value) => { if (ui.lv) ui.lv.pages = String(value ?? ''); },
910 branchSubmit: (value) => { void branchDesign($, 'site', value ?? (ui.lv ? ui.lv.pages : '')); },
911 buildThis: () => { void buildThis($); },
912 retry: (tile) => { void retryOption($, tile); },
913 keep: (tile) => { toggleKeep($, tile); },
914 simplify: (level) => { void simplifyDesign($, level); },
915 groupMore: (group) => { void moreOfGroup($, group); },
916 sketchPathInput: (value) => { ui.sketchPath = String(value ?? ''); },
917 addSketch: (value) => { void addSketch($, value); },
918 removeSketch: (id) => { void removeSketch($, id); },
919 });
920 return paneTree(els, model);
921 });
922
923 // The band above the prompt, only while the pane waits undrawn: one line and Open. Every other time, and while the
924 // engine shows its own survey there, the band is the next plugin's.
925 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
926 if (!paneWaits || (e.props && e.props.hasSurvey)) return next(e);
927 return bandTree($.ui.resolve(e), () => { void openPane($, true); });
928 });
929}
930hooks/workspace/actions.mjs 174 lines1/**
2 * The arguments of the clicks the pane records: Build this (`design.slate.pick`, then `design.slate.handoff`), Edit,
3 * Simplify, Branch, Generate more (and a group's More), Keep, Retry and Continue (`design.slate.run`), and the
4 * inspiration selection with the person's own sketches (`design.slate.inspiration`). A new request carries a UUID v4
5 * minted when its dialog opened, so a repeated call never repeats work (the schema's rule); hold, continue and retry
6 * name the request that already exists (the waiting round's, the failed round's), whose own id they carry. Pure: no `$`.
7 *
8 * The limits are the server's schema (workers/api/src/slate/mcp/tools.json); a value over one is refused here with
9 * words the pane shows, rather than sent to be refused.
10 */
11
12import { UUID_V4 } from './bytes.mjs';
13
14/** The counts Generate more offers, and the one it starts on (SLATE_MORE_COUNTS). */
15export const MORE_COUNTS = Object.freeze([1, 2, 4, 6, 8, 12]);
16export const MORE_COUNT_INITIAL = 6;
17export const NOTE_MAX_CHARS = 600;
18export const EDIT_PROMPT_MAX_BYTES = 6000;
19/** The longest design prompt the server stores (the view contract's SLATE_BRIEF_MAX_CHARACTERS), in characters once whitespace collapses. */
20export const BRIEF_MAX_CHARS = 20000;
21
22/** A request the pane cannot send as it stands, with the words it shows: a plain Error named `ActionError`. */
23export function actionError(message) {
24 const error = new Error(message);
25 error.name = 'ActionError';
26 return error;
27}
28
29/** Whether an error is one `actionError` made. */
30export function isActionError(error) {
31 return Boolean(error) && error.name === 'ActionError';
32}
33
34function requireId(id) {
35 if (!UUID_V4.test(id)) throw actionError('The request id is not a UUID v4.');
36 return id;
37}
38
39function cleanText(text) {
40 // Control characters are stripped and the ends trimmed, as the servers measure user words.
41 return String(text ?? '').replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, '').trim();
42}
43
44function utf8Bytes(text) {
45 return new TextEncoder().encode(text).length;
46}
47
48/** `design.slate.pick`: record the selection of a version. */
49export function pickArgs(runDir, versionId) {
50 return { runDir, versionId };
51}
52
53/**
54 * `design.slate.handoff`: record Build this's Convert hand-off, as the Codex screen's does (remoteChoose): kind
55 * `convert`, output `html`, engine `local`. It puts a waiting request, with its command and an upload token, into
56 * `design.slate.data`; without it Claude has a pick but nothing to build from.
57 */
58export function convertHandoffArgs(runDir, handoffId, versionId) {
59 return { runDir, handoffId: requireId(handoffId), kind: 'convert', versionId, options: { engine: 'local', output: 'html' } };
60}
61
62/** The techniques of a mixed round (the server's SlateGroup); a group's More draws more of one. */
63export const GROUPS = Object.freeze(['sketch', 'inspiration', 'site']);
64
65/**
66 * `design.slate.run`: new options, `count` of MORE_COUNTS, an optional steer note, an optional `group` (a mixed round's
67 * More on one technique: a round of that group only, `count` the person's 6 or 12 of which the server deals the group's).
68 */
69export function runNewArgs(runDir, opId, { count = MORE_COUNT_INITIAL, note = '', group = null } = {}) {
70 const n = Number(count);
71 if (!MORE_COUNTS.includes(n)) throw actionError(`Choose ${MORE_COUNTS.join(', ')} options.`);
72 const words = cleanText(note);
73 if (words.length > NOTE_MAX_CHARS) throw actionError(`The note is longer than ${NOTE_MAX_CHARS} characters.`);
74 if (group !== null && !GROUPS.includes(group)) throw actionError('Choose a group of the round.');
75 const action = { kind: 'round', mode: 'new', count: n };
76 if (words) action.note = words;
77 if (group) action.group = group;
78 return { runDir, opId: requireId(opId), action };
79}
80
81/** `design.slate.run`: draw a failed option again, through the failed round's own request (`roundOpId`). */
82export function runRetryArgs(runDir, roundOpId, option) {
83 if (!option) throw actionError('Choose the option to draw again.');
84 return { runDir, opId: requireId(roundOpId), action: { kind: 'retry', option } };
85}
86
87/** `design.slate.run`: the person's Keep heart on an option; it waits for nobody, so it needs no agent. */
88export function runKeepArgs(runDir, opId, option, kept) {
89 return { runDir, opId: requireId(opId), action: { kind: 'keep', option, kept: Boolean(kept) } };
90}
91
92/** The levels of a Simplify (the hosted screen's two choices). */
93export const SIMPLIFY_LEVELS = Object.freeze(['standard', 'high']);
94
95/** `design.slate.run`: simplify one version, `standard` or `high` (which ranks every competing element before it picks). */
96export function runSimplifyArgs(runDir, opId, versionId, level = 'standard') {
97 if (!SIMPLIFY_LEVELS.includes(level)) throw actionError('Choose Standard or High.');
98 return { runDir, opId: requireId(opId), action: { kind: 'simplify', versionId, level } };
99}
100
101/** `design.slate.run`: more like one version (the server's default count). */
102export function runLikeArgs(runDir, opId, fromVersionId) {
103 return { runDir, opId: requireId(opId), action: { kind: 'round', mode: 'like', fromVersionId } };
104}
105
106/** `design.slate.run`: edit one version with an instruction in words (the pane has no drawing). */
107export function runEditArgs(runDir, opId, versionId, prompt) {
108 const words = cleanText(prompt);
109 if (!words) throw actionError('Say what to change.');
110 if (utf8Bytes(words) > EDIT_PROMPT_MAX_BYTES) throw actionError('The change is too long to send.');
111 return { runDir, opId: requireId(opId), action: { kind: 'edit', versionId, prompt: words } };
112}
113
114/** `design.slate.run`: start a round that waits on the person now. The op is the round's own (`pause.opId`). */
115export function continueArgs(runDir, roundOpId, { referenceIds = null, brief = '' } = {}) {
116 const action = { kind: 'continue' };
117 if (referenceIds) action.referenceIds = [...referenceIds];
118 const words = cleanText(brief).replace(/\s+/g, ' ');
119 // Every word the person wrote is sent, never cut: one over the server's ceiling is refused here with its count.
120 const count = Array.from(words).length;
121 if (count > BRIEF_MAX_CHARS) throw actionError(`The design prompt is ${count} characters; at most ${BRIEF_MAX_CHARS} fit. Shorten it by ${count - BRIEF_MAX_CHARS}.`);
122 if (words) action.brief = words;
123 return { runDir, opId: requireId(roundOpId), action };
124}
125
126/** `design.slate.run`: hold a waiting round's countdown while the person chooses (the screen holds on any touch). */
127export function holdArgs(runDir, roundOpId) {
128 return { runDir, opId: requireId(roundOpId), action: { kind: 'hold' } };
129}
130
131/** The most inspiration ids one selection holds (the server's schema): references, websites and sketches together. */
132export const SELECTION_MAX = 8;
133
134/** `design.slate.inspiration`: replace the whole selection; with `sketch` also add the person's own sketch, with `removeSketch` remove one. */
135export function inspirationArgs(runDir, referenceIds, { sketch = null, removeSketch = null } = {}) {
136 const args = { runDir, referenceIds: [...referenceIds].slice(0, SELECTION_MAX) };
137 if (sketch) args.sketch = { mimeType: sketch.mimeType, data: sketch.data };
138 if (removeSketch) args.removeSketch = removeSketch;
139 return args;
140}
141
142/** `design.slate.inspire`: search the reference collection with the prompt's words. */
143export function inspireArgs(runDir, query, count) {
144 const words = cleanText(query);
145 if (!words) throw actionError('Describe the design first.');
146 return { runDir, query: words, count };
147}
148
149/** The scopes of a branch (the screen's two choices): the design's full page, or more pages of the product. */
150export const BRANCH_SCOPES = Object.freeze(['page', 'site']);
151export const BRANCH_MAX_PAGES = 8;
152export const PAGE_NAME_MAX_CHARS = 60;
153
154/** Page names typed as one line: comma, semicolon or newline separated, each trimmed and cut, at most eight. */
155export function branchPages(text) {
156 return String(text ?? '')
157 .split(/[,\n;]/)
158 .map((name) => Array.from(cleanText(name).replace(/\s+/g, ' ')).slice(0, PAGE_NAME_MAX_CHARS).join(''))
159 .filter(Boolean)
160 .slice(0, BRANCH_MAX_PAGES);
161}
162
163/**
164 * `design.slate.run`: branch one design. `scope` `page` continues it below the fold into its full page; `site` adds the
165 * product's other pages, the person's names when given (`pages` only travels with `site`).
166 */
167export function runBranchArgs(runDir, opId, fromVersionId, scope, pagesText = '') {
168 if (!BRANCH_SCOPES.includes(scope)) throw actionError('Choose Full page or More pages.');
169 const action = { kind: 'round', mode: 'branch', fromVersionId, scope };
170 const pages = scope === 'site' ? branchPages(pagesText) : [];
171 if (pages.length > 0) action.pages = pages;
172 return { runDir, opId: requireId(opId), action };
173}
174hooks/workspace/bytes.mjs 82 lines1/**
2 * Bytes helpers for the Design workspace mod: base64 both ways and UUID v4 ids.
3 *
4 * Written by hand on purpose: the mod's environment has no Node `Buffer`, and CI runs these modules under Node 22.13,
5 * which has no `Uint8Array.prototype.toBase64` or `Uint8Array.fromBase64`. Pure: no `$`.
6 */
7
8const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
9const LOOKUP = (() => {
10 const table = new Int16Array(128).fill(-1);
11 for (let index = 0; index < ALPHABET.length; index += 1) table[ALPHABET.charCodeAt(index)] = index;
12 return table;
13})();
14
15/** Standard padded base64 of the bytes. */
16export function base64Encode(bytes) {
17 const parts = [];
18 const CHUNK = 3 * 4096;
19 for (let start = 0; start < bytes.length; start += CHUNK) {
20 const end = Math.min(bytes.length, start + CHUNK);
21 let out = '';
22 let index = start;
23 for (; index + 2 < end; index += 3) {
24 const n = (bytes[index] << 16) | (bytes[index + 1] << 8) | bytes[index + 2];
25 out += ALPHABET[(n >> 18) & 63] + ALPHABET[(n >> 12) & 63] + ALPHABET[(n >> 6) & 63] + ALPHABET[n & 63];
26 }
27 const rest = end - index;
28 if (rest === 1) {
29 const n = bytes[index] << 16;
30 out += ALPHABET[(n >> 18) & 63] + ALPHABET[(n >> 12) & 63] + '==';
31 } else if (rest === 2) {
32 const n = (bytes[index] << 16) | (bytes[index + 1] << 8);
33 out += ALPHABET[(n >> 18) & 63] + ALPHABET[(n >> 12) & 63] + ALPHABET[(n >> 6) & 63] + '=';
34 }
35 parts.push(out);
36 }
37 return parts.join('');
38}
39
40/** The bytes of standard base64 text; whitespace is ignored, anything else outside the alphabet throws. */
41export function base64Decode(text) {
42 const clean = String(text).replace(/[\t\n\r ]/g, '');
43 if (clean.length % 4 === 1) throw new Error('base64 text has a bad length');
44 const unpadded = clean.replace(/={1,2}$/, '');
45 const out = new Uint8Array(Math.floor((unpadded.length * 3) / 4));
46 let bits = 0;
47 let value = 0;
48 let at = 0;
49 for (let index = 0; index < unpadded.length; index += 1) {
50 const code = unpadded.charCodeAt(index);
51 const digit = code < 128 ? LOOKUP[code] : -1;
52 if (digit < 0) throw new Error('base64 text holds a character outside its alphabet');
53 value = (value << 6) | digit;
54 bits += 6;
55 if (bits >= 8) {
56 bits -= 8;
57 out[at] = (value >> bits) & 0xff;
58 at += 1;
59 }
60 }
61 return out;
62}
63
64/** Sixteen random bytes from the environment's `crypto.getRandomValues`. */
65export function randomBytes16() {
66 const bytes = new Uint8Array(16);
67 globalThis.crypto.getRandomValues(bytes);
68 return bytes;
69}
70
71/** A UUID v4 (the schema's pattern: lower-case hex, version 4, variant 8-b) from 16 bytes, random by default. */
72export function uuidV4(bytes = randomBytes16()) {
73 const b = Uint8Array.from(bytes.subarray(0, 16));
74 b[6] = (b[6] & 0x0f) | 0x40;
75 b[8] = (b[8] & 0x3f) | 0x80;
76 const hex = Array.from(b, (byte) => byte.toString(16).padStart(2, '0')).join('');
77 return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
78}
79
80/** The server's UUID v4 pattern for opId, handoffId and clientRequestId. */
81export const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
82hooks/workspace/copy.mjs 74 lines1/**
2 * The words the mod shows the person: the pane's labels, the toast and the band above the prompt. Sentence case,
3 * bare-verb buttons, no all-caps. Pure: no `$`.
4 */
5
6export const PANE_ID = 'design-workspace';
7export const PANE_TITLE = 'Design workspace';
8
9export const READY_TOAST = 'Design workspace ready. Press Open above the prompt to see it.';
10/** The band above the prompt while the pane waits for room, beside its Open button. */
11export const BAND_TEXT = 'Design workspace ready';
12export const NO_WORKSPACE = 'No Design workspace yet. Ask Claude to open one, for example: Open a Design workspace for my app idea.';
13export const LOADING = 'Loading the Design workspace.';
14export const BRANCH_PAGES_HINT = 'Pages (optional), e.g. about, sign in, settings';
15export const SENT = 'Recorded. Claude has been told.';
16export const RECORDED_RUNNER = 'Recorded. It will be drawn on this computer.';
17
18export const SKETCHES_CAPTION = 'Layout sketches for your brief. A selected sketch leads each group of the next round.';
19export const SKETCH_PATH_HINT = 'Path to your own sketch (JPEG, PNG or WebP)';
20export const SKETCHES_NONE = 'No sketches yet. Add your own, or draw a round.';
21export const SKETCHES_DRAWING = 'Drawing sketches…';
22export const SKETCH_GAP_AFTER = 'No sketches this round, so these were drawn without one.';
23export const SKETCH_GAP_AHEAD = 'No sketches this round, so these will be drawn without one.';
24/** A mixed round's groups, one per technique (the hosted screen's groupSketch words). */
25export const GROUP_NAMES = Object.freeze({ sketch: 'Sketch', inspiration: 'Sketch + inspiration', site: 'Sketch + site' });
26
27export const LABELS = Object.freeze({
28 design: 'Design',
29 sketches: 'Sketches',
30 add: 'Add',
31 remove: 'Remove',
32 keep: '♡ Keep',
33 kept: '♥ Kept',
34 retry: 'Retry',
35 simplify: 'Simplify',
36 standard: 'Standard',
37 high: 'High',
38 groupMore: '+ More',
39 selected: 'Selected',
40 chosen: 'Building',
41 back: 'Back',
42 branch: 'Branch',
43 fullPage: 'Full page',
44 morePages: 'More pages',
45 buildThis: 'Build this',
46 select: 'Select',
47 like: 'More like this',
48 edit: 'Edit',
49 send: 'Send',
50 cancel: 'Cancel',
51 more: 'Generate more',
52 continue: 'Continue',
53 cells: 'Show colour cells',
54 pictures: 'Show pictures',
55 count: 'Options',
56 note: 'Note',
57 pages: 'Pages',
58 change: 'Change',
59 explanation: 'Explanation',
60 open: 'Open',
61 format: 'Format',
62});
63
64/**
65 * An option picture's alt text. The terminal draws it in the picture's place, under the option's own label, where it
66 * cannot show pixels: there it says only what to do, never the label again. Elsewhere it is read in place of the
67 * picture, so it names the option.
68 */
69export const TERMINAL_PICTURE_ALT = 'Press v for colour cells';
70
71export function pictureAlt(label, surface) {
72 return surface === 'terminal' ? TERMINAL_PICTURE_ALT : `Option ${label}`;
73}
74hooks/workspace/gallery.mjs 148 lines1/**
2 * Slate v2's three tabs as plain data (no `$`): what Inspiration and References list, which picks a waiting round
3 * holds, and how many designs a round draws. Shapes follow `12ui.slate.view/3` as the slate v2 Worker projects it
4 * (workers/api/src/slate/view.ts): `inspiration.searches`, `references`, `sites`, `rounds[].referenceIds` and `pause`.
5 */
6
7import { SELECTION_MAX } from './actions.mjs';
8import { sketchesOf } from './sketches.mjs';
9import { shownVersionIds } from './view.mjs';
10
11/** The tabs in flow order, as the hosted screen's: Sketches, Inspiration, References, Designs. */
12export const TABS = Object.freeze(['sketches', 'inspiration', 'references', 'designs']);
13export const TAB_LABELS = Object.freeze({ sketches: 'Sketches', inspiration: 'Inspiration', references: 'References', designs: 'Designs' });
14/** Designs per round: 6 by default, 12 one tap away (the screen's switch). */
15export const PER_ROUND = Object.freeze([6, 12]);
16/** How many references one search asks for (the screen's first page). */
17export const SEARCH_COUNT = 12;
18
19/** The latest round that waits on the person, or null. */
20export function waitingRound(view) {
21 const rounds = (view && view.rounds ? view.rounds : []).filter((round) => round.pause);
22 return rounds.length ? rounds[rounds.length - 1] : null;
23}
24
25function unique(ids) {
26 return [...new Set(ids.filter((id) => typeof id === 'string' && id))];
27}
28
29/**
30 * Inspiration: the first page (SEARCH_COUNT) of the newest search's results, with any pick of the waiting round that page
31 * lacks put first. The server's own search behind a new workspace answers up to 96; every listed reference is fetched
32 * and decoded on the hooks worker, so the pane lists one page, as the screen's first page does.
33 */
34export function inspirationIds(view) {
35 const searches = (view.inspiration && view.inspiration.searches) || [];
36 const newest = (searches.length ? searches[searches.length - 1].referenceIds || [] : []).slice(0, SEARCH_COUNT);
37 const round = waitingRound(view);
38 const picks = round ? round.referenceIds || [] : [];
39 const missing = picks.filter((id) => !newest.includes(id));
40 return unique([...missing, ...newest]);
41}
42
43/** References: the live site screenshots, in the order they landed. */
44export function siteItems(view) {
45 return (view.sites || []).map((site) => ({ id: site.id, title: site.title || '', sourceUrl: site.sourceUrl || '' }));
46}
47
48/** A reference's picture size as the corpus recorded it (null when unknown: the picture's own size then decides). */
49export function referenceSize(view, id) {
50 const meta = view.references ? view.references[id] : null;
51 if (meta && meta.width && meta.height) return { width: meta.width, height: meta.height };
52 if (meta && meta.aspect === 'portrait') return { width: 3, height: 4 };
53 if (meta && meta.aspect === 'square') return { width: 1, height: 1 };
54 return { width: 16, height: 10 };
55}
56
57/**
58 * The selection the next round draws from while no round waits: the view's `inspiration.selected` (references,
59 * websites and sketches in click order, at most eight), or the person's own toggles not yet answered (`chosen`).
60 */
61export function selectedOf(view, chosen) {
62 if (chosen) return chosen;
63 const selected = view.inspiration && Array.isArray(view.inspiration.selected) ? view.inspiration.selected : [];
64 return [...selected];
65}
66
67/** The picks of the waiting round: the person's own once they changed them, else the round's preselection. */
68export function picksOf(view, chosen) {
69 if (chosen) return chosen;
70 const round = waitingRound(view);
71 return round ? [...(round.referenceIds || [])] : [];
72}
73
74/** At most this many picks: the round's own count of references. */
75export function pickLimit(view) {
76 const round = waitingRound(view);
77 return round && typeof round.count === 'number' && round.count > 0 ? round.count : 12;
78}
79
80/** Adds or removes one pick; past the limit nothing changes and `refused` says so. The order never changes. */
81export function togglePick(picks, id, limit = SELECTION_MAX) {
82 const at = picks.indexOf(id);
83 if (at >= 0) return { picks: picks.filter((pick) => pick !== id), refused: false };
84 if (picks.length >= limit) return { picks, refused: true };
85 return { picks: [...picks, id], refused: false };
86}
87
88export function sameList(a, b) {
89 return a.length === b.length && a.every((id, index) => b[index] === id);
90}
91
92/** The switch's place: 12 once the newest round drew twelve or more, else 6 (or what the person tapped). */
93export function perRoundOf(view, tapped) {
94 if (tapped) return tapped;
95 const rounds = view.rounds || [];
96 const newest = rounds.length ? rounds[rounds.length - 1] : null;
97 return newest && typeof newest.count === 'number' && newest.count >= 12 ? 12 : 6;
98}
99
100/**
101 * The tab the pane opens a workspace on: Inspiration while a round waits for the person's picks (the tray with its Continue
102 * is there then); otherwise Designs once the workspace has options to show; Inspiration when it has none yet.
103 */
104export function openingTab(view, roundWaits) {
105 if (roundWaits) return 'inspiration';
106 return view.candidates.length > 0 ? 'designs' : 'inspiration';
107}
108
109/**
110 * The thumbnails a tab shows, each with the slot it is kept under (the version id, or `ref:` and the reference id) and
111 * which picture tool reads it. Only the shown tab's decide a drawing (redraw.mjs `drawnSignature`).
112 */
113export function tabThumbs(view, tab) {
114 if (tab === 'designs') {
115 return shownVersionIds(view).map((versionId) => ({ slot: versionId, kind: 'version', args: { versionId } }));
116 }
117 const ids = tab === 'sketches' ? sketchesOf(view).map((sketch) => sketch.id)
118 : tab === 'references' ? siteItems(view).map((site) => site.id) : inspirationIds(view);
119 return ids.map((id) => ({ slot: `ref:${id}`, kind: 'reference', args: { referenceId: id } }));
120}
121
122/**
123 * Every thumbnail the pane reads for a view: the shown tab's first, then the other tabs', each slot once (a pick that is
124 * also a website is one picture). The other tabs' pictures land without a redraw, since only the shown tab is drawn, so
125 * a tab's first visit draws them in the press's own drawing. Read for the shown tab only, each first visit drew its
126 * tab once or twice more 1 to 2 s after the press, where the next press landed (gate press rig, a press every 2 s: 1 of
127 * 14 presses refused that way in out-drawn400p2000 and in out-drawn400p2000c; every 3 s, 1 of 9 in out-drawn400p3000a).
128 */
129export function viewThumbs(view, shownTab) {
130 const seen = new Set();
131 const wants = [];
132 for (const tab of [shownTab, ...TABS.filter((name) => name !== shownTab)]) {
133 for (const want of tabThumbs(view, tab)) {
134 if (seen.has(want.slot)) continue;
135 seen.add(want.slot);
136 wants.push(want);
137 }
138 }
139 return wants;
140}
141
142/** Whether tapping 12 draws a round of twelve now: the newest round drew fewer and no round runs. */
143export function twelveDraws(view, roundRuns) {
144 const rounds = view.rounds || [];
145 const newest = rounds.length ? rounds[rounds.length - 1] : null;
146 return Boolean(newest) && !roundRuns && (typeof newest.count !== 'number' || newest.count < 12);
147}
148hooks/workspace/handles.mjs 47 lines1/**
2 * Workspace handles (`runDir`, "w_" and 22 base62 characters): reading them from the results of the plugin's own create
3 * and show tools. Pure: no `$`.
4 */
5
6/** The plugin's two model-facing tools whose results name a workspace (exact names as Claude Code lists them). */
7export const CREATE_TOOL = 'mcp__plugin_12ui-design_12ui-workspace__design_slate_create';
8export const SHOW_TOOL = 'mcp__plugin_12ui-design_12ui-workspace__design_slate_show';
9
10const HANDLE = /^w_[0-9A-Za-z]{22}$/;
11const HANDLE_IN_TEXT = /\bw_[0-9A-Za-z]{22}\b/;
12
13/** Whether the text is exactly one workspace handle. */
14export function isHandle(text) {
15 return typeof text === 'string' && HANDLE.test(text);
16}
17
18function handleInText(text) {
19 if (typeof text !== 'string' || !text) return null;
20 try {
21 const parsed = JSON.parse(text);
22 if (parsed && typeof parsed === 'object' && isHandle(parsed.runDir)) return parsed.runDir;
23 } catch {
24 // Not JSON: the text the model reads may be plain words; the pattern below reads those.
25 }
26 const match = HANDLE_IN_TEXT.exec(text);
27 return match ? match[0] : null;
28}
29
30function stringify(value) {
31 try {
32 return value === undefined ? '' : JSON.stringify(value);
33 } catch {
34 return '';
35 }
36}
37
38/**
39 * The workspace a create or show call names: the show input's `runDir`, else the first handle in the result as the
40 * model reads it (`text`), else in the result record. Null when the call names none (an error result, a deny).
41 */
42export function handleFromCall(input, result) {
43 if (input && input.tool === SHOW_TOOL && isHandle(input.runDir)) return input.runDir;
44 if (!result || result.deny || result.isError) return null;
45 return handleInText(result.text) ?? handleInText(stringify(result.result));
46}
47hooks/workspace/messages.mjs 57 lines1/**
2 * What the pane tells Claude after a click is recorded, and when it says nothing: the port of the hosted screen's
3 * messages (packages/12ui/src/mcp-slate-ui-script-remote.ts). Pure: no `$`, no clock.
4 *
5 * Eight messages, one per click that waits for the agent: new options (or more of one group), more like an option, an edit,
6 * a simplify, a retry, a branch, and Build this (the selection). Keep and the sketch and selection writes wait for nobody. `$.prompt.submit`
7 * sends them framed as from this mod, so "I" of the screen becomes "The user". Each names what happened and how to
8 * confirm it (`design.slate.data`, whose answer is the server's own trusted text) and carries no command, flag, path,
9 * price or credit word; the user's own words (a note, an edit instruction, branch page names) are never put in a
10 * message: the agent reads them from the data tool, quoted.
11 *
12 * The runner rule: when the run result says the workspace runner on the user's computer holds the workspace
13 * (`runner.alive`), the runner claims the request within seconds and nobody is told. The agent is told after all, with
14 * the same message, when the request is still the agent's once RUNNER_GRACE_MS has passed; while the runner draws it,
15 * or while its round waits on the user, the pane keeps checking every RUNNER_RECHECK_MS.
16 */
17
18export const DATA_TOOL = 'design.slate.data';
19export const RUNNER_GRACE_MS = 20000;
20export const RUNNER_RECHECK_MS = 10000;
21
22/** The message for a recorded Generate more, More like this, Edit, Simplify, Retry or Branch request. */
23export function runMessage(runDir, opId, action, labelOf) {
24 let head;
25 if (action.kind === 'retry') head = `The user asked to draw ${action.option ? `option ${action.option}` : 'a failed option'} again`;
26 else if (action.kind === 'simplify') head = `The user asked to simplify ${labelOf(action.versionId) ?? 'an option'}`;
27 else if (action.kind === 'edit') head = `The user asked to edit ${labelOf(action.versionId) ?? 'an option'}`;
28 else if (action.mode === 'branch') head = `The user asked for ${action.scope === 'page' ? 'the full page' : 'more pages'} of ${labelOf(action.fromVersionId) ?? 'a design'}`;
29 else if (action.mode === 'like') head = `The user asked for more like ${labelOf(action.fromVersionId) ?? 'an option'}`;
30 else if (action.group) head = 'The user asked for more options of one group';
31 else head = 'The user asked for new options';
32 return `${head} in the Design workspace (request ${opId}, runDir ${runDir}). Please confirm it with ${DATA_TOOL}, then carry it out.`;
33}
34
35/** The message for a recorded Build this: the pick is recorded, and Claude is told to build that design. */
36export function buildMessage(runDir, label) {
37 return `The user chose design ${label} to build in the Design workspace (runDir ${runDir}). Please read its selection with ${DATA_TOOL}, then build that design as the user's request asks.`;
38}
39
40/** After a run is recorded: tell the agent now, or watch while the runner has it (returns the first wait). */
41export function afterRun(runner) {
42 return runner && runner.alive === true ? { tell: false, waitMs: RUNNER_GRACE_MS } : { tell: true };
43}
44
45/**
46 * One runner check, on a fresh view: `{ tell: true }` sends the message now; `{ waitMs }` checks again after that
47 * long; `{ drop: true }` forgets the request (it finished, failed or went away). `watch.waited` records that the round
48 * waited on the user, after which the runner gets its grace again; the caller keeps the returned `waited`.
49 */
50export function judgeRunner(op, waitsOnPerson, watch) {
51 if (!op || !(op.state === 'running' || op.state === 'starting')) return { drop: true };
52 if (op.phase === 'drawing') return { waitMs: RUNNER_RECHECK_MS, waited: watch.waited };
53 if (waitsOnPerson) return { waitMs: RUNNER_RECHECK_MS, waited: true };
54 if (watch.waited) return { waitMs: RUNNER_GRACE_MS, waited: false };
55 return { tell: true };
56}
57hooks/workspace/pane.mjs 307 lines1/**
2 * The Design workspace pane's element tree (slate v2), built from the surface's own element table (what
3 * `$.ui.resolve(e)` returned) and a plain model of what to show. No `$` here: every handler is a closure register.mjs
4 * passes in.
5 *
6 * Top to bottom, as the hosted screen lays it out: one prompt line (its Design button inside the same row), the tabs
7 * Sketches · Inspiration · References · Designs with a quiet "N selected" at the right, the notice and error lines,
8 * then the active tab. Sketches, Inspiration and References are a wrapped gallery of picture tiles; a selected tile
9 * carries a ring and a check, and Sketches adds the person's own sketch from a typed path and removes it. The tray
10 * under the gallery holds the round's words and Continue. Designs holds the 6 · 12 switch and a section for each
11 * round (a mixed round's groups each with its More) of design tiles (Keep, and Retry on a failed one); pressing a
12 * tile opens the large view with Edit (and Simplify) · Branch · Build this, and Keep.
13 */
14
15import { BAND_TEXT, BRANCH_PAGES_HINT, LABELS, LOADING, SKETCHES_CAPTION, SKETCHES_DRAWING, SKETCH_PATH_HINT, pictureAlt } from './copy.mjs';
16import { TABS, TAB_LABELS } from './gallery.mjs';
17import { BUTTON_GAP, TILE_GAP, briefReserve } from './layout.mjs';
18import { stateLine } from './view.mjs';
19
20const RING = 'cyan';
21/** Columns between two tab labels. */
22const TAB_GAP = 3;
23
24/** The engine accepts `plain` only as true or absent (a Button with `plain: false` is skipped), so a quiet button spreads this. */
25function quiet(isQuiet) {
26 return isQuiet ? { plain: true } : {};
27}
28
29function text(els, words, props = {}) {
30 return els.Text({ ...props, children: words });
31}
32
33function pictureNode(els, name, picture, alt) {
34 if (!picture) return text(els, ' ', { dimColor: true });
35 if (picture.kind === 'image') return els.Image({ key: `picture:${name}`, source: picture.source, columns: picture.columns, rows: picture.rows, alt });
36 if (picture.kind === 'raster') return els.Raster({ key: `cells:${name}`, cells: picture.cells, columns: picture.columns, rows: picture.rows });
37 if (picture.kind === 'svg') return els.Svg({ source: picture.source, alt, width: picture.width, height: picture.height });
38 if (picture.kind === 'text') return text(els, picture.text, { dimColor: true, wrap: 'wrap' });
39 if (picture.kind === 'loading') return text(els, 'Loading picture', { dimColor: true });
40 if (picture.kind === 'failed') return text(els, `No picture: ${picture.reason}`, { dimColor: true, wrap: 'wrap' });
41 return null;
42}
43
44function row(els, key, children, gap = BUTTON_GAP) {
45 return els.Box({ key, flexDirection: 'row', flexWrap: 'wrap', columnGap: gap, children: children.filter(Boolean) });
46}
47
48function promptNode(els, model) {
49 const { handlers, prompt } = model;
50 const children = [];
51 if (els.Input) {
52 // No label: the engine draws any given label, even an empty one, as "<label>: " before the value.
53 children.push(els.Input({
54 key: 'prompt',
55 placeholder: 'Describe the design',
56 value: prompt,
57 submitLabel: LABELS.design.toLowerCase(),
58 onInput: (value) => handlers.promptInput(value),
59 onSubmit: (value) => handlers.promptSubmit(value),
60 }));
61 } else children.push(text(els, prompt, { bold: true, wrap: 'wrap' }));
62 children.push(els.Button({ key: 'design', label: LABELS.design, variant: 'primary', onPress: () => handlers.promptSubmit(prompt) }));
63 return els.Box({ key: 'prompt-row', flexDirection: 'row', columnGap: BUTTON_GAP, paddingRight: briefReserve(model.surface), children });
64}
65
66function tabsNode(els, model) {
67 const tabs = TABS.map((name) => els.Button({
68 key: `tab:${name}`,
69 label: TAB_LABELS[name],
70 plain: true,
71 dimColor: model.tab !== name,
72 onPress: () => model.handlers.tab(name),
73 }));
74 const right = model.selectedCount > 0 ? text(els, `${model.selectedCount} selected`, { dimColor: true }) : null;
75 // The active tab is underlined: a rule under its label, as the screen's slim tab row has it.
76 let offset = 0;
77 for (const name of TABS) {
78 if (name === model.tab) break;
79 offset += TAB_LABELS[name].length + TAB_GAP;
80 }
81 const rule = `${' '.repeat(offset)}${'─'.repeat(TAB_LABELS[model.tab].length)}`;
82 return els.Box({
83 key: 'tabs',
84 flexDirection: 'column',
85 marginTop: 1,
86 children: [
87 els.Box({ key: 'tab-line', flexDirection: 'row', justifyContent: 'space-between', children: [row(els, 'tab-row', tabs, TAB_GAP), right].filter(Boolean) }),
88 text(els, rule, { color: RING }),
89 ],
90 });
91}
92
93/**
94 * One gallery tile: its picture inside a ring when selected, then the one-tap toggle (a pick of the waiting round, or,
95 * with none waiting, of the selection the next round draws from) and, on an own sketch, its Remove.
96 */
97function galleryTile(els, item, model) {
98 const children = [pictureNode(els, item.id, item.picture, item.title || 'Reference')];
99 if (item.title) children.push(text(els, item.title, { dimColor: true, wrap: 'truncate-end' }));
100 const mark = item.selected ? `✓ ${LABELS.selected}` : LABELS.select;
101 const buttons = [els.Button({ key: `pick:${item.id}`, label: mark, ...quiet(!item.selected), dimColor: !item.selected, onPress: () => model.handlers.toggle(item.id) })];
102 if (item.own) buttons.push(els.Button({ key: `remove:${item.id}`, label: LABELS.remove, plain: true, dimColor: true, onPress: () => model.handlers.removeSketch(item.id) }));
103 children.push(row(els, `under:${item.id}`, buttons));
104 return els.Box({
105 key: `item:${item.id}`,
106 flexDirection: 'column',
107 width: model.tileColumns + 2,
108 borderStyle: 'round',
109 borderColor: item.selected ? RING : undefined,
110 borderDimColor: !item.selected,
111 marginBottom: 1,
112 children,
113 });
114}
115
116function trayNode(els, model) {
117 if (!model.tray) return null;
118 const { words, canContinue } = model.tray;
119 return row(els, 'tray', [
120 text(els, words, { wrap: 'wrap' }),
121 canContinue ? els.Button({ key: 'continue', label: LABELS.continue, variant: 'primary', onPress: () => model.handlers.continueRound() }) : null,
122 ], 2);
123}
124
125/** The Sketches tab's head: its caption, the line for a running sketch call, and the typed path of an own sketch. */
126function sketchesHead(els, model) {
127 const { sketches, handlers } = model;
128 const parts = [text(els, SKETCHES_CAPTION, { dimColor: true, wrap: 'wrap' })];
129 if (sketches.drawing) parts.push(text(els, SKETCHES_DRAWING, { dimColor: true }));
130 if (els.Input) {
131 parts.push(row(els, 'sketch-add', [
132 els.Input({
133 key: 'sketch-path',
134 placeholder: SKETCH_PATH_HINT,
135 value: sketches.path,
136 submitLabel: LABELS.add.toLowerCase(),
137 onInput: (value) => handlers.sketchPathInput(value),
138 onSubmit: (value) => handlers.addSketch(value),
139 }),
140 els.Button({ key: 'sketch-add-button', label: LABELS.add, variant: 'primary', onPress: () => handlers.addSketch() }),
141 ], 2));
142 }
143 return parts;
144}
145
146function galleryNode(els, model) {
147 const parts = [model.sketches ? els.Box({ key: 'sketches-head', flexDirection: 'column', children: sketchesHead(els, model) }) : null, trayNode(els, model)];
148 if (model.items.length === 0) parts.push(text(els, model.emptyLine, { dimColor: true, wrap: 'wrap' }));
149 else parts.push(els.Box({ key: 'gallery', flexDirection: 'row', flexWrap: 'wrap', columnGap: TILE_GAP, children: model.items.map((item) => galleryTile(els, item, model)) }));
150 return parts.filter(Boolean);
151}
152
153/** The Keep heart of a mixed round's design with a picture (the hosted screen offers it nowhere else). */
154function keepButton(els, tile, handlers, key) {
155 if (!tile.group || !tile.versionId) return null;
156 return els.Button({ key, label: tile.kept ? LABELS.kept : LABELS.keep, ...quiet(!tile.kept), dimColor: !tile.kept, onPress: () => handlers.keep(tile) });
157}
158
159function designTile(els, tile, model) {
160 const children = [
161 pictureNode(els, tile.candidateId, tile.picture, pictureAlt(tile.label, model.surface)),
162 row(els, `under:${tile.candidateId}`, [
163 els.Button({ key: `open:${tile.candidateId}`, label: tile.label, plain: true, onPress: () => model.handlers.open(tile) }),
164 tile.isReady && !tile.isSelected ? null : text(els, tile.isSelected ? LABELS.chosen : stateLine(tile), tile.state === 'failed' ? { color: 'red', wrap: 'wrap' } : { dimColor: true, wrap: 'wrap' }),
165 keepButton(els, tile, model.handlers, `keep:${tile.candidateId}`),
166 tile.retryOpId ? els.Button({ key: `retry:${tile.candidateId}`, label: LABELS.retry, variant: 'primary', onPress: () => model.handlers.retry(tile) }) : null,
167 ]),
168 ];
169 return els.Box({
170 key: `design:${tile.candidateId}`,
171 flexDirection: 'column',
172 width: model.tileColumns + 2,
173 borderStyle: 'round',
174 borderColor: tile.isSelected ? RING : undefined,
175 borderDimColor: !tile.isSelected,
176 marginBottom: 1,
177 children,
178 });
179}
180
181function designsNode(els, model) {
182 const switchRow = row(els, 'per-round', [
183 text(els, 'Per round', { dimColor: true }),
184 ...model.perRoundOptions.map((n) => els.Button({ key: `per:${n}`, label: String(n), ...quiet(model.perRound !== n), dimColor: model.perRound !== n, variant: model.perRound === n ? 'primary' : undefined, onPress: () => model.handlers.perRound(n) })),
185 ]);
186 const parts = [trayNode(els, model), switchRow];
187 if (model.sections.length === 0) parts.push(text(els, 'No designs yet.', { dimColor: true }));
188 else for (const section of model.sections) parts.push(sectionNode(els, section, model));
189 return parts.filter(Boolean);
190}
191
192/** One round: its heading, then each group (a mixed round's technique with its More) over its design tiles. */
193function sectionNode(els, section, model) {
194 const children = [text(els, section.title, { bold: true })];
195 for (const group of section.groups) {
196 if (group.name) {
197 children.push(row(els, `group-head:${group.key}`, [
198 text(els, group.name, { dimColor: true }),
199 group.gap ? text(els, group.gap, { dimColor: true, wrap: 'wrap' }) : null,
200 group.more ? els.Button({ key: `more:${group.key}`, label: LABELS.groupMore, plain: true, onPress: () => model.handlers.groupMore(group.group) }) : null,
201 ], 2));
202 }
203 children.push(els.Box({ key: `designs:${group.key}`, flexDirection: 'row', flexWrap: 'wrap', columnGap: TILE_GAP, children: group.tiles.map((tile) => designTile(els, tile, model)) }));
204 }
205 return els.Box({ key: `section:${section.key}`, flexDirection: 'column', marginTop: 1, children });
206}
207
208/** The large view of one design: the picture at the pane's width, then Edit · Branch · Build this. */
209function largeViewNode(els, model) {
210 const { lv, handlers } = model;
211 const { tile } = lv;
212 const actions = [els.Button({ key: 'lv-back', label: LABELS.back, plain: true, dimColor: true, onPress: () => handlers.close() })];
213 if (tile.isReady) {
214 if (els.Input) actions.push(els.Button({ key: 'lv-edit', label: LABELS.edit, ...quiet(lv.mode !== 'edit'), onPress: () => handlers.edit() }));
215 // Once the design is building, Branch is no longer offered next to "Building".
216 if (!tile.isSelected) actions.push(els.Button({ key: 'lv-branch', label: LABELS.branch, ...quiet(lv.mode !== 'branch'), onPress: () => handlers.branch() }));
217 actions.push(keepButton(els, tile, handlers, 'lv-keep'));
218 actions.push(tile.isSelected ? text(els, LABELS.chosen, { color: RING }) : els.Button({ key: 'lv-build-this', label: LABELS.buildThis, variant: 'primary', onPress: () => handlers.buildThis() }));
219 }
220 const children = [
221 row(els, 'lv-head', [text(els, `Design ${tile.label}`, { bold: true }), tile.isReady ? null : text(els, stateLine(tile), { dimColor: true })], 2),
222 pictureNode(els, `lv:${tile.candidateId}`, lv.picture, pictureAlt(tile.label, model.surface)),
223 row(els, 'lv-actions', actions, 2),
224 ];
225 if (lv.mode === 'edit' && els.Input) {
226 children.push(els.Input({
227 key: `lv-edit-note:${tile.candidateId}`,
228 label: LABELS.change,
229 placeholder: `What to change in ${tile.label}`,
230 submitLabel: 'send',
231 autoFocus: true,
232 onSubmit: (value) => handlers.editSubmit(value),
233 }));
234 // Simplify, the edit bar's quick tool: removes up to two elements of the design that add nothing, as one new version.
235 if (tile.editable) {
236 children.push(row(els, 'lv-simplify', [
237 text(els, LABELS.simplify, { dimColor: true }),
238 els.Button({ key: 'lv-simplify-standard', label: LABELS.standard, onPress: () => handlers.simplify('standard') }),
239 els.Button({ key: 'lv-simplify-high', label: LABELS.high, onPress: () => handlers.simplify('high') }),
240 ], 2));
241 }
242 }
243 if (lv.mode === 'branch') children.push(...branchNodes(els, model));
244 return children;
245}
246
247/**
248 * The branch bar, as the screen's: Full page (the design continued below the fold) or More pages (other pages of the
249 * product, names optional). Full page branches at once; More pages opens the names line, then Send.
250 */
251function branchNodes(els, model) {
252 const { lv, handlers } = model;
253 const choices = [
254 els.Button({ key: 'lv-scope-page', label: LABELS.fullPage, onPress: () => handlers.branchScope('page') }),
255 els.Button({ key: 'lv-scope-site', label: LABELS.morePages, ...quiet(lv.scope !== 'site'), onPress: () => handlers.branchScope('site') }),
256 ];
257 const nodes = [row(els, 'lv-branch-scope', choices, 2)];
258 if (lv.scope === 'site') {
259 const line = [];
260 if (els.Input) {
261 line.push(els.Input({
262 key: `lv-branch-pages:${lv.tile.candidateId}`,
263 label: LABELS.pages,
264 placeholder: BRANCH_PAGES_HINT,
265 value: lv.pages,
266 submitLabel: 'send',
267 autoFocus: true,
268 onInput: (value) => handlers.branchPagesInput(value),
269 onSubmit: (value) => handlers.branchSubmit(value),
270 }));
271 }
272 line.push(els.Button({ key: 'lv-branch-send', label: LABELS.send, variant: 'primary', onPress: () => handlers.branchSubmit(lv.pages) }));
273 nodes.push(row(els, 'lv-branch-pages', line, 2));
274 }
275 return nodes;
276}
277
278/** The whole pane. `model` is built by register.mjs; see the fields read above. */
279export function paneTree(els, model) {
280 if (!model.workspace) {
281 const children = [text(els, model.emptyText, { wrap: 'wrap' })];
282 if (model.errorText) children.push(text(els, model.errorText, { color: 'red', wrap: 'wrap' }));
283 return els.Box({ flexDirection: 'column', children });
284 }
285 const children = [promptNode(els, model)];
286 if (model.isLoading) {
287 if (model.errorText) children.push(text(els, model.errorText, { color: 'red', wrap: 'wrap' }));
288 else children.push(text(els, LOADING, { dimColor: true }));
289 return els.Box({ flexDirection: 'column', children });
290 }
291 children.push(tabsNode(els, model));
292 if (model.noticeText) children.push(text(els, model.noticeText, { dimColor: true, wrap: 'wrap' }));
293 if (model.errorText) children.push(text(els, model.errorText, { color: 'red', wrap: 'wrap' }));
294 if (model.lv) children.push(...largeViewNode(els, model));
295 else if (model.tab === 'designs') children.push(...designsNode(els, model));
296 else children.push(...galleryNode(els, model));
297 return els.Box({ flexDirection: 'column', rowGap: 0, children: children.filter(Boolean) });
298}
299
300/** The band above the prompt while the pane waits undrawn for room: one dim line and Open, which seats the pane. */
301export function bandTree(els, onOpen) {
302 return row(els, 'design-workspace-band', [
303 text(els, BAND_TEXT, { key: 'ready', dimColor: true }),
304 els.Button({ key: 'open', label: LABELS.open, variant: 'primary', onPress: onOpen }),
305 ]);
306}
307hooks/workspace/layout.mjs 58 lines1/**
2 * The pane's grid policy: how many option tiles sit side by side, how wide each one is, how tall a picture may grow, and
3 * the columns the brief line leaves for the terminal's close mark. Every sizing rule of the pane's layout lives here and
4 * nowhere else (CLAUDE.md item 9); picture.mjs sizes the picture inside the tile this module returns. Pure: no `$`.
5 *
6 * The facts it works from are the surface's own: `bodyColumns` and `scroll.bodyRows` of the Pane props, and the width
7 * the terminal draws a Button in (`[ label ]`, 2.1.287 d.ts `ButtonProps`: the label plus four columns).
8 */
9
10import { LABELS } from './copy.mjs';
11
12/** Columns between two tiles in a row. */
13export const TILE_GAP = 2;
14/** Columns between two buttons in a tile's button row (pane.mjs draws the row with this gap). */
15export const BUTTON_GAP = 1;
16/** The rows a tile draws besides its picture: the label, the state line, the button row, and the gap below it. */
17export const TILE_CHROME_ROWS = 4;
18/**
19 * The columns the terminal's close mark takes from the pane's first row: the mark in the last column, and one column of
20 * space before it, so a truncated brief ends in its ellipsis and never runs into the mark.
21 */
22export const CLOSE_MARK_COLUMNS = 2;
23
24/** The columns a terminal Button takes: `[ label ]`. */
25export function buttonColumns(label) {
26 return label.length + 4;
27}
28
29/** The narrowest tile whose button row (Select, More like this, Edit) fits on one line: 38 columns with today's labels. */
30export const TILE_MIN_COLUMNS = [LABELS.select, LABELS.like, LABELS.edit].map(buttonColumns).reduce((sum, n) => sum + n, 0)
31 + BUTTON_GAP * 2;
32
33/**
34 * The tile grid for a pane `bodyColumns` wide: `{ perRow, columns }`. As many tiles a row as fit at TILE_MIN_COLUMNS
35 * (one at least), each as wide as the row then allows. A pane narrower than one minimum tile gets one tile of the
36 * whole width (its button row wraps there; nothing narrower can hold it).
37 */
38export function tileGrid(bodyColumns) {
39 const width = Math.max(1, Math.floor(bodyColumns));
40 const perRow = Math.max(1, Math.floor((width + TILE_GAP) / (TILE_MIN_COLUMNS + TILE_GAP)));
41 const columns = Math.floor((width - TILE_GAP * (perRow - 1)) / perRow);
42 return { perRow, columns };
43}
44
45/**
46 * The tallest a picture may be in a pane whose window shows `bodyRows` rows: one whole tile (picture and chrome) fits
47 * the window, so no picture is taller than what the person can see at once. Without a window height, no limit here.
48 */
49export function pictureMaxRows(bodyRows) {
50 if (typeof bodyRows !== 'number' || !Number.isFinite(bodyRows)) return Infinity;
51 return Math.max(3, Math.floor(bodyRows) - TILE_CHROME_ROWS);
52}
53
54/** The columns the pane's first row leaves at its right edge: the close mark's on the terminal, none elsewhere. */
55export function briefReserve(surface) {
56 return surface === 'terminal' ? CLOSE_MARK_COLUMNS : 0;
57}
58hooks/workspace/picture.mjs 233 lines1/**
2 * The picture policy: how an option's thumbnail (the server's 480 px JPEG) is drawn on each surface. Every rendering
3 * rule for the pictures lives here and nowhere else (CLAUDE.md item 9). Pure: no `$`; register.mjs feeds it facts
4 * (the surface, the `$.ui.blit` answer, the person's `v` toggle) and pane.mjs draws what it returns.
5 *
6 * Terminal. The `Image` element takes PNG or RGBA only, so the JPEG is decoded (the vendored jpeg-js decoder) to RGBA.
7 * It shows real pixels on terminals with a graphics protocol (kitty, Ghostty) and its `alt` text elsewhere. The fact
8 * that tells the two apart is the engine's own: `$.ui.blit` on a keyed Image resolves `{ deny }` with a reason naming
9 * the alt when that Image draws its alt (2.1.287 d.ts `UiBlitResult`). On that fact the pane draws `Raster` cells
10 * instead: half blocks (U+2580), the top pixel as the foreground and the bottom one as the background, two pixels a
11 * cell. `v` toggles either way. Which default stands, and the exact deny words, are recorded in mod/NOTES.md (spike 1).
12 *
13 * Desktop and the other remote surfaces. `Svg` (at most 131,072 characters) with the JPEG embedded as a data URI when
14 * the whole document fits; otherwise the picture is decoded, scaled down and re-encoded as a stored PNG until it fits.
15 */
16
17import { base64Decode, base64Encode } from './bytes.mjs';
18import { decode as decodeJpeg } from './jpeg-decoder.mjs';
19import { encodePng, storedPngBytes } from './png.mjs';
20import { decodeWebp } from './webp-decoder.mjs';
21
22/** The Svg element's character ceiling (2.1.287 d.ts `SvgProps.source`). */
23export const SVG_MAX_CHARS = 131072;
24/** The XML namespace an SVG document names itself with; an identifier, never fetched. */
25export const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
26/** The half-block glyph a Raster cell draws: upper half in the foreground, lower half in the background. */
27export const HALF_BLOCK = 0x2580;
28/** Raster's own bounds (2.1.287 d.ts `RasterProps`), and Image's. */
29export const RASTER_MAX_COLUMNS = 512;
30export const RASTER_MAX_ROWS = 256;
31export const IMAGE_MAX_CELLS = 255;
32/** RGBA handed to an Image never exceeds this edge (2.1.287 d.ts `ImageSource`: 1 to 2048). */
33export const IMAGE_MAX_EDGE = 2048;
34/** The pixels an Image source carries per terminal cell, and a desktop picture's CSS pixels per column: a common cell size at 1x. */
35export const CELL_PIXELS = Object.freeze({ width: 8, height: 16 });
36
37/**
38 * Which element draws the pictures on this surface: `image` or `raster` on the terminal (the person's or the blit
39 * fact's choice, `useCells`), `svg` on every surface whose table has `Svg`.
40 */
41export function pictureKind(surface, { useCells = false } = {}) {
42 if (surface === 'terminal') return useCells ? 'raster' : 'image';
43 return 'svg';
44}
45
46/**
47 * Whether a `$.ui.blit` answer says the keyed Image draws its alt text, the one deny that means "no pixels here".
48 * Every other answer is silent: `{}` (pixels taken), or a deny for another reason (not mounted yet, another size).
49 */
50export function blitSaysAlt(result) {
51 return Boolean(result && typeof result.deny === 'string' && /\balt\b/i.test(result.deny));
52}
53
54/** Whether the terminal should draw cells: the person's toggle when they pressed `v`, else the blit fact. */
55export function useCellsFor({ toggled = null, altDrawn = false } = {}) {
56 return toggled === null ? Boolean(altDrawn) : Boolean(toggled);
57}
58
59/** The decoded thumbnail: `{ rgba, width, height }` from the JPEG's base64. Throws on bytes that are not a JPEG. */
60export function decodeThumb(jpegBase64, mimeType = 'image/jpeg') {
61 // The mod carries no PNG decoder: an own sketch uploaded as a PNG shows on the desktop (embedded as it is) when it fits.
62 if (mimeType === 'image/png') throw new Error('this PNG cannot be previewed here');
63 if (mimeType === 'image/webp') {
64 const webp = decodeWebp(base64Decode(jpegBase64));
65 return { rgba: webp.data, width: webp.width, height: webp.height };
66 }
67 const image = decodeJpeg(base64Decode(jpegBase64), { formatAsRGBA: true, maxResolutionInMP: 16, maxMemoryUsageInMB: 64 });
68 return { rgba: image.data, width: image.width, height: image.height };
69}
70
71/** Image source one pane tree may carry: under the engine's 2 MiB cap on a tree's Image sources. */
72export const IMAGE_TREE_BYTES = 1_800_000;
73
74/**
75 * One tree's Image budget. `admit(picture)` passes every picture through except an Image whose source would take the
76 * tree past `limit`, which waits as loading for a later drawing: the engine refuses a whole tree past its cap and draws
77 * an empty pane (seen live 2026-10-02 on a page of tall references before the blit probe answered). An Image's source
78 * is `{ rgba, width, height }` (`imageSource`), so the bytes that count are its base64 RGBA. Every other picture
79 * (Raster cells, an Svg, loading, failed) passes untouched.
80 */
81export function imageTreeBudget(limit = IMAGE_TREE_BYTES) {
82 let used = 0;
83 return {
84 admit(picture) {
85 if (!picture || picture.kind !== 'image') return picture;
86 const bytes = picture.source.rgba.length;
87 if (used + bytes > limit) return { kind: 'loading' };
88 used += bytes;
89 return picture;
90 },
91 };
92}
93
94/** The picture scaled to `width` x `height` by averaging the source area under each target pixel. */
95export function resizeRgba({ rgba, width, height }, toWidth, toHeight) {
96 const w = Math.max(1, Math.round(toWidth));
97 const h = Math.max(1, Math.round(toHeight));
98 if (w === width && h === height) return { rgba, width, height };
99 const out = new Uint8Array(w * h * 4);
100 const sx = width / w;
101 const sy = height / h;
102 for (let y = 0; y < h; y += 1) {
103 const y0 = y * sy;
104 const y1 = Math.min(height, y0 + sy);
105 for (let x = 0; x < w; x += 1) {
106 const x0 = x * sx;
107 const x1 = Math.min(width, x0 + sx);
108 let r = 0;
109 let g = 0;
110 let b = 0;
111 let a = 0;
112 let area = 0;
113 for (let py = Math.floor(y0); py < Math.ceil(y1); py += 1) {
114 const wy = Math.min(py + 1, y1) - Math.max(py, y0);
115 if (wy <= 0) continue;
116 for (let px = Math.floor(x0); px < Math.ceil(x1); px += 1) {
117 const wx = Math.min(px + 1, x1) - Math.max(px, x0);
118 if (wx <= 0) continue;
119 const weight = wx * wy;
120 const at = (py * width + px) * 4;
121 r += rgba[at] * weight;
122 g += rgba[at + 1] * weight;
123 b += rgba[at + 2] * weight;
124 a += rgba[at + 3] * weight;
125 area += weight;
126 }
127 }
128 const to = (y * w + x) * 4;
129 out[to] = Math.round(r / area);
130 out[to + 1] = Math.round(g / area);
131 out[to + 2] = Math.round(b / area);
132 out[to + 3] = Math.round(a / area);
133 }
134 }
135 return { rgba: out, width: w, height: h };
136}
137
138/**
139 * The box of one tile's picture, in cells: the tile's whole width (layout.mjs `tileGrid`), and as many rows as the
140 * picture's aspect asks at two pixels a cell height (a cell is about twice as tall as wide). A picture taller than
141 * `maxRows` (layout.mjs `pictureMaxRows`) is held to it and narrowed to keep its aspect. Never past Image's 255 cells.
142 */
143export function tileBox(tileColumns, width, height, maxRows = Infinity) {
144 const aspect = width > 0 && height > 0 ? height / width : 9 / 16;
145 let columns = Math.max(1, Math.min(IMAGE_MAX_CELLS, Math.floor(tileColumns)));
146 let rows = Math.max(1, Math.round(columns * aspect / 2));
147 const limit = Math.max(1, Math.min(IMAGE_MAX_CELLS, Math.floor(maxRows)));
148 if (rows > limit) {
149 rows = limit;
150 columns = Math.max(1, Math.min(columns, Math.round(rows * 2 / aspect)));
151 }
152 return { columns, rows };
153}
154
155/** A desktop picture's CSS size for its box: CELL_PIXELS.width a column, the height from the picture's own aspect. */
156export function desktopPictureSize(box, width, height) {
157 const cssWidth = box.columns * CELL_PIXELS.width;
158 return { width: cssWidth, height: Math.round(cssWidth * height / width) };
159}
160
161/**
162 * An Image's source for the decoded picture: raw RGBA no larger than its box needs at CELL_PIXELS per cell (the tree
163 * crosses to the engine on every redraw, so a 480 px thumbnail drawn 30 columns wide is sent at 240 px), and never past
164 * the element's edge limit. A picture already small enough is sent as decoded.
165 */
166export function imageSource(picture, box = null) {
167 const limits = [1, IMAGE_MAX_EDGE / Math.max(picture.width, picture.height)];
168 if (box) limits.push((box.columns * CELL_PIXELS.width) / picture.width, (box.rows * CELL_PIXELS.height) / picture.height);
169 const scale = Math.min(...limits);
170 const sized = scale < 1 ? resizeRgba(picture, Math.max(1, picture.width * scale), Math.max(1, picture.height * scale)) : picture;
171 return { rgba: base64Encode(sized.rgba), width: sized.width, height: sized.height };
172}
173
174/** A Raster's `cells` for the picture over `columns` x `rows`: half blocks, two pixels a cell. */
175export function rasterCells(picture, columns, rows) {
176 const c = Math.max(1, Math.min(RASTER_MAX_COLUMNS, columns));
177 const r = Math.max(1, Math.min(RASTER_MAX_ROWS, rows));
178 const sized = resizeRgba(picture, c, r * 2);
179 const words = new Uint32Array(c * r * 3);
180 for (let row = 0; row < r; row += 1) {
181 for (let col = 0; col < c; col += 1) {
182 const top = ((row * 2) * c + col) * 4;
183 const bottom = ((row * 2 + 1) * c + col) * 4;
184 const at = (row * c + col) * 3;
185 words[at] = HALF_BLOCK;
186 words[at + 1] = (sized.rgba[top] << 16) | (sized.rgba[top + 1] << 8) | sized.rgba[top + 2];
187 words[at + 2] = (sized.rgba[bottom] << 16) | (sized.rgba[bottom + 1] << 8) | sized.rgba[bottom + 2];
188 }
189 }
190 const bytes = new Uint8Array(words.length * 4);
191 for (let index = 0; index < words.length; index += 1) {
192 const word = words[index];
193 const at = index * 4;
194 bytes[at] = word & 0xff;
195 bytes[at + 1] = (word >>> 8) & 0xff;
196 bytes[at + 2] = (word >>> 16) & 0xff;
197 bytes[at + 3] = (word >>> 24) & 0xff;
198 }
199 return { cells: base64Encode(bytes), columns: c, rows: r };
200}
201
202function svgDocument(width, height, mimeType, base64) {
203 return `<svg xmlns="${SVG_NAMESPACE}" viewBox="0 0 ${width} ${height}" width="${width}" height="${height}">`
204 + `<image href="data:${mimeType};base64,${base64}" x="0" y="0" width="${width}" height="${height}" preserveAspectRatio="xMidYMid meet"/>`
205 + '</svg>';
206}
207
208/** The characters an Svg embedding `bytes` bytes of base64 takes, for a picture of that size. */
209function svgChars(width, height, mimeType, bytes) {
210 return svgDocument(width, height, mimeType, '').length + 4 * Math.ceil(bytes / 3);
211}
212
213/**
214 * The Svg source for a thumbnail: `{ source, embedded }`, `embedded` naming what it carries (`jpeg` as the server sent
215 * it, or `png` re-encoded smaller). `decode` is only called when the JPEG does not fit.
216 */
217export function svgPicture({ jpegBase64, width, height, mimeType = 'image/jpeg' }, decode = () => decodeThumb(jpegBase64, mimeType)) {
218 const asIs = svgDocument(width, height, mimeType, jpegBase64);
219 if (asIs.length <= SVG_MAX_CHARS) return { source: asIs, embedded: mimeType === 'image/webp' ? 'webp' : 'jpeg' };
220 const picture = decode();
221 let scale = 1;
222 for (;;) {
223 const w = Math.max(1, Math.floor(picture.width * scale));
224 const h = Math.max(1, Math.floor(picture.height * scale));
225 if (svgChars(width, height, 'image/png', storedPngBytes(w, h, 3)) <= SVG_MAX_CHARS) {
226 const png = encodePng(resizeRgba(picture, w, h));
227 return { source: svgDocument(width, height, 'image/png', base64Encode(png)), embedded: 'png' };
228 }
229 if (w === 1 && h === 1) throw new Error('the picture cannot fit an Svg');
230 scale *= 0.85;
231 }
232}
233hooks/workspace/poll.mjs 42 lines1/**
2 * When the pane next asks the server for the workspace (`design.slate.status`): the hosted screen's backoff
3 * (2, 3, 5, 8, then 10 s; `DELAYS` in packages/12ui/src/mcp-slate-ui-script-state.ts), reset by every change, and
4 * never later than the moment a start countdown ends, when the server lets that round go. Polling is the screen being
5 * in sight (workers/api/src/slate/limits.ts `SLATE_PAUSE`): only while the pane is open and something runs, or while the
6 * first read of the shown workspace keeps failing in a way a retry can mend. Pure.
7 */
8
9export const POLL_DELAYS_MS = Object.freeze([2000, 3000, 5000, 8000, 10000]);
10
11/** A countdown's last poll lands this long after its end, so the server has passed its deadline. */
12export const COUNTDOWN_MARGIN_MS = 500;
13
14/** The backoff step after a poll: back to the start when the view changed, one step on otherwise (unchanged, failed). */
15export function nextStep(step, changed) {
16 return changed ? 0 : Math.min(step + 1, POLL_DELAYS_MS.length - 1);
17}
18
19/** Whether the pane polls at all: open, a workspace shown, and something running. */
20export function wantsPolling({ isOpen, hasWorkspace, isRunning }) {
21 return Boolean(isOpen && hasWorkspace && isRunning);
22}
23
24/**
25 * Whether the pane reads again for a workspace it holds no view of yet: open, and the last read failed in a way a later
26 * read can mend (a 429, a 5xx, no answer at all). A refusal such as `unknown_workspace` keeps its error line and reads
27 * nothing more; Claude showing the workspace again still asks once.
28 */
29export function retriesFirstRead({ isOpen, hasView, failedRetryably }) {
30 return Boolean(isOpen && !hasView && failedRetryably);
31}
32
33/** How long until the next poll: the backoff delay, cut short to just after a running countdown's end. */
34export function pollDelay(step, countdown, nowMs) {
35 const delay = POLL_DELAYS_MS[Math.min(Math.max(step, 0), POLL_DELAYS_MS.length - 1)];
36 if (countdown && countdown.state === 'countdown' && typeof countdown.endsAtMs === 'number') {
37 const untilEnd = countdown.endsAtMs - nowMs + COUNTDOWN_MARGIN_MS;
38 return Math.max(COUNTDOWN_MARGIN_MS, Math.min(delay, untilEnd));
39 }
40 return delay;
41}
42hooks/workspace/redraw.mjs 90 lines1/**
2 * The redraw policy, one module (CLAUDE.md item 9): when the pane asks the engine for a fresh drawing on its own, not
3 * after the person pressed something. Pure: no `$`; register.mjs feeds it the model and the clock.
4 *
5 * Why it matters. Claude Code keeps one live set of button handles per pane, and every fresh drawing retires the last
6 * set; the Claude app cancels an ask in flight when a newer one comes and applies drawings only after the pointer is
7 * released, so a press lands on a drawing the engine has already retired and is refused (`ui_press` answered
8 * `{ handled: false }`, nothing run). Measured on the 0.2.117 pane: 21 to 25 self-redraws in a drawn workspace's first
9 * 10 s (one per picture) and about 1.5 a second while a round waits (a 1 s countdown ticker plus polls), with 23% to
10 * 50% of presses refused under the app's lag (~/.orchestrator/evidence/12ui/claude-workspace/results.md). So the pane
11 * redraws on its own only when what it shows changes, never on the clock alone (the start countdown's words do not
12 * change with time, view.mjs); a view that brings pictures is drawn once, together with them; and its own redraws wait
13 * for a pause in the person's presses: a press redraws at once and its drawing carries whatever landed before it.
14 */
15
16/** The pane's picture redraws come at most once a second: a batch never draws sooner than this after the last self-redraw. */
17export const PICTURE_BATCH_MS = 1000;
18
19/**
20 * How long a batch waits for the shown tab's pictures still being read, from the batch's start (a view that brings
21 * pictures, or the first picture to land), before it draws what is in. design.12ui.com answered a whole workspace's
22 * pictures in 0.6 to 2.6 s when they were all read at once (fix/round2/picture-latency-all.out: 3 runs of 34), and a
23 * website's screenshot in a waiting round took longer than the 1 s the batch used to wait, so each website landing was
24 * drawn twice, a second apart (gate out-waitidle400 at 19.0/20.0 s and 21.7/22.7 s).
25 */
26export const PICTURE_WAIT_MS = 3000;
27
28/** A picture as a drawing shows it: nothing, loading, failed with its reason, or ready (whatever element draws it). */
29function pictureFact(picture) {
30 if (!picture) return null;
31 if (picture.kind === 'loading') return 'loading';
32 if (picture.kind === 'failed') return `failed:${picture.reason}`;
33 return 'ready';
34}
35
36/**
37 * What a drawing of `model` shows, as one string: the tab, the lines, the tray, every tile and item with its picture's
38 * state. Two models with the same signature draw the same pane, so a self-redraw between them is skipped. Pictures
39 * count by state only, so the bytes of an Svg or an Image never decide a redraw. Only the shown tab is in the model, so
40 * the pictures of the other tabs land without a redraw.
41 */
42export function drawnSignature(model) {
43 return JSON.stringify({
44 surface: model.surface,
45 workspace: model.workspace,
46 emptyText: model.emptyText,
47 isLoading: model.isLoading,
48 prompt: model.prompt,
49 tab: model.tab,
50 noticeText: model.noticeText,
51 errorText: model.errorText,
52 tileColumns: model.tileColumns,
53 tray: model.tray,
54 selectedCount: model.selectedCount,
55 emptyLine: model.emptyLine,
56 perRound: model.perRound,
57 lv: model.lv ? { tile: { ...model.lv.tile }, picture: pictureFact(model.lv.picture), mode: model.lv.mode, scope: model.lv.scope, pages: model.lv.pages } : null,
58 sections: model.sections.map((section) => ({ ...section, groups: section.groups.map((group) => ({ ...group, tiles: group.tiles.map((tile) => ({ ...tile, picture: pictureFact(tile.picture) })) })) })),
59 sketches: model.sketches,
60 selectable: model.selectable,
61 items: model.items.map((item) => ({ ...item, picture: pictureFact(item.picture) })),
62 });
63}
64
65/**
66 * How long, from now, a batch of the shown tab's pictures waits for its redraw: never sooner than PICTURE_BATCH_MS after
67 * the last self-redraw (`sinceLastSelfMs`, null for none yet); once nothing the shown tab draws is still out, no longer
68 * than that; while pictures are still out (`outstanding`), until PICTURE_WAIT_MS after the batch began
69 * (`sinceBatchStartMs`), unless the last of them lands first. A picture that lands after that starts a batch of its own.
70 */
71export function pictureRedrawDelay({ sinceLastSelfMs, sinceBatchStartMs, outstanding }) {
72 const floor = sinceLastSelfMs === null ? 0 : Math.max(0, PICTURE_BATCH_MS - sinceLastSelfMs);
73 if (outstanding === 0) return floor;
74 return Math.max(floor, PICTURE_WAIT_MS - sinceBatchStartMs);
75}
76
77/**
78 * The pane's own redraws wait this long after the person's last press. Each self-redraw retires the drawing the person
79 * is pressing on; while they press, every press redraws anyway and its drawing shows what landed meanwhile, so nothing
80 * waits longer than the next press or this pause. Measured in the press rig at a 400 ms app delay: a picture batch drawn
81 * 114 ms before a tab press refused it (1 of 28; fix/results.md).
82 */
83export const PRESS_QUIET_MS = 1500;
84
85/** How long a self-redraw waits for the pause after the last press (`sinceLastPressMs`, null for none yet): 0 to draw now. */
86export function pressQuietDelay(sinceLastPressMs) {
87 if (sinceLastPressMs === null) return 0;
88 return Math.max(0, PRESS_QUIET_MS - sinceLastPressMs);
89}
90