SLOPSHOPPER

workorder-pane

Keygrip work orders in a pane: /workorders lists your project's deploy queue; pick one to read its fields, edits, schema and verify steps, see the page before…

panecommandtoastnetwork
v0.8.0no licenseupdated 2026-10-23KeygripGit/claude-mods/plugins/workorder-pane
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · workorder-pane
│ ┃ Work orders ✕ › fix the failing auth test and add an audit log call │ ┃ Connect this pane to your Keygrip project │ ┃ ⏺ Read(src/auth.ts) │ ┃ Paste the project's client key ⎿ Read 6 lines │ ┃ (kg_client_…). It comes from the project's ⏺ Update(src/auth.ts) │ ┃ Settings → Client MCP access in ⎿ Added 2 lines, removed 1 line │ ┃ app.keygrip.ai, or from your Keygrip ⏺ Bash(bun test) │ ┃ contact. It is kept on this machine only. ⎿ 3 pass, 1 fail │ ┃ │ ┃ Client key: kg_client_… ⏎ Connect ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /workorders │ ⎿ workorder-pane: Work orders pane opened. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Work orders
Connect this pane to your Keygrip project Paste the project's client key (kg_client_…). It comes from the project's Settings → Client MCP access in app.keygrip.ai, or from your Keygrip contact. It is kept on this machine only. Client key: kg_client_… ⏎ Connect
README

workorder-pane — Keygrip work orders inside Claude Code

A Claude Code mod (a plugin of function hooks, see docs/claude-code-mods.md) that draws the client deploy loop in a pane instead of a wall of markdown in a tool row. Tracks issue #1516.

/workorders          # the queue: every work order the connected project has
/workorders 502      # straight to one order by optimization id

What it draws

Queue. One row per work order from kg_workorders: id, version, mode, state, keyword. Blocked rows are dimmed and refuse to open (the server refuses them too). (The open pull request line above the rows and the in PR state draw only when the server sends open_pull_request / pull_request_url; the client server stopped sending them on 2026-10-23, when its PR-report tool came off, so on it a reported deploy is the only publish-side state.) The queue is fetched from the server every time the pane opens and every time you go back to it (nothing from an earlier open is shown as current); a row with no keyword (an order made from a URL) is named by its slug. r refresh, s show/hide superseded versions.

Reader (pick a row). Fetches kg_fetch_workorder(format="json") once: the work order as data, built on the server from the same work order IR the markdown is rendered from (#1524), so nothing in the pane reads the document's headings. Tabs on 1–7, b back to the queue:

TabShows
1 Overviewmode, prepared date, blockers, keyword target, "what changed", redirect, hero image
2 Fieldseach deployable value in a code block, a length meter against the rubric's band for that field (red when outside it), unchanged when it matches the live page, a copy button
3 Editseach body edit boxed: why, where, the Find text and the Replace/Insert HTML, a copy button; a net-new order shows the full body
4 Schemaeach JSON-LD node with the <script> wrapper stripped, a copy button
5 Verifythe post-publish steps as toggles, with a checked count
6 Notescontext changed since this version, recommended-not-applied, checked-and-left-alone
7 Previewthe page rendered on the server by kg_workorder_preview (the first slice starts rendering the moment an order is opened, so the tab usually draws at once): p toggles live (as served now) and proposed (the work order's edits applied in the browser, removals marked with a dashed red rule; the web page the link opens shows the page alone under a header, and an edit the preview cannot apply marks the work order stale for staff instead of appearing on the page); n/u move through 1600 px slices, r re-renders. Terminal: pixels (kitty/Ghostty). Desktop/VS Code: a half-scale JPEG inside an Svg, plus a link to the same preview as a page on app.keygrip.ai. A net-new page (no live URL yet) is shown on a template: a live page of the same site — the server picks the inventory page nearest the new URL's path, and a Template URL field under the picture swaps in any other live page on the site. live is the template as served; proposed is the template with its article thrown out and the work order's body, H1 and hero in its place, so the new page appears in the site's own layout

Under the tabs, an Approve for publishing button (a) calls kg_workorder_approve; on an approved order it becomes Withdraw approval. The queue's state column reads approved for a stamped row (ready is a row nobody has signed off; deployed outranks both). The stamp is per version — an edit makes a new, unapproved version — and it is what a publishing step will read (#1518). Editing is not done in the pane: the reader says so and points at the loop — tell Claude what to change, it calls kg_fetch_body → kg_save_version on the client server (configure that server in the session, see below), and the new version appears in the queue.

Nothing else in the mod writes. There is no "report deployed" step (0.8.0, 2026-10-23: the client server's kg_report_deployed came off): Keygrip's daily check of the site records when a page goes live, and the queue's state column reads deployed once it has.

Installing it (clients, and anyone outside the monorepo)

The client path is the public GitHub marketplace KeygripGit/claude-mods, published from this folder by bin/publish-mods (bump version first). The desktop app's plugin browser lists git-hosted marketplaces and showed nothing for a URL-hosted one (measured 2026-10-03), so the guide — /mods/ on the app, Desktop and Terminal sections — uses the repo for both:

claude plugin marketplace add KeygripGit/claude-mods
claude plugin install workorder-pane@keygrip

The app also serves this folder as a marketplace (web/mods.py: GET /mods/marketplace.json with archive sources, GET /mods/<name>-<version>.zip built on demand, deterministic, sha256 in the manifest) under the name keygrip-app — the no-git fallback for a terminal. The two names differ on purpose: the engine refuses to add a marketplace whose name is already declared with another source, with a plain "Failed to add marketplace" in the desktop app.

The pane talks to https://app.keygrip.ai/client/mcp itself — one JSON-RPC tools/call POST per tool over $.http.fetch, the project's kg_client_ key as the Bearer header — and asks for that key once, in the pane, keeping it in the plugin's own $.store (k on the queue changes it). It deliberately does not declare the server in the manifest: a tool call made from a button is refused by the Auto-mode permission classifier ("the request that produced this action did not ask for one"), measured on the desktop with a plugin-bundled server too, which would make every client paste an allow list; and a manifest server needs the key through /plugin configure. A direct fetch needs neither — measured under --permission-mode auto on 2026-10-03. The endpoint is stateless and answers JSON, so there is no handshake. Bump version in plugin.json with every change you want installs to pick up: an install pins to the version it saw, claude plugin update only moves when the number does, and the zip URL carries the version.

⚠️ A plugin loaded through --plugin-dir / CLAUDE_CODE_PLUGIN_DIRS overrides a marketplace install of the same name (and claude plugin install --config then reports "failed to load after install"); on a developer machine use one or the other.

Loading it from the checkout (developers)

CLI, one session: claude --plugin-dir app/mods/workorder-pane

CLI or desktop, always: name the folder in CLAUDE_CODE_PLUGIN_DIRS, in the process environment or the env block of ~/.claude/settings.json (the user file, never a project's).

Claude Desktop on Windows runs its own engine with its own %USERPROFILE%\.claude, so it needs a Windows path. The copy that works today:

// C:\Users\<you>\.claude\settings.json
{
  "env": { "CLAUDE_CODE_PLUGIN_DIRS": "C:\\Users\\<you>\\.claude\\mods\\workorder-pane" },
  "permissions": { "allow": [
    "mcp__keygrip-workorder__kg_workorders",
    "mcp__keygrip-workorder__kg_fetch_workorder",
    "mcp__keygrip-workorder__kg_workorder_preview",
    "mcp__keygrip-workorder__kg_fetch_body"
  ] }
}

(For a marketplace install the server is plugin_workorder-pane_keygrip-workorder in those rules.) The allow list matters in Auto permission mode only for the developer path above, where the tools come from a hand-configured server: the pane's MCP calls come from a button, not a prompt, so the auto-mode classifier has nothing to match them against and refuses them ("the request that produced this action did not ask for one"). Allowed tools skip the classifier. The write tools (kg_workorder_approve, kg_save_version, kg_restore_version) are deliberately not allowed; switch the session off Auto, or approve the prompt, when you approve from the pane or ask Claude to edit a page.

Sync the Windows copy from WSL after a change:

rsync -a --delete --exclude .cache --exclude '.claude-plugin/types' --exclude tsconfig.json \
  app/mods/workorder-pane/ /mnt/c/Users/<you>/.claude/mods/workorder-pane/

The MCP server it talks to

keygrip-workorder → https://app.keygrip.ai/client/mcp with a project-scoped kg_client_ key (claude mcp add --transport http keygrip-workorder <url> -H "Authorization: Bearer kg_client_…"). The server name is what $.mcp.call is given; the desktop app needs the same server in its .claude.json. Minting the key: project settings in the app (issue #1071).

How the preview is made

Nothing runs on the laptop. kg_workorder_preview(optimization_id, mode, slice, format, scale) on the client MCP server (and the same tool on the internal /mcp) calls GET /api/v1/optimizations/{id}/preview, which content/page_preview.py serves: the app image's own Chromium loads the run's page_url, and in proposed mode runs the work order's BodyEdits against the live DOM by the same rules a person follows in the CMS editor (find by meaning, a section runs to the next heading of the same level, edits apply in order), then screenshots the page in 1280×1600 slices. A net-new page has no live URL, so the browser loads a template instead — template_url (a live page on the same site; anything off the site is refused) or the inventory page nearest the new URL's path — and in proposed mode finds the template's content column, removes the article from its first text block onward (the H1, byline and hero above it stay), appends the work order's body there, and swaps in the new H1, hero and title. The metadata then carries template_url and page_url beside url. One call returns one slice as an image block plus a JSON block (slices, height, applied per edit, view_url). Renders are cached ten minutes per (run, version, mode) in the web process. The web twin is …/studio/runs/<id>/preview/?mode=proposed, which shows the page alone under a header, as a live document (the render's DOM, scripts stripped, in a sandboxed frame) rather than slices (an edit the preview cannot apply marks the work order stale rather than appearing on the page); that is the view_url the desktop pane links to.

Pixels in the terminal still need kitty ≥ 0.28 or Ghostty (see docs/claude-code-mods.md).

Developing

claude plugin validate app/mods/workorder-pane   # manifest + what the module hooks/calls
claude plugin test     app/mods/workorder-pane   # hooks/*.test.tsx against the engine

hooks/workorder.ts holds the shapes the server answers with; hooks/fixture.ts is a compact work order in the JSON shape, modelled on optimization 502. The server side of that shape is packager.render_workorder_json, pinned against the markdown by content.tests.test_workorder_ir.TestWorkorderJsonMatchesTheMarkdown. Rules the validator enforces that cost a round each: $ may only be passed to a top-level function declaration; atom() references need literal plugin strings; a Button takes one string child or label; a fetch must start from a command or button handler, never from the render hook (a write from the draw's async chain is dropped silently).

Not built

  • A shared render cache (R2 or Postgres) if the per-process one proves too cold across the two web boxes.
Source 3 files
hooks/register.tsx 716 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderSurface } from 'claude-code'
3
4import type { Tab } from '../types'
5import { readWorkOrder, rowLabel, unwrap } from './workorder'
6import type { OpenPullRequest, QueueRow, WorkOrder, Field } from './workorder'
7
8const PANE = 'workorders'
9// The pane talks to Keygrip's client MCP endpoint itself, over the engine's fetch, with the
10// project's kg_client_ key as a header. Not through an MCP server in the manifest: a tool call
11// made from a button is refused by the Auto-mode permission classifier ("the request that
12// produced this action did not ask for one"), which would make every client paste an allow
13// list, and the key would have to be set through /plugin configure. A direct fetch needs
14// neither — the key is pasted once into the pane and kept in the plugin's own store. The
15// endpoint is stateless and answers JSON, so one POST per tool call is the whole protocol.
16const ENDPOINT = 'https://app.keygrip.ai/client/mcp'
17const KEY_STORE = 'client_key'
18let clientKey: string | null | undefined   // undefined: not read yet; null: none stored
19
20async function loadKey($: EngineInterface): Promise<string | null> {
21  if (clientKey === undefined) {
22    const v = await $.store.get(KEY_STORE)
23    clientKey = typeof v === 'string' && v ? v : null
24  }
25  return clientKey
26}
27
28async function saveKey($: EngineInterface, key: string) {
29  clientKey = key || null
30  if (key) await $.store.set(KEY_STORE, key)
31  else await $.store.delete(KEY_STORE)
32  // every cache was filled under the old key
33  queue = null; queueKey = null; orders.clear(); shots.clear()
34}
35
36type ToolResult = { isError: boolean; content: { type: string; text?: string; [k: string]: unknown }[] }
37let rpcId = 0
38async function callTool($: EngineInterface, tool: string, args: Record<string, unknown>): Promise<ToolResult> {
39  const key = await loadKey($)
40  if (!key) return { isError: true, content: [{ type: 'text', text: 'no client key: paste one into the pane first' }] }
41  const r = await $.http.fetch(ENDPOINT, {
42    method: 'POST',
43    headers: { 'Authorization': `Bearer ${key}`, 'Content-Type': 'application/json', 'Accept': 'application/json' },
44    body: JSON.stringify({ jsonrpc: '2.0', id: ++rpcId, method: 'tools/call', params: { name: tool, arguments: args } }),
45  })
46  if (r.status === 401 || r.status === 403) return { isError: true, content: [{ type: 'text', text: `the key was refused (HTTP ${r.status}): paste a current one (k)` }] }
47  if (!r.ok) return { isError: true, content: [{ type: 'text', text: `HTTP ${r.status} from ${ENDPOINT}: ${r.text.slice(0, 200)}` }] }
48  let body: { result?: ToolResult; error?: { message?: string } }
49  try { body = JSON.parse(r.text) } catch { return { isError: true, content: [{ type: 'text', text: `not JSON: ${r.text.slice(0, 200)}` }] } }
50  if (body.error) return { isError: true, content: [{ type: 'text', text: body.error.message ?? 'rpc error' }] }
51  const res = body.result ?? { isError: true, content: [{ type: 'text', text: 'empty result' }] }
52  return { isError: Boolean(res.isError), content: res.content ?? [] }
53}
54
55const view = atom({ plugin: 'workorder-pane', key: 'view' } as const, 'queue' as 'queue' | 'order')
56const selected = atom({ plugin: 'workorder-pane', key: 'selected' } as const, null as number | null)
57const tab = atom({ plugin: 'workorder-pane', key: 'tab' } as const, 'overview' as Tab)
58const includeSuperseded = atom({ plugin: 'workorder-pane', key: 'includeSuperseded' } as const, false)
59const checked = atom({ plugin: 'workorder-pane', key: 'checked' } as const, [] as number[])
60const tick = atom({ plugin: 'workorder-pane', key: 'tick' } as const, 0)
61const slice = atom({ plugin: 'workorder-pane', key: 'slice' } as const, 0)
62const keyPrompt = atom({ plugin: 'workorder-pane', key: 'keyPrompt' } as const, false)
63const previewMode = atom({ plugin: 'workorder-pane', key: 'previewMode' } as const, 'proposed' as 'live' | 'proposed')
64
65// Fetched data lives here, not in $.state: a work order is tens of KB. A hot reload
66// empties it and the next draw refetches, keyed by the ids $.state still holds.
67type Loaded<T> = { ok: true; data: T } | { ok: false; error: string }
68let queue: Loaded<QueueRow[]> | null = null
69let openPr: OpenPullRequest | null = null
70let queueKey: string | null = ''
71const orders = new Map<number, Loaded<WorkOrder>>()
72// One rendered slice from kg_workorder_preview, keyed by `${id}:${mode}:${slice}:${variant}`.
73type Shot = { data: string; mime: string; meta: PreviewMeta }
74type PreviewMeta = { mode: string; url: string; width: number; height: number; slice_height: number; slices: number
75  truncated: boolean; elapsed_ms: number; applied: { id: string; kind: string; status: string; note?: string }[]
76  applied_count: number; not_found: string[]; view_url?: string; slice: number
77  // A page that is not live yet renders on a template page of the same site: `url` is the
78  // template loaded, `template_url` names it and `page_url` is the work order's own.
79  page_url?: string; template_url?: string }
80const shots = new Map<string, Loaded<Shot>>()
81// The template a net-new order is previewed on, per order, once the reader typed one; unset
82// means the server picks the inventory page nearest the new URL's path.
83const templates = new Map<number, string>()
84const shotKey = (id: number, mode: string, at: number, variant: string) => `${id}:${mode}:${at}:${variant}`
85const inflight = new Set<string>()
86
87const TABS: { id: Tab; label: string; hotkey: string }[] = [
88  { id: 'overview', label: 'Overview', hotkey: '1' },
89  { id: 'fields', label: 'Fields', hotkey: '2' },
90  { id: 'edits', label: 'Edits', hotkey: '3' },
91  { id: 'schema', label: 'Schema', hotkey: '4' },
92  { id: 'verify', label: 'Verify', hotkey: '5' },
93  { id: 'notes', label: 'Notes', hotkey: '6' },
94  { id: 'preview', label: 'Preview', hotkey: '7' },
95]
96
97// One word per row: blocked outranks everything (the server refuses the document), a
98// reported deploy outranks the approval it needed, and `approved` is the stamp a publishing
99// step reads (#1518) — a ready row is one nobody has signed off yet.
100// An approved page already reported in a pull request reads `in PR` (#1855).
101function stateOf(r: QueueRow): string {
102  return r.blocked ? `BLOCKED(${r.blocker_count})` : r.deployed_at ? 'deployed'
103    : r.approved_at ? (r.pull_request_url ? 'in PR' : 'approved') : 'ready'
104}
105
106// Where an approved page goes next in the client's repo: the open PR's branch, or a new PR.
107function prHint(id: number): string {
108  return openPr
109    ? `Ask Claude to add #${id} to the open PR ${openPr.url} (branch ${openPr.branch}), not a new one.`
110    : `Ask Claude to write #${id} into the site from its work order (a PR in the repo, or the CMS).`
111}
112
113// kg_workorder_approve, then the queue refetches so the row's state follows the server.
114async function setApproval($: EngineInterface, id: number, approved: boolean) {
115  const r = await callTool($, 'kg_workorder_approve', { optimization_id: id, approved })
116  if (r.isError) { $.ui.toast(`${approved ? 'Approve' : 'Withdraw'} failed: ${unwrap(r.content).slice(0, 120)}`); return }
117  $.ui.toast(approved ? `#${id} approved. ${prHint(id)}` : `#${id} approval withdrawn`)
118  queue = null
119  await update($, tick, n => (n ?? 0) + 1)
120  const superseded = await read($, includeSuperseded)
121  void loadQueue($, superseded)
122}
123
124function meter(n: number, limit: number, width = 20): string {
125  const filled = Math.min(width, Math.round((n / limit) * width))
126  return `${'#'.repeat(filled)}${'-'.repeat(width - filled)} ${n}/${limit}`
127}
128
129function outOfBand(f: Field): boolean {
130  const [lo, hi] = f.band
131  return (lo !== null && f.chars < lo) || (hi !== null && f.chars > hi)
132}
133
134function overview(wo: WorkOrder): string {
135  const parts = [`**Mode:** ${wo.mode}${wo.prepared ? `  \n**Prepared:** ${wo.prepared}` : ''}`]
136  if (wo.blocked) parts.push(`**Blocked:** ${wo.blocking.map(b => b.reason).join('; ')}`)
137  if (wo.keyword.primary || wo.keyword.secondaries.length) {
138    parts.push(['### Keyword target', '',
139      ...(wo.keyword.primary ? [`- **Primary:** ${wo.keyword.primary}`] : []),
140      ...(wo.keyword.secondaries.length ? [`- **Secondary:** ${wo.keyword.secondaries.join(', ')}`] : []),
141    ].join('\n'))
142  }
143  if (wo.what_changed.length) parts.push(['### What changed', '', ...wo.what_changed.map((w, i) => `${i + 1}. ${w}`)].join('\n'))
144  if (wo.redirect) parts.push(`### Redirect\n\n\`${wo.redirect.from_url}\` answers ${wo.redirect.status} to \`${wo.redirect.to_url}\` once this page is live.`)
145  for (const a of wo.assets) {
146    parts.push([a.disposition === 'upload' ? '### Hero image → add to the page' : '### Hero image → keep in place', '',
147      `- **URL:** ${a.url}`, ...(a.alt ? [`- **Alt text:** ${a.alt}`] : [])].join('\n'))
148  }
149  return parts.join('\n\n')
150}
151
152// The Notes tab: what changed in the client record since this version, then the editor notes.
153function noteSections(wo: WorkOrder): string[] {
154  const out: string[] = []
155  if (wo.context_changes.length) {
156    const bySection = new Map<string, string[]>()
157    for (const c of wo.context_changes) {
158      const flag = c.recheck_due ? `${c.reason}; recheck due${c.recheck_at ? ` ${c.recheck_at}` : ''}` : c.reason
159      for (const name of c.sections) bySection.set(name, [...(bySection.get(name) ?? []), `    - fact ${c.fact_id} (${flag}): ${c.text}`])
160    }
161    out.push(['## Context changed since this version', '',
162      ...[...bySection].flatMap(([name, lines]) => [`- **${name}**`, ...lines])].join('\n'))
163  }
164  if (wo.recommended.length) {
165    out.push(['## Recommended, not applied', '', ...wo.recommended.map(r =>
166      `- **${r.label}**${r.heading ? ` under "${r.heading}"` : ''}: ${r.reason}`
167      + (r.text ? ` Current text: "${r.text}"` : '') + (r.suggestion ? ` Suggested: ${r.suggestion}` : ''))].join('\n'))
168  }
169  if (wo.checked.length) {
170    out.push(['## Checked and left alone', '', ...wo.checked.map(c => `- ${c.label}${c.reason ? ` (${c.reason})` : ''}`)].join('\n'))
171  }
172  return out
173}
174
175async function loadQueue($: EngineInterface, superseded: boolean) {
176  const key = `queue:${superseded}`
177  if (inflight.has(key)) return
178  inflight.add(key)
179  await update($, tick, n => (n ?? 0) + 1)
180  try {
181    const r = await callTool($, 'kg_workorders', { include_superseded: superseded })
182    if (r.isError) queue = { ok: false, error: unwrap(r.content) }
183    else {
184      const parsed = JSON.parse(unwrap(r.content)) as { items?: QueueRow[]; open_pull_request?: OpenPullRequest | null }
185      queue = { ok: true, data: parsed.items ?? [] }
186      openPr = parsed.open_pull_request ?? null
187    }
188    queueKey = key
189  } catch (err) {
190    queue = { ok: false, error: String(err) }
191    queueKey = key
192  } finally {
193    inflight.delete(key)
194    await update($, tick, n => (n ?? 0) + 1)
195  }
196}
197
198async function loadOrder($: EngineInterface, id: number) {
199  const key = `order:${id}`
200  if (inflight.has(key)) return
201  inflight.add(key)
202  await update($, tick, n => (n ?? 0) + 1)
203  try {
204    // The order as data (#1524), not the markdown: the pane draws it, an agent follows the document.
205    const r = await callTool($, 'kg_fetch_workorder', { optimization_id: id, format: 'json' })
206    const text = unwrap(r.content)
207    orders.set(id, r.isError ? { ok: false, error: text } : { ok: true, data: readWorkOrder(text) })
208  } catch (err) {
209    orders.set(id, { ok: false, error: String(err) })
210  } finally {
211    inflight.delete(key)
212    await update($, tick, n => (n ?? 0) + 1)
213  }
214}
215
216
217//: Under this many raw bytes the engine leaves a PNG alone (measured: a 200 KB slice arrived
218//: as PNG, a 1.1 MB one as JPEG).
219const TERMINAL_PNG_BUDGET = 400_000
220// base64 of the PNG signature 0x89 'P' 'N' 'G' \r \n 0x1a \n
221const isPng = (b64: string) => b64.startsWith('iVBORw0KGgo')
222
223type ImageBlock = { type: string; data?: string; mimeType?: string; source?: { type?: string; data?: string; media_type?: string } }
224function pictureOf(blocks: readonly { type: string }[]): { data: string; mime: string } | null {
225  for (const b of blocks as ImageBlock[]) {
226    if (b.type !== 'image') continue
227    if (b.source?.data) return { data: b.source.data, mime: b.source.media_type ?? 'image/png' }
228    if (b.data) return { data: b.data, mime: b.mimeType ?? 'image/png' }
229  }
230  return null
231}
232
233// Layer 3: the server renders the page (live, or with the edits applied in the browser)
234// and hands one slice back as an image block plus its metadata — kg_workorder_preview.
235// `variant` is `full` (PNG, for the terminal's Image) or `thumb` (half-scale JPEG, for the
236// desktop's Svg budget).
237async function loadShot($: EngineInterface, id: number, mode: string, at: number, variant: 'full' | 'thumb', refresh = false) {
238  const key = shotKey(id, mode, at, variant)
239  if (inflight.has(key)) return
240  inflight.add(key)
241  await update($, tick, n => (n ?? 0) + 1)
242  try {
243    const args: Record<string, unknown> = { optimization_id: id, mode, slice: at, refresh }
244    const template = templates.get(id)
245    if (template) args.template_url = template
246    // The engine re-encodes an image block over its own byte limit to JPEG before a plugin
247    // sees it, and the terminal's Image takes PNG only: ask the server to keep the PNG under
248    // that limit (palette, then scale). The desktop's Svg takes any picture under ~128 KB.
249    if (variant === 'thumb') Object.assign(args, { format: 'jpeg', scale: 0.5 })
250    else Object.assign(args, { format: 'png', max_bytes: TERMINAL_PNG_BUDGET })
251    const r = await callTool($, 'kg_workorder_preview', args)
252    if (r.isError) { shots.set(key, { ok: false, error: unwrap(r.content).slice(0, 400) }); return }
253    // The engine hands a plugin the result as the session stores it, which is the API shape
254    // ({ type: 'image', source: { type: 'base64', media_type, data } }); a raw MCP block
255    // ({ data, mimeType }) is accepted too, so a test or another host reads the same.
256    const picture = pictureOf(r.content)
257    const metaText = r.content.find(b => b.type === 'text' && (b.text ?? '').trim().startsWith('{'))?.text ?? '{}'
258    if (!picture) {
259      const shapes = r.content.map(b => `${b.type}{${Object.keys(b).filter(k => k !== 'type').join(',')}}`).join(' ')
260      shots.set(key, { ok: false, error: `the tool returned no image block (blocks: ${shapes || 'none'})` })
261      return
262    }
263    if (variant === 'full' && !isPng(picture.data)) {
264      const kb = Math.round((picture.data.length * 3) / 4 / 1024)
265      shots.set(key, { ok: false, error: `the engine handed the pane a ${picture.mime} of ${kb} KB, not a PNG; the terminal draws PNG only (server max_bytes=${TERMINAL_PNG_BUDGET})` })
266      return
267    }
268    shots.set(key, { ok: true, data: { ...picture, meta: JSON.parse(metaText) as PreviewMeta } })
269  } catch (err) {
270    shots.set(key, { ok: false, error: String(err) })
271  } finally {
272    inflight.delete(key)
273    await update($, tick, n => (n ?? 0) + 1)
274  }
275}
276
277// Opening an order starts the server render of its first preview slice right away, so the
278// Preview tab draws from the cache instead of making the reader wait the few seconds a
279// Chromium render takes. Only slice 0 of the current mode: one render warms the server's
280// page cache for every other slice of that mode, and the other mode is a `p` away.
281async function prefetchPreview($: EngineInterface, id: number, surface: RenderSurface) {
282  const variant = surface === 'terminal' ? 'full' : 'thumb'
283  const mode = await read($, previewMode)
284  if (!shots.has(shotKey(id, mode, 0, variant))) void loadShot($, id, mode, 0, variant)
285}
286
287export const register: Register = on => {
288  on('session.start', async ($, e, next) => {
289    await $.command.register({
290      name: 'workorders',
291      description: 'Keygrip work orders in a pane: the queue, or one order by id (/workorders 502)',
292    })
293    return next(e)
294  })
295
296  on('command.run', { command: 'workorders' }, async ($, e) => {
297    const id = Number.parseInt(e.args.trim(), 10)
298    if (Number.isFinite(id)) {
299      await update($, selected, () => id)
300      await update($, view, () => 'order')
301      await update($, tab, () => 'overview')
302    } else {
303      await update($, view, () => 'queue')
304    }
305    const superseded = await read($, includeSuperseded)
306    // Every open asks the server again: a work order changes under the pane (a new version,
307    // an approval, a deploy report), so what an earlier open fetched is not shown as current.
308    queue = null
309    if (Number.isFinite(id)) orders.delete(id)
310    if (await loadKey($)) {
311      void loadQueue($, superseded)
312      if (Number.isFinite(id)) void loadOrder($, id)
313      if (Number.isFinite(id)) void prefetchPreview($, id, 'terminal')
314    }
315    const opened = await $.ui.open({ id: PANE, title: 'Work orders' })
316    return { text: opened.isPlaced ? 'Work orders pane opened.' : `Pane not placed: ${opened.reason}` }
317  })
318
319  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
320    if (e.surface === 'mobile') {
321      const { Text } = $.ui.resolve(e)
322      return <Text dimColor>The work-order pane needs a surface with Input (terminal, desktop or VS Code).</Text>
323    }
324    const { Box, Text, Button, Input, Code, Markdown, Link } = $.ui.resolve(e)
325    const [which, id, current, superseded, done, at, pmode] = await Promise.all([
326      read($, view), read($, selected), read($, tab), read($, includeSuperseded), read($, checked), read($, slice), read($, previewMode),
327    ])
328    await read($, tick)
329    const width = Math.max(20, e.props.bodyColumns - 2)
330    const surface: RenderSurface = e.surface
331
332    const copy = (text: string, what: string) => async () => {
333      const r = await $.ui.copy({ text, surface })
334      $.ui.toast(r.isCopied ? `Copied ${what}` : `Could not copy ${what}: ${r.reason}`)
335    }
336
337    // ---- key ---------------------------------------------------------------
338    // Pasted once per machine and kept in the plugin's store; `k` on the queue changes it.
339    const haveKey = await loadKey($)
340    const askKey = await read($, keyPrompt)
341    if (!haveKey || askKey) {
342      const submit = (value: string) => {
343        const k = value.trim()
344        if (!k.startsWith('kg_client_')) { $.ui.toast('A Keygrip client key starts with kg_client_'); return }
345        void (async () => {
346          await saveKey($, k)
347          await update($, keyPrompt, () => false)
348          await update($, view, () => 'queue')
349          void loadQueue($, superseded)
350        })()
351      }
352      return (
353        <Box flexDirection="column" gap={1}>
354          <Text bold>{haveKey ? 'Change the Keygrip client key' : 'Connect this pane to your Keygrip project'}</Text>
355          <Text dimColor wrap="wrap">Paste the project's client key (kg_client_…). It comes from the project's Settings → Client MCP access in app.keygrip.ai, or from your Keygrip contact. It is kept on this machine only.</Text>
356          <Input key="client-key" label="Client key" placeholder="kg_client_…" submitLabel="Connect" autoFocus onSubmit={submit} />
357          {haveKey && <Button key="keep-key" hotkey="b" onPress={() => update($, keyPrompt, () => false)}>Keep the current key</Button>}
358        </Box>
359      )
360    }
361
362    // ---- queue -------------------------------------------------------------
363    if (which === 'queue' || id === null) {
364      const key = `queue:${superseded}`
365      if (queue === null || queueKey !== key) {
366        if (inflight.has(key)) return <Text dimColor>Loading work orders…</Text>
367        return (
368          <Box flexDirection="column" gap={1}>
369            <Text dimColor>Work orders not loaded yet.</Text>
370            <Button key="load-queue" hotkey="l" onPress={() => { void loadQueue($, superseded) }}>Load</Button>
371          </Box>
372        )
373      }
374      if (!queue.ok) {
375        return (
376          <Box flexDirection="column" gap={1}>
377            <Text color="red">Could not list work orders: {queue.error}</Text>
378            <Button hotkey="r" onPress={() => { queue = null; void loadQueue($, superseded) }}>Retry</Button>
379          </Box>
380        )
381      }
382      const rows = queue.data
383      const ready = rows.filter(r => !r.blocked).length
384      const open = (row: QueueRow) => () => {
385        if (row.blocked) { $.ui.toast(`#${row.id} is blocked (${row.blocker_count}); Keygrip is resolving it`); return }
386        orders.delete(row.id)
387        void loadOrder($, row.id)
388        void prefetchPreview($, row.id, surface)
389        void (async () => {
390          await update($, selected, () => row.id)
391          await update($, tab, () => 'overview')
392          await update($, checked, () => [])
393          await update($, slice, () => 0)
394          await update($, view, () => 'order')
395        })()
396      }
397      return (
398        <Box flexDirection="column" gap={1}>
399          <Text bold>{rows.length} work orders · {ready} ready · {rows.length - ready} blocked{superseded ? ' · superseded included' : ''}</Text>
400          <Text key="open-pr" dimColor wrap="truncate-end">{openPr
401            ? `Open PR: ${openPr.url} · branch ${openPr.branch} · ${openPr.optimization_ids.length} page${openPr.optimization_ids.length === 1 ? '' : 's'}`
402            : 'No open PR — the first approved page starts one.'}</Text>
403          {surface === 'terminal' ? (
404            // Monospace: one padded line per row is the table.
405            <Box flexDirection="column">
406              <Text dimColor>{'id    ver  mode      state       keyword'}</Text>
407              {rows.map(r => {
408                const flag = stateOf(r)
409                const label = `#${String(r.id).padEnd(4)} v${String(r.version).padEnd(3)} ${r.mode.padEnd(9)} ${flag.padEnd(11)} ${rowLabel(r)}`
410                return (
411                  <Button
412                    key={`row-${r.id}`}
413                    plain
414                    dimColor={r.blocked}
415                    label={label.length > width ? label.slice(0, width - 1) + '…' : label}
416                    onPress={open(r)}
417                  />
418                )
419              })}
420            </Box>
421          ) : (
422            // Proportional type: padding does not line up, so the columns are Boxes of a
423            // fixed share of the width; the keyword is the button that opens the order.
424            <Box flexDirection="column">
425              <Box flexDirection="row" gap={1}>
426                <Box width="9%"><Text dimColor bold>id</Text></Box>
427                <Box width="7%"><Text dimColor bold>ver</Text></Box>
428                <Box width="13%"><Text dimColor bold>mode</Text></Box>
429                <Box width="16%"><Text dimColor bold>state</Text></Box>
430                <Box flexGrow={1}><Text dimColor bold>keyword</Text></Box>
431              </Box>
432              {rows.map(r => {
433                const flag = stateOf(r)
434                return (
435                  <Box key={`qrow-${r.id}`} flexDirection="row" gap={1} alignItems="center">
436                    <Box width="9%"><Text dimColor={r.blocked}>#{r.id}</Text></Box>
437                    <Box width="7%"><Text dimColor={r.blocked}>v{r.version}</Text></Box>
438                    <Box width="13%"><Text dimColor={r.blocked}>{r.mode === 'net_new' ? 'net new' : r.mode}</Text></Box>
439                    <Box width="16%"><Text color={r.blocked ? 'red' : r.deployed_at ? 'green' : r.approved_at ? 'cyan' : undefined} dimColor={r.blocked}>{flag}</Text></Box>
440                    <Box flexGrow={1}>
441                      <Button key={`row-${r.id}`} plain dimColor={r.blocked} label={rowLabel(r)} onPress={open(r)} />
442                    </Box>
443                  </Box>
444                )
445              })}
446            </Box>
447          )}
448          <Box gap={1}>
449            <Button hotkey="r" onPress={() => { queue = null; void loadQueue($, superseded) }}>Refresh</Button>
450            <Button key="change-key" hotkey="k" onPress={() => update($, keyPrompt, () => true)}>Key</Button>
451            <Button hotkey="s" onPress={() => { void (async () => { const next = !superseded; await update($, includeSuperseded, () => next); void loadQueue($, next) })() }}>{superseded ? 'Hide superseded' : 'Show superseded'}</Button>
452            <Button role="dismiss" onPress={() => $.ui.close({ id: PANE })}>Close</Button>
453          </Box>
454        </Box>
455      )
456    }
457
458    // ---- one order ----------------------------------------------------------
459    const loaded = orders.get(id)
460    const back = <Button key="back" hotkey="b" onPress={() => { queue = null; void loadQueue($, superseded); void update($, view, () => 'queue') }}>Back to queue</Button>
461    if (!loaded) {
462      if (inflight.has(`order:${id}`)) return <Box flexDirection="column" gap={1}><Text dimColor>Fetching work order #{id}…</Text>{back}</Box>
463      return (
464        <Box flexDirection="column" gap={1}>
465          <Text dimColor>Work order #{id} not loaded yet.</Text>
466          <Box gap={1}>
467            <Button key="load-order" hotkey="l" onPress={() => { void loadOrder($, id); void prefetchPreview($, id, surface) }}>Load</Button>
468            {back}
469          </Box>
470        </Box>
471      )
472    }
473    if (!loaded.ok) {
474      return (
475        <Box flexDirection="column" gap={1}>
476          <Text color="red">#{id}: {loaded.error}</Text>
477          <Box gap={1}>
478            <Button hotkey="r" onPress={() => { orders.delete(id); void loadOrder($, id); void prefetchPreview($, id, surface) }}>Retry</Button>
479            {back}
480          </Box>
481        </Box>
482      )
483    }
484    const wo = loaded.data
485    const row = queue?.ok ? queue.data.find(r => r.id === id) : undefined
486
487    let body
488    switch (current) {
489      case 'fields':
490        body = (
491          <Box flexDirection="column" gap={1}>
492            {wo.fields.map((f: Field) => (
493              <Box flexDirection="column">
494                <Box gap={1}>
495                  <Text bold>{f.name}</Text>
496                  <Text dimColor>→ {f.target}</Text>
497                </Box>
498                <Code source={f.value} />
499                <Box gap={2}>
500                  {f.measured && f.value && f.band[1] !== null && (
501                    <Text color={outOfBand(f) ? 'red' : 'green'}>{meter(f.chars, f.band[1])}</Text>
502                  )}
503                  {f.blocked_reason && <Text color="red">blocked: {f.blocked_reason}</Text>}
504                  {f.unchanged && <Text dimColor>unchanged on the live page</Text>}
505                  <Button plain onPress={copy(f.value, f.name)}>copy</Button>
506                </Box>
507              </Box>
508            ))}
509            {wo.fields.length === 0 && <Text dimColor>No deployable fields found.</Text>}
510          </Box>
511        )
512        break
513      case 'edits':
514        body = (
515          <Box flexDirection="column" gap={1}>
516            {wo.body.paste && (
517              <Box flexDirection="column">
518                <Box gap={2}><Text bold>{wo.body.strategy === 'merge' ? 'BODY (merge into the live article; keep its images and media)' : 'BODY (full page)'}</Text><Button plain onPress={copy(wo.body.html, 'the body')}>copy</Button></Box>
519                <Code source={wo.body.html} language="html" />
520              </Box>
521            )}
522            {wo.edits.length > 0 && <Text dimColor>Apply these {wo.edits.length} edits in place, in the CMS editor, in the order listed. "Find" quotes the page as it reads today; match by meaning.</Text>}
523            {wo.edits.map((ed, i) => {
524              const removes = ed.kind.startsWith('delete')
525              const inserts = ed.kind.startsWith('insert')
526              return (
527                <Box flexDirection="column" borderStyle="round" borderDimColor paddingX={1}>
528                  <Text bold>Edit {i + 1} of {wo.edits.length}: {ed.label}</Text>
529                  {ed.why && <Text dimColor>Why: {ed.why}</Text>}
530                  {ed.where && <Text dimColor>Where: {ed.where}</Text>}
531                  {ed.before_text && <Text>{removes ? 'Remove (current text):' : 'Find:'}</Text>}
532                  {ed.before_text && <Code source={ed.before_text} />}
533                  <Box gap={2}>
534                    <Text>{removes ? 'Replace with: nothing; remove it.' : inserts ? 'Insert:' : 'Replace with:'}</Text>
535                    {ed.after_html && <Button plain onPress={copy(ed.after_html, `edit ${i + 1}`)}>copy</Button>}
536                  </Box>
537                  {ed.after_html && <Code source={ed.after_html} language="html" />}
538                </Box>
539              )
540            })}
541            {wo.edits.length === 0 && !wo.body.paste && <Text dimColor>No body edits in this work order.</Text>}
542          </Box>
543        )
544        break
545      case 'schema':
546        body = wo.structured_data.length ? (
547          <Box flexDirection="column" gap={1}>
548            {wo.structured_data.map((s, i) => (
549              <Box flexDirection="column">
550                <Box gap={2}><Text bold>JSON-LD: {s.schema_type} → inject into &lt;head&gt; (merge into an existing @graph)</Text><Button plain onPress={copy(s.json, `JSON-LD ${i + 1}`)}>copy</Button></Box>
551                <Code source={s.json} language="json" />
552              </Box>
553            ))}
554          </Box>
555        ) : <Text dimColor>No structured data in this work order.</Text>
556        break
557      case 'verify':
558        body = (
559          <Box flexDirection="column">
560            {wo.verify.map((step, i) => (
561              <Button
562                key={`verify-${i}`}
563                plain
564                dimColor={done.includes(i)}
565                label={`${done.includes(i) ? '[x]' : '[ ]'} ${i + 1}. ${step}`}
566                onPress={() => update($, checked, list => done.includes(i) ? (list ?? []).filter(x => x !== i) : [...(list ?? []), i])}
567              />
568            ))}
569            <Text dimColor>{done.length}/{wo.verify.length} checked</Text>
570          </Box>
571        )
572        break
573      case 'notes': {
574        const notes = noteSections(wo)
575        body = (
576          <Box flexDirection="column" gap={1}>
577            {notes.map(text => <Markdown text={text} />)}
578            {notes.length === 0 && <Text dimColor>No notes.</Text>}
579          </Box>
580        )
581        break
582      }
583      case 'preview': {
584        const variant = e.surface === 'terminal' ? 'full' : 'thumb'
585        const key = shotKey(id, pmode, at, variant)
586        const shot = shots.get(key)
587        const modeRow = (
588          <Box gap={1}>
589            <Button hotkey="p" onPress={() => { void (async () => {
590              const next = pmode === 'proposed' ? 'live' : 'proposed'
591              await update($, previewMode, () => next)
592              if (!shots.has(shotKey(id, next, at, variant))) void loadShot($, id, next, at, variant)
593            })() }}>{pmode === 'proposed' ? 'Show live' : 'Show proposed'}</Button>
594            <Button hotkey="r" onPress={() => { for (const k of [...shots.keys()]) if (k.startsWith(`${id}:`)) shots.delete(k); void loadShot($, id, pmode, at, variant, true) }}>Re-render</Button>
595          </Box>
596        )
597        // A page that is not live yet is previewed on a template: a live page of the same
598        // site, its article swapped for this work order's. The server picks the nearest
599        // inventory page unless one is typed here; a new template drops the cached shots.
600        const shownTemplate = shot?.ok ? shot.data.meta.template_url : undefined
601        const notLive = (row ? row.mode !== 'existing' : wo.mode !== 'existing') || Boolean(shownTemplate)
602        const templateRow = notLive && (
603          <Box flexDirection="column">
604            <Text dimColor>Not live yet — shown on a template page of the site{shownTemplate ? `: ${shownTemplate}` : templates.get(id) ? `: ${templates.get(id)}` : ' (the nearest page in the inventory)'}. Type another live URL on the site to use its layout instead:</Text>
605            <Input
606              key="template-url"
607              label="Template URL"
608              placeholder={shownTemplate ?? 'https://…/a-live-page-on-the-site'}
609              submitLabel="Use as template"
610              onSubmit={value => {
611                const url = value.trim()
612                if (url) templates.set(id, url); else templates.delete(id)
613                for (const k of [...shots.keys()]) if (k.startsWith(`${id}:`)) shots.delete(k)
614                void loadShot($, id, pmode, at, variant)
615              }}
616            />
617          </Box>
618        )
619        if (!shot) {
620          body = (
621            <Box flexDirection="column" gap={1}>
622              {inflight.has(key)
623                ? <Text dimColor>Rendering the {pmode} page on the server… (started when the order was opened; a few seconds)</Text>
624                : <Button key="load-preview" hotkey="l" label={`Render ${pmode} preview`} onPress={() => { void loadShot($, id, pmode, at, variant) }} />}
625              {modeRow}
626              {templateRow}
627            </Box>
628          )
629          break
630        }
631        if (!shot.ok) {
632          body = (
633            <Box flexDirection="column" gap={1}>
634              <Text color="red">Preview failed: {shot.error}</Text>
635              {modeRow}
636              {templateRow}
637            </Box>
638          )
639          break
640        }
641        const m = shot.data.meta
642        const n = Math.max(1, m.slices)
643        const i = Math.min(Math.max(0, at), n - 1)
644        const from = i * m.slice_height
645        const sliceH = Math.min(m.slice_height, m.height - from)
646        const columns = Math.max(1, Math.min(255, width))
647        const rows = Math.max(1, Math.min(255, Math.round((columns * sliceH) / m.width / 2)))
648        const caption = `${m.mode} · ${m.width}×${m.height} px · slice ${i + 1}/${n} (${from}–${from + sliceH} px)${m.truncated ? ' · page cut' : ''} · ${Math.round(m.elapsed_ms / 1000)} s`
649        const applied = m.mode === 'proposed' ? `${m.applied_count}/${m.applied.length} ${m.template_url ? 'parts placed' : 'edits applied'}${m.not_found.length ? `, not found: ${m.not_found.length}` : ''}` : ''
650        const nav = (
651          <Box gap={1}>
652            <Button hotkey="u" onPress={() => { void (async () => { const k = Math.max(0, i - 1); await update($, slice, () => k); if (!shots.has(shotKey(id, pmode, k, variant))) void loadShot($, id, pmode, k, variant) })() }}>Up</Button>
653            <Button hotkey="n" onPress={() => { void (async () => { const k = Math.min(n - 1, i + 1); await update($, slice, () => k); if (!shots.has(shotKey(id, pmode, k, variant))) void loadShot($, id, pmode, k, variant) })() }}>Down</Button>
654          </Box>
655        )
656        let picture
657        if (e.surface === 'terminal') {
658          const { Image } = $.ui.resolve(e)
659          picture = <Image source={{ png: shot.data.data }} columns={columns} rows={rows} alt={`[${m.mode} preview slice ${i + 1}/${n}: this terminal cannot draw pixels]`} />
660        } else {
661          const { Svg } = $.ui.resolve(e)
662          const W = 640, H = Math.round((640 * sliceH) / m.width)
663          const svg = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}"><image width="${W}" height="${H}" xlink:href="data:${shot.data.mime};base64,${shot.data.data}"/></svg>`
664          picture = <Svg source={svg} alt={`${m.mode} preview slice ${i + 1} of ${n}`} width={W} height={H} />
665        }
666        body = (
667          <Box flexDirection="column" gap={1}>
668            <Text dimColor wrap="truncate-end">{m.template_url ? `${m.page_url ?? ''} (on template ${m.template_url})` : m.url}</Text>
669            <Text dimColor>{caption}{applied ? ` · ${applied}` : ''}</Text>
670            {picture}
671            {m.view_url && <Link href={m.view_url}>Open this preview as a page</Link>}
672            <Box gap={1}>{nav}{modeRow}</Box>
673            {templateRow}
674          </Box>
675        )
676        break
677      }
678      default:
679        body = (
680          <Box flexDirection="column" gap={1}>
681            <Markdown text={overview(wo)} />
682          </Box>
683        )
684    }
685
686    return (
687      <Box flexDirection="column" gap={1}>
688        <Box flexDirection="column">
689          <Text bold>#{id} · {row ? rowLabel(row) : wo.canonical}</Text>
690          <Text dimColor wrap="truncate-end">{wo.canonical}{row ? ` · v${row.version} · ${row.mode} · ${stateOf(row)}${row.approved_at ? ` by ${row.approved_by || 'someone'}` : ''}` : ''}</Text>
691        </Box>
692        <Box gap={1} flexWrap="wrap">
693          {TABS.map(t => (
694            <Button key={`tab-${t.id}`} hotkey={t.hotkey} variant={t.id === current ? 'primary' : 'secondary'} onPress={() => {
695              if (t.id === 'preview') { const v = e.surface === 'terminal' ? 'full' : 'thumb'; if (!shots.has(shotKey(id, pmode, at, v))) void loadShot($, id, pmode, at, v) }
696              return update($, tab, () => t.id)
697            }}>{t.label}</Button>
698          ))}
699          {back}
700        </Box>
701        {body}
702        <Box flexDirection="column" borderStyle="single" borderDimColor paddingX={1}>
703          <Text dimColor>{row?.approved_at
704            ? `Approved for publishing${row.approved_by ? ` by ${row.approved_by}` : ''}. ${row.pull_request_url ? `In PR ${row.pull_request_url}.` : prHint(id)} An edit makes a new, unapproved version.`
705            : 'Approve once the preview and fields look right; a publishing step reads the stamp. To change the page first, tell Claude what to change — it edits with kg_save_version and the new version appears here.'}</Text>
706          <Box gap={1}>
707            {row?.approved_at
708              ? <Button key="unapprove" hotkey="a" onPress={() => { void setApproval($, id, false) }}>Withdraw approval</Button>
709              : <Button key="approve" hotkey="a" variant="primary" onPress={() => { void setApproval($, id, true) }}>Approve for publishing</Button>}
710          </Box>
711        </Box>
712      </Box>
713    )
714  })
715}
716
hooks/workorder.ts 77 lines
1// The shapes the client MCP server answers with. A work order is kg_fetch_workorder(format="json")
2// (issue #1524): the server builds it from the same work order IR it renders the markdown from,
3// so nothing here reads headings, and a wording change in the document cannot empty a tab.
4
5// band: the rubric's [min, max] characters for the field, null on a side with no limit.
6export type Field = {
7  role: string; name: string; target: string; value: string; chars: number
8  band: [number | null, number | null]; measured: boolean; required: boolean
9  blocked_reason: string; unchanged: boolean
10}
11// kind: replace_paragraph, replace_section, insert_after, insert_section, delete_paragraph,
12// delete_section. before_text is the page's current text, after_html the new HTML ('' on a delete).
13export type Edit = {
14  id: string; kind: string; label: string; heading: string; locator: Record<string, unknown>
15  before_text: string; after_html: string; why: string; where: string
16}
17export type StructuredData = { schema_type: string; script: string; json: string; injection: string; merge_strategy: string }
18export type Recommendation = { label: string; heading: string; reason: string; text: string; suggestion: string }
19export type ContextChange = { fact_id: number; reason: string; sections: string[]; text: string; recheck_due: boolean; recheck_at: string | null }
20export type WorkOrder = {
21  optimization_id: number; version: number; audience: string
22  canonical: string; mode: string; prepared: string
23  blocked: boolean; blocking: { kind: string; subject: string; reason: string }[]
24  keyword: { primary: string; secondaries: string[] }
25  what_changed: string[]
26  fields: Field[]
27  // paste: the html is the page body to deploy; false for a targeted-edits order, whose html is
28  // the resulting article for reading only.
29  body: { strategy: string; html: string; paste: boolean }
30  edits: Edit[]
31  structured_data: StructuredData[]
32  assets: { url: string; alt: string; role: string; disposition: 'upload' | 'preserve' }[]
33  redirect: { from_url: string; to_url: string; status: number } | null
34  recommended: Recommendation[]
35  checked: { label: string; reason: string }[]
36  verify: string[]
37  report_back: { tool: string; optimization_id: number; targets: string[] } | null
38  context_changes: ContextChange[]
39}
40
41export function readWorkOrder(text: string): WorkOrder {
42  const wo = JSON.parse(text) as WorkOrder
43  if (!wo || !Array.isArray(wo.fields) || !Array.isArray(wo.verify)) throw new Error(`not a work order: ${text.slice(0, 120)}`)
44  return wo
45}
46
47export type QueueRow = {
48  // keyword is null for an order made from a URL with no target keyword (Silna #512).
49  id: number; keyword: string | null; page_url: string; slug: string; version: number; mode: string
50  blocked: boolean; blocker_count: number; deployed_at: string | null; deployed_url: string; status: string
51  // The approval stamp (#1518): a person said this version may be published. Per version.
52  approved_at?: string | null; approved_by?: string
53  // The pull request this page was reported in (#1855, kg_pull_request), '' when none.
54  pull_request_url?: string
55}
56
57// What a row is called: its keyword, else the page it changes. Never empty — the desktop
58// table makes it a Button's label, and a Button without one makes the engine refuse the
59// whole pane ("has not drawn in this pane", 2026-10-22).
60export function rowLabel(r: Pick<QueueRow, 'id' | 'keyword' | 'slug' | 'page_url'>): string {
61  return r.keyword || r.slug || r.page_url || `#${r.id}`
62}
63
64// The PR newly approved pages go onto (#1855): one open PR per batch in the client's repo.
65export type OpenPullRequest = { url: string; branch: string; state: string; optimization_ids: number[] }
66
67// kg_* results arrive as a text block holding {"result": <json string or markdown>, "keygrip_tools_version": ...}.
68export function unwrap(blocks: { type: string; text?: string }[]): string {
69  const text = blocks.find(b => b.type === 'text')?.text ?? ''
70  try {
71    const outer = JSON.parse(text) as { result?: unknown }
72    if (typeof outer.result === 'string') return outer.result
73    if (outer.result !== undefined) return JSON.stringify(outer.result)
74  } catch { /* the text is the result itself */ }
75  return text
76}
77
types/index.d.ts 18 lines
1export type Tab = 'overview' | 'fields' | 'edits' | 'schema' | 'verify' | 'notes' | 'preview'
2
3declare module 'claude-code' {
4  interface PluginState {
5    'workorder-pane': {
6      view: 'queue' | 'order'
7      selected: number | null
8      tab: Tab
9      includeSuperseded: boolean
10      checked: number[]
11      tick: number
12      slice: number
13      keyPrompt: boolean
14      previewMode: 'live' | 'proposed'
15    }
16  }
17}
18