# Code editor

A code editor beside the chat for a query, a formula or a JSON payload the user and the agent write together. It highlights and checks the code as it changes, marks the lines the agent edits, and runs a preview through your app.

{/* Generated by scripts/build-ui-catalog.mjs from src/ui-catalog/. Do not edit. */}

A code editor beside the chat for a query, a formula or a JSON payload the user and the agent write together. It highlights and checks the code as it changes, marks the lines the agent edits, and runs a preview through your app.

## When to use it

**Use it when:** A query, a formula, a script or a config the user and the agent write together: a SQL report, a filter formula, a webhook payload. The agent writes it into the editor, keeps it valid, and the user runs a preview before your app saves it.

**Use something else when:** A snippet the agent shows once and the user copies (a chat message with a code block). Settings with fixed choices (form canvas). Mobile: the canvas isn't available; use the snippet card (mountMobile).

## What the agent receives

| The template calls | The agent gets | When |
| --- | --- | --- |
| `canvas.setState({ code })` | `Canvas state` | 600 ms after the user stops typing, and on blur. The agent edits the same field and sends it whole. |
| `canvas.setState({ lastRun })` | `Canvas state` | After each run: ok, the row count or the error, so the agent can fix what failed. |
| `displayed()` | `FUNCTION_TOOL_DISPLAYED` | Mobile snippet card: as soon as it shows. |

## States

Besides its data, the template draws these as itself, with `mountState()`. Pick one on the preview with **State**.

| State | When it shows |
| --- | --- |
| Loading | While execute loads the saved query, or the agent's first draft, into the editor. The skeleton has the editor's shape. |
| Empty | There's no code to show yet, for example a saved query that was deleted. The agent offers to write one. |
| Error | execute couldn't load the query or the schema. Nothing changed; Try again loads it in place. |

```ts
mountState({ root, head, title: "…", state: { kind: "error", text: "…", retry } });
```

The hosted action and the in-page handler below show each case. The state types are `LoadingState`, `EmptyState` and `ErrorState` in fs-kit.

## Data

### CodeCanvasState

| Field | Type | Notes |
| --- | --- | --- |
| `canvasTitle` (optional) | `string` | The canvas header (setTitle, up to 80 characters). Default: title. |
| `title` | `string` | What the code does, e.g. "Churned accounts last quarter". |
| `intro` (optional) | `string` | One line under the title. |
| `language` | `CodeLanguage` | Highlighting and the built-in check: sql, json, formula or text. |
| `code` | `string` | The code. The user and the agent both write here; the agent sends it whole and keeps it valid. |
| `runLabel` (optional) | `string` | The Run button. Default: "Run". |
| `lastRun` (optional) | `CodeCanvasRun` | Set by the canvas after each run, so the agent sees whether it worked. |

### CodeCanvasRun

| Field | Type | Notes |
| --- | --- | --- |
| `ok` | `boolean` | Whether it ran. |
| `at` | `string` | When (ISO 8601). |
| `rows` (optional) | `number` | Rows returned. |
| `error` (optional) | `string` | What failed, as your run() threw it. |

### CodeCanvasResult

| Field | Type | Notes |
| --- | --- | --- |
| `columns` (optional) | `string[]` | Column names. |
| `rows` (optional) | `(string \| number \| boolean \| null)[][]` | Up to about 50 rows; one value per column. |
| `output` (optional) | `string` | Plain output instead of rows, e.g. a webhook's response. |
| `note` (optional) | `string` | A note beside the result, e.g. "First 50 of 1,204 rows". |

### CodeCanvasProblem

| Field | Type | Notes |
| --- | --- | --- |
| `message` | `string` | What to fix, in plain words. |
| `line` (optional) | `number` | 1-based line. |

### CodeCanvasActions

| Field | Type | Notes |
| --- | --- | --- |
| `run()` (optional) | `(code: string, language: CodeLanguage) => Promise<CodeCanvasResult>` | Runs a preview through your app. Throw to show the error; put "line N" in the message to point at a line. |
| `validate()` (optional) | `(code: string, language: CodeLanguage) => CodeCanvasProblem \| null \| Promise<CodeCanvasProblem \| null>` | Your own check (a parser, a dry run). Return null when it's valid. Default: the built-in check for the language. |
| `save()` (optional) | `(code: string) => Promise<void>` | Saves the code in your app, e.g. as a saved report. Shows a Save button. Throw to show why it wasn't saved. |
| `onChange()` (optional) | `(state: CodeCanvasState) => void` | Called each time the code is shared with the agent (debounced). |

## Install

Copy the template and the shared kit into your code: `agent/ui/` in an agent repo, or anywhere in your app. The template imports only `./fs-kit.js`. Then wire it up from the hosted action or the in-page handler.

- Hosted action: [TypeScript](/ui-catalog/files/ts/usage/code-canvas.hosted.ts), [JavaScript](/ui-catalog/files/js/usage/code-canvas.hosted.js)
- In-page handler: [TypeScript](/ui-catalog/files/ts/usage/code-canvas.canvas.ts), [JavaScript](/ui-catalog/files/js/usage/code-canvas.canvas.js)
- code-canvas: [TypeScript](/ui-catalog/files/ts/code-canvas.ts), [JavaScript](/ui-catalog/files/js/code-canvas.js)
- fs-kit: [TypeScript](/ui-catalog/files/ts/fs-kit.ts), [JavaScript](/ui-catalog/files/js/fs-kit.js)

The hosted action needs an agent repo with one folder per action (`agent/actions/<action_key>/index.ts`). If your repo keeps its actions in `agent/actions/index.ts`, use the in-page handler: it runs the same template in your app.

All templates in machine-readable form: [/ui-catalog/catalog.json](/ui-catalog/catalog.json).

## Code

### Hosted action

```ts title="agent/actions/write_report_query/index.ts"
// agent/actions/write_report_query/index.ts: a hosted canvas action (desktop).
// Copy the template (code-canvas.ts) and fs-kit.ts into agent/ui/.

type Result = CodeCanvasState | { error: string };

// The canvas's first state: a saved query, or an empty one the agent drafts on its next turn (in the code field, not the chat).
export async function execute(args: { reportId?: string; title?: string }, ctx: ActionContext): Promise<Result> {
  if (!args.reportId) return { title: args.title ?? "New query", language: "sql", code: "", runLabel: "Run query" };
  const res = await ctx.fetch(`/api/reports/${encodeURIComponent(args.reportId)}`);
  if (!res.ok) return { error: `The saved query didn't load (${res.status}). Nothing changed.` };
  const report = await res.json();
  return { title: report.name, language: "sql", code: report.sql, runLabel: "Run query" };
}

export function renderCanvas(ctx: CanvasActionContext) {
  const canvas = liveCanvas(ctx.canvas); // canvas.state follows your setState calls and the agent's edits
  // CODE: the agent writes a query with the user, keeps it valid and complete, and puts it in the code field, not the chat.
  canvas.setType("CODE");
  canvas.setStatus("EDIT_MODE"); // the user and the agent both write
  const state = canvas.state as Result;
  if ("error" in state) {
    return mountState({ root: canvas.root, head: canvas.head, canvas, title: "Report query", state: { kind: "error", text: state.error } });
  }
  return mount({
    root: canvas.root, head: canvas.head, canvas,
    actions: {
      // A read-only preview: your API runs it with a row limit and a timeout. Throw with "line N" to point at a line.
      run: async (code) => {
        const res = await ctx.fetch("/api/reports/preview", { method: "POST", body: JSON.stringify({ sql: code, limit: 50 }), headers: { "content-type": "application/json" } });
        const body = await res.json();
        if (!res.ok) throw new Error(body.message ?? "The query didn't run. Nothing changed.");
        return { columns: body.columns, rows: body.rows, note: body.total > 50 ? `First 50 of ${body.total.toLocaleString()}` : undefined };
      },
      save: async (code) => {
        const res = await ctx.fetch("/api/reports", { method: "POST", body: JSON.stringify({ name: state.title, sql: code }), headers: { "content-type": "application/json" } });
        if (!res.ok) throw new Error("The query wasn't saved. Your code is kept. Try again.");
      },
    },
  });
}
```

```js title="agent/actions/write_report_query/index.js"
// agent/actions/write_report_query/index.js: a hosted canvas action (desktop).
// Copy the template (code-canvas.ts) and fs-kit.ts into agent/ui/.

// The canvas's first state: a saved query, or an empty one the agent drafts on its next turn (in the code field, not the chat).
export async function execute(args, ctx) {
  if (!args.reportId) return { title: args.title ?? "New query", language: "sql", code: "", runLabel: "Run query" };
  const res = await ctx.fetch(`/api/reports/${encodeURIComponent(args.reportId)}`);
  if (!res.ok) return { error: `The saved query didn't load (${res.status}). Nothing changed.` };
  const report = await res.json();
  return { title: report.name, language: "sql", code: report.sql, runLabel: "Run query" };
}

export function renderCanvas(ctx) {
  const canvas = liveCanvas(ctx.canvas); // canvas.state follows your setState calls and the agent's edits
  // CODE: the agent writes a query with the user, keeps it valid and complete, and puts it in the code field, not the chat.
  canvas.setType("CODE");
  canvas.setStatus("EDIT_MODE"); // the user and the agent both write
  const state = canvas.state;
  if ("error" in state) {
    return mountState({ root: canvas.root, head: canvas.head, canvas, title: "Report query", state: { kind: "error", text: state.error } });
  }
  return mount({
    root: canvas.root, head: canvas.head, canvas,
    actions: {
      // A read-only preview: your API runs it with a row limit and a timeout. Throw with "line N" to point at a line.
      run: async (code) => {
        const res = await ctx.fetch("/api/reports/preview", { method: "POST", body: JSON.stringify({ sql: code, limit: 50 }), headers: { "content-type": "application/json" } });
        const body = await res.json();
        if (!res.ok) throw new Error(body.message ?? "The query didn't run. Nothing changed.");
        return { columns: body.columns, rows: body.rows, note: body.total > 50 ? `First 50 of ${body.total.toLocaleString()}` : undefined };
      },
      save: async (code) => {
        const res = await ctx.fetch("/api/reports", { method: "POST", body: JSON.stringify({ name: state.title, sql: code }), headers: { "content-type": "application/json" } });
        if (!res.ok) throw new Error("The query wasn't saved. Your code is kept. Try again.");
      },
    },
  });
}
```

### In-page handler

```ts title="in-page handler.ts"
// An in-page canvas action (desktop). The SDK leaves canvas actions out on mobile,
// so mobile gets the snippet card below.

foldspace("when", "ready", () => {
  foldspace.agent({ /* …common setup… */ }).addActionHandlers({
    edit_webhook_payload: {
      // { title, language, code }: the agent writes into code, in the state, on its next turn.
      execute: async ({ hookId }: { hookId: string }): Promise<CodeCanvasState> => ({
        title: "Order shipped webhook",
        language: "json",
        code: JSON.stringify(await myApi.webhookTemplate(hookId), null, 2),
        runLabel: "Send test",
      }),

      renderCanvas: (sdk: CanvasContext) => {
        const ctx = liveCanvas(sdk); // ctx.state follows your setState calls and the agent's edits
        ctx.setType("CODE");
        ctx.setStatus("EDIT_MODE"); // the user and the agent both write
        return mount({
          root: ctx.host, head: ctx.header, canvas: ctx,
          actions: {
            // Your own check on top of JSON syntax: return { message, line } or null.
            validate: (code) => myApi.checkPayload(code),
            // Sends a test delivery and shows the response. Throw to show why it failed.
            run: async (code) => ({ output: await myApi.sendTestWebhook(JSON.parse(code)) }),
            save: (code) => myApi.saveWebhookTemplate(JSON.parse(code)),
          },
        });
      },
    },

    // Mobile: a read-only snippet of the same state.
    show_webhook_payload: {
      execute: async ({ hookId }: { hookId: string }): Promise<CodeCanvasState> => ({
        title: "Order shipped webhook", language: "json", code: JSON.stringify(await myApi.webhookTemplate(hookId), null, 2),
      }),
      renderComponent: ({ data, host, header, readyState }: ComponentContext<CodeCanvasState>) =>
        mountMobile({ root: host, head: header, data, api: { displayed: () => readyState(data) } }),
    },
  });
});
```

```js title="in-page handler.js"
// An in-page canvas action (desktop). The SDK leaves canvas actions out on mobile,
// so mobile gets the snippet card below.

foldspace("when", "ready", () => {
  foldspace.agent({ /* …common setup… */ }).addActionHandlers({
    edit_webhook_payload: {
      // { title, language, code }: the agent writes into code, in the state, on its next turn.
      execute: async ({ hookId }) => ({
        title: "Order shipped webhook",
        language: "json",
        code: JSON.stringify(await myApi.webhookTemplate(hookId), null, 2),
        runLabel: "Send test",
      }),

      renderCanvas: (sdk) => {
        const ctx = liveCanvas(sdk); // ctx.state follows your setState calls and the agent's edits
        ctx.setType("CODE");
        ctx.setStatus("EDIT_MODE"); // the user and the agent both write
        return mount({
          root: ctx.host, head: ctx.header, canvas: ctx,
          actions: {
            // Your own check on top of JSON syntax: return { message, line } or null.
            validate: (code) => myApi.checkPayload(code),
            // Sends a test delivery and shows the response. Throw to show why it failed.
            run: async (code) => ({ output: await myApi.sendTestWebhook(JSON.parse(code)) }),
            save: (code) => myApi.saveWebhookTemplate(JSON.parse(code)),
          },
        });
      },
    },

    // Mobile: a read-only snippet of the same state.
    show_webhook_payload: {
      execute: async ({ hookId }) => ({
        title: "Order shipped webhook", language: "json", code: JSON.stringify(await myApi.webhookTemplate(hookId), null, 2),
      }),
      renderComponent: ({ data, host, header, readyState }) =>
        mountMobile({ root: host, head: header, data, api: { displayed: () => readyState(data) } }),
    },
  });
});
```

### code-canvas

```ts title="agent/ui/code-canvas.ts"
// Template: code-canvas. A CODE canvas where the user and the agent write a query, a formula or a JSON payload together (desktop), plus its mobile snippet card.

export const meta = {
  id: "code-canvas",
  title: "Code editor",
  surface: "canvas",
  canvasType: "CODE",
  canvasStatus: "EDIT_MODE",
  kind: "interactive",
  mobile: "fallback-card",
  whenToUse: "A query, a formula, a script or a config the user and the agent write together: a SQL report, a filter formula, a webhook payload. The agent writes it into the editor, keeps it valid, and the user runs a preview before your app saves it.",
  whenNotToUse: "A snippet the agent shows once and the user copies (a chat message with a code block). Settings with fixed choices (form canvas). Mobile: the canvas isn't available; use the snippet card (mountMobile).",
};

const CSS = `
.fsk-cd { container: fsk-cd / inline-size; height: 100%; min-height: 460px; display: flex; flex-direction: column; gap: 12px; padding: 14px 20px 16px; background: var(--k-paper); }
.fsk-cd-top { flex: none; display: flex; align-items: flex-end; gap: 12px; }
.fsk-cd-top > div:first-child { flex: 1; min-width: 0; }
.fsk-cd-badges { display: flex; align-items: center; gap: 6px; }
.fsk-cd-lang { padding: 1px 7px; border-radius: var(--k-r); border: 1px solid var(--k-border); font: 600 .72em/1.6 var(--k-mono); letter-spacing: .04em; color: var(--k-text-2); text-transform: uppercase; }
.fsk-cd-title { margin: 8px 0 2px; font-size: 1.25em; font-weight: 650; letter-spacing: -0.02em; line-height: 1.25; }
.fsk-cd-intro { margin: 0; color: var(--k-text-2); font-size: .93em; max-width: 64ch; }
.fsk-cd-actions { flex: none; display: flex; align-items: center; gap: 8px; }
.fsk-cd-kbd { padding: 0 5px; margin-left: 2px; border-radius: var(--k-r); background: color-mix(in srgb, var(--k-on-primary) 18%, transparent); font: 500 .79em/1.5 var(--k-mono); }

/* The editor */
.fsk-cd-box { position: relative; flex: 1 1 0; min-height: 200px; display: flex; flex-direction: column; overflow: hidden;
  border: 1px solid var(--k-border); border-radius: var(--k-r-lg); background: var(--k-sunken); transition: border-color .15s, box-shadow .15s; }
.fsk-cd-box:focus-within { border-color: color-mix(in srgb, var(--k-primary) 55%, var(--k-border)); box-shadow: 0 0 0 3px color-mix(in srgb, var(--k-primary) 14%, transparent); }
.fsk-cd-box[data-bad] { border-color: color-mix(in srgb, var(--k-error) 50%, var(--k-border)); }
.fsk-cd-note { flex: none; display: flex; align-items: center; flex-wrap: wrap; gap: 4px 10px; padding: 7px 10px 7px 12px; font-size: .86em;
  background: var(--k-tint); color: var(--k-text); border-bottom: 1px solid color-mix(in srgb, var(--k-primary) 22%, var(--k-paper)); animation: fsk-in .25s var(--k-ease) both; }
.fsk-cd-note > .fsk-icon { color: var(--k-primary); }
.fsk-cd-note > span { flex: 1; min-width: 160px; }
.fsk-cd-note b { font-weight: 600; }
.fsk-cd-link { appearance: none; display: inline-flex; align-items: center; gap: 4px; min-height: 26px; padding: 0 8px; border: 0; border-radius: var(--k-r);
  background: transparent; color: var(--k-primary); font: inherit; font-weight: 600; cursor: pointer; white-space: nowrap; }
.fsk-cd-link:hover { background: var(--k-tint-2); }
.fsk-cd-link:focus-visible, .fsk-cd-problem:focus-visible { outline: 2px solid var(--k-primary); outline-offset: 1px; }
.fsk-cd-scroll { position: relative; flex: 1; min-height: 0; overflow: auto; overscroll-behavior: contain; }
.fsk-cd-code { display: grid; grid-template-columns: auto minmax(0, 1fr); min-width: max-content; min-height: 100%;
  font-family: var(--k-mono); font-size: .9em; line-height: 1.6; tab-size: 2; }
.fsk-cd-gutter { position: sticky; left: 0; z-index: 2; padding: 12px 0; min-width: 44px; text-align: right; user-select: none;
  color: color-mix(in srgb, var(--k-text-2) 75%, transparent); background: var(--k-sunken); border-right: 1px solid var(--k-muted-border); font-variant-numeric: tabular-nums; }
.fsk-cd-gutter > div { position: relative; height: 1.6em; padding: 0 12px 0 14px; }
.fsk-cd-gutter > .fsk-cd-g--cur { color: var(--k-text); }
.fsk-cd-gutter > .fsk-cd-g--ai::before { content: ""; position: absolute; left: 4px; top: 2px; bottom: 2px; width: 3px; border-radius: 2px; background: var(--k-primary); }
.fsk-cd-gutter > .fsk-cd-g--bad { color: var(--k-error); font-weight: 700; }
.fsk-cd-gutter > .fsk-cd-g--bad::after { content: "!"; position: absolute; left: 3px; font-weight: 700; }
.fsk-cd-ed { position: relative; display: grid; min-width: 0; }
.fsk-cd-hl, .fsk-cd-ta { grid-area: 1 / 1; margin: 0; padding: 12px 24px 12px 12px; border: 0; font: inherit; line-height: inherit; letter-spacing: 0; tab-size: inherit;
  white-space: pre; overflow-wrap: normal; word-break: normal; }
.fsk-cd-hl { pointer-events: none; color: var(--k-text); min-height: 100%; }
.fsk-cd-hl > div { min-height: 1.6em; margin: 0 -24px 0 -12px; padding: 0 24px 0 12px; }
.fsk-cd-hl > .fsk-cd-l--ai { background: color-mix(in srgb, var(--k-primary) 10%, var(--k-sunken)); }
.fsk-cd-hl > .fsk-cd-l--bad { background: color-mix(in srgb, var(--k-error) 9%, var(--k-sunken)); }
.fsk-cd-flash { animation: fsk-cd-flash 1.6s var(--k-ease); }
.fsk-cd-ta { display: block; width: 100%; height: 100%; min-height: 100%; resize: none; overflow: hidden; outline: none; background: transparent;
  color: transparent; -webkit-text-fill-color: transparent; caret-color: var(--k-text); }
.fsk-cd-ta::selection { background: color-mix(in srgb, var(--k-primary) 28%, transparent); }
.fsk-cd-ta::placeholder { -webkit-text-fill-color: var(--k-text-2); color: var(--k-text-2); }
.fsk-cd-ta[readonly] { caret-color: transparent; }
/* Tokens: one hue (the theme's primary) plus text weights, so any theme reads */
.fsk-cd-t-kw { color: var(--k-primary); font-weight: 600; }
.fsk-cd-t-fn { color: color-mix(in srgb, var(--k-primary) 62%, var(--k-text)); }
.fsk-cd-t-str { color: var(--k-success); }
.fsk-cd-t-num, .fsk-cd-t-lit { color: var(--k-warning); }
.fsk-cd-t-key { color: color-mix(in srgb, var(--k-primary) 70%, var(--k-text)); }
.fsk-cd-t-com { color: var(--k-text-2); font-style: italic; }
.fsk-cd-t-op, .fsk-cd-t-punc { color: var(--k-text-2); }
.fsk-cd-t-err { text-decoration: underline wavy var(--k-error); text-decoration-skip-ink: none; text-underline-offset: 3px; }

/* Diff view */
.fsk-cd-diff { padding: 10px 0; font-family: var(--k-mono); font-size: .9em; line-height: 1.6; }
.fsk-cd-diff > div { display: grid; grid-template-columns: 32px 32px 18px 1fr; white-space: pre; padding-right: 16px; }
.fsk-cd-diff span { color: var(--k-text-2); text-align: right; padding-right: 8px; user-select: none; }
.fsk-cd-diff span:nth-child(3) { text-align: center; padding: 0; font-weight: 700; }
.fsk-cd-diff .fsk-cd-d--add { background: color-mix(in srgb, var(--k-primary) 11%, var(--k-sunken)); }
.fsk-cd-diff .fsk-cd-d--add span:nth-child(3) { color: var(--k-primary); }
.fsk-cd-diff .fsk-cd-d--del { background: color-mix(in srgb, var(--k-error) 9%, var(--k-sunken)); color: var(--k-text-2); }
.fsk-cd-diff .fsk-cd-d--del span:nth-child(3) { color: var(--k-error); }

/* Status bar */
.fsk-cd-status { flex: none; display: flex; align-items: center; gap: 12px; min-height: 32px; padding: 4px 8px 4px 12px; font-size: .79em; color: var(--k-text-2);
  border-top: 1px solid var(--k-muted-border); background: var(--k-paper); }
.fsk-cd-status > span { white-space: nowrap; }
.fsk-cd-pos { font-variant-numeric: tabular-nums; }
.fsk-cd-hint { overflow: hidden; text-overflow: ellipsis; }
.fsk-cd-problem { appearance: none; display: inline-flex; align-items: center; gap: 5px; min-height: 24px; margin-left: auto; padding: 0 8px; border: 0; border-radius: var(--k-r);
  background: none; font: inherit; font-weight: 600; white-space: nowrap; cursor: default; color: var(--k-success); }
.fsk-cd-problem[data-bad] { cursor: pointer; color: var(--k-error); background: color-mix(in srgb, var(--k-error) 10%, var(--k-paper)); }
.fsk-cd-problem[data-bad] > span { overflow: hidden; text-overflow: ellipsis; max-width: 36ch; }
.fsk-cd-problem[data-busy] { color: var(--k-text-2); font-weight: 500; }
.fsk-cd-share { display: inline-flex; align-items: center; gap: 5px; }
.fsk-cd-share[data-s="saved"] .fsk-icon { color: var(--k-success); }
.fsk-cd-share[data-s="partial"] .fsk-icon { color: var(--k-warning); }
.fsk-cd-share[data-s="error"] { color: var(--k-error); }
.fsk-cd-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--k-primary); animation: fsk-cd-pulse 1.1s ease-in-out infinite; }

/* Results */
.fsk-cd-res { flex: 0 0 34%; min-height: 140px; display: flex; flex-direction: column; overflow: hidden; border: 1px solid var(--k-border); border-radius: var(--k-r-lg); background: var(--k-paper); }
.fsk-cd-res-head { flex: none; display: flex; align-items: center; gap: 10px; min-height: 38px; padding: 0 12px; border-bottom: 1px solid var(--k-divider); font-size: .86em; }
.fsk-cd-res-head h3 { margin: 0; font-size: 1em; font-weight: 600; }
.fsk-cd-res-meta { display: inline-flex; align-items: center; gap: 6px; color: var(--k-text-2); }
.fsk-cd-res-meta[data-ok] .fsk-icon { color: var(--k-success); }
.fsk-cd-res-meta[data-bad] { color: var(--k-error); }
.fsk-cd-stale { margin-left: auto; display: inline-flex; align-items: center; gap: 4px; color: var(--k-text-2); font-size: .93em; }
.fsk-cd-res-body { flex: 1; min-height: 0; overflow: auto; }
.fsk-cd-res table { width: 100%; border-collapse: separate; border-spacing: 0; font-size: .86em; }
.fsk-cd-res th { position: sticky; top: 0; z-index: 1; padding: 0 12px; height: 32px; text-align: left; font-weight: 500; color: var(--k-text-2); white-space: nowrap;
  background: var(--k-sunken); border-bottom: 1px solid var(--k-divider); font-family: var(--k-mono); font-size: .93em; }
.fsk-cd-res td { padding: 0 12px; height: 32px; border-bottom: 1px solid var(--k-divider); white-space: nowrap; max-width: 280px; overflow: hidden; text-overflow: ellipsis; }
.fsk-cd-res td.fsk-cd-numc, .fsk-cd-res th.fsk-cd-numc { text-align: right; font-variant-numeric: tabular-nums; }
.fsk-cd-res td.fsk-cd-null { color: var(--k-text-2); font-style: italic; }
.fsk-cd-res tbody tr:hover td { background: var(--k-sunken); }
.fsk-cd-out { margin: 0; padding: 12px; font: .86em/1.6 var(--k-mono); white-space: pre-wrap; overflow-wrap: anywhere; }
.fsk-cd-res-empty { height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px; padding: 16px; text-align: center; color: var(--k-text-2); font-size: .93em; }
.fsk-cd-res-empty .fsk-icon { color: var(--k-text-2); }
.fsk-cd-res-empty kbd { padding: 0 5px; border-radius: var(--k-r); border: 1px solid var(--k-border); border-bottom-width: 2px; font: 500 .9em/1.5 var(--k-mono); color: var(--k-text); }
.fsk-cd-res-err { display: flex; gap: 10px; align-items: flex-start; padding: 14px; font-size: .93em; }
.fsk-cd-res-err > .fsk-icon { color: var(--k-error); margin-top: 2px; }
.fsk-cd-res-err p { margin: 0 0 8px; }
.fsk-cd-res-err pre { margin: 0 0 10px; padding: 8px 10px; border-radius: var(--k-r-md); background: var(--k-sunken); font: .93em/1.5 var(--k-mono); white-space: pre-wrap; color: var(--k-text-2); }
.fsk-cd-res-skel { display: flex; flex-direction: column; gap: 12px; padding: 14px 12px; }

/* States in the panel */
.fsk-cd-center { flex: 1; display: grid; place-items: center; padding: 24px; }
.fsk-cd-center > div { width: 100%; max-width: 420px; }
.fsk-cd-skel { display: flex; flex: 1; gap: 14px; padding: 12px; }
.fsk-cd-skel-g { display: flex; flex-direction: column; gap: 12px; width: 18px; }
.fsk-cd-skel-l { flex: 1; display: flex; flex-direction: column; gap: 12px; }

@keyframes fsk-cd-flash { 0%, 30% { background-color: color-mix(in srgb, var(--k-primary) 22%, var(--k-sunken)); } }
@keyframes fsk-cd-pulse { 50% { opacity: .35; transform: scale(.75); } }
@container fsk-cd (max-width: 560px) {
  .fsk-cd { padding: 12px 14px 14px; }
  .fsk-cd-hint, .fsk-cd-long { display: none; }
}
@media (prefers-reduced-motion: reduce) { .fsk-cd-flash { animation: none; } }

/* Mobile snippet card */
.fsk-cdm .fsk-cdm-code { position: relative; max-height: 220px; overflow: hidden; margin: 0; padding: 10px 12px; border-radius: var(--k-r-md); background: var(--k-sunken);
  border: 1px solid var(--k-muted-border); font: .79em/1.6 var(--k-mono); white-space: pre; }
.fsk-cdm .fsk-cdm-code::after { content: ""; position: absolute; left: 0; right: 0; bottom: 0; height: 48px; background: linear-gradient(to bottom, transparent, var(--k-sunken)); }
.fsk-cdm .fsk-cdm-code > div { min-height: 1.6em; }
.fsk-cdm-row { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 12px; margin: 10px 0 0; font-size: .86em; color: var(--k-text-2); }
.fsk-cdm-row > span { display: inline-flex; align-items: center; gap: 5px; }
.fsk-cdm-ok .fsk-icon { color: var(--k-success); }
.fsk-cdm-bad { color: var(--k-error); }
.fsk-cdm-desk { display: flex; gap: 10px; align-items: flex-start; margin: 12px 0 0; padding: 12px; border-radius: var(--k-r-md); background: var(--k-sunken); font-size: .93em; }
.fsk-cdm-desk .fsk-icon { color: var(--k-primary); margin-top: 2px; }
.fsk-cdm-desk strong { display: block; font-weight: 600; }
.fsk-cdm-desk span { color: var(--k-text-2); }
`;

export type CodeLanguage = "sql" | "json" | "formula" | "text";

/** The canvas state the agent reads and edits. Keep the code under about 2.5 KB. */
export interface CodeCanvasState {
  /** The canvas header (setTitle, up to 80 characters). Default: title. */
  canvasTitle?: string;
  /** What the code does, e.g. "Churned accounts last quarter". */
  title: string;
  /** One line under the title. */
  intro?: string;
  /** Highlighting and the built-in check: sql, json, formula or text. */
  language: CodeLanguage;
  /** The code. The user and the agent both write here; the agent sends it whole and keeps it valid. */
  code: string;
  /** The Run button. Default: "Run". */
  runLabel?: string;
  /** Set by the canvas after each run, so the agent sees whether it worked. */
  lastRun?: CodeCanvasRun;
}

export interface CodeCanvasRun {
  /** Whether it ran. */
  ok: boolean;
  /** When (ISO 8601). */
  at: string;
  /** Rows returned. */
  rows?: number;
  /** What failed, as your run() threw it. */
  error?: string;
}

/** What actions.run returns: rows for a table, or output text. */
export interface CodeCanvasResult {
  /** Column names. */
  columns?: string[];
  /** Up to about 50 rows; one value per column. */
  rows?: (string | number | boolean | null)[][];
  /** Plain output instead of rows, e.g. a webhook's response. */
  output?: string;
  /** A note beside the result, e.g. "First 50 of 1,204 rows". */
  note?: string;
}

/** A problem in the code: what's wrong, and on which line. */
export interface CodeCanvasProblem {
  /** What to fix, in plain words. */
  message: string;
  /** 1-based line. */
  line?: number;
}

export interface CodeCanvasActions {
  /** Runs a preview through your app. Throw to show the error; put "line N" in the message to point at a line. */
  run?(code: string, language: CodeLanguage): Promise<CodeCanvasResult>;
  /** Your own check (a parser, a dry run). Return null when it's valid. Default: the built-in check for the language. */
  validate?(code: string, language: CodeLanguage): CodeCanvasProblem | null | Promise<CodeCanvasProblem | null>;
  /** Saves the code in your app, e.g. as a saved report. Shows a Save button. Throw to show why it wasn't saved. */
  save?(code: string): Promise<void>;
  /** Called each time the code is shared with the agent (debounced). */
  onChange?(state: CodeCanvasState): void;
}

export interface CodeCanvasProps {
  root: HTMLElement;
  head: StyleHost;
  /** The canvas: the in-page renderCanvas ctx or a hosted ctx.canvas. Its state wins over data. */
  canvas?: CanvasApi;
  data?: CodeCanvasState;
  actions?: CodeCanvasActions;
}

export interface CodeCanvasCardProps {
  root: HTMLElement;
  head: StyleHost;
  data: CodeCanvasState;
  api?: CardApi;
}

export interface CodeCanvasStateProps extends StateProps {
  /** Desktop: the canvas, so the header shows the title. */
  canvas?: Pick<CanvasApi, "setTitle">;
}

// ---------- tokenizing (text nodes only: user code is never parsed as HTML) ----------

type Tok = [kind: string, text: string];
const SQL_KW = new Set(("select from where and or not in is null as join left right inner outer full cross on using group by order having limit offset distinct " +
  "case when then else end union all insert into values update set delete with asc desc between like ilike exists interval true false returning over partition " +
  "window filter lateral natural nulls first last any some cast").split(" "));
const FORMULA_KW = new Set(["AND", "OR", "NOT", "TRUE", "FALSE", "IF", "BLANK"]);
const LANG_LABEL: Record<CodeLanguage, string> = { sql: "SQL", json: "JSON", formula: "Formula", text: "Text" };
const OPEN = "([{", CLOSE = ")]}";

function nextNonSpace(src: string, from: number): string {
  const m = /\S/.exec(src.slice(from, from + 64));
  return m ? m[0] : "";
}

export function tokenize(src: string, lang: CodeLanguage): Tok[] {
  const out: Tok[] = [];
  if (lang === "text") return [["plain", src]];
  const re = lang === "sql"
    ? /(--[^\n]*|\/\*[\s\S]*?(?:\*\/|$))|('(?:[^'\\]|\\.|'')*'?)|("(?:[^"\\\n]|\\.)*"?)|(\b\d+(?:\.\d+)?\b)|([A-Za-z_][\w$]*)|(\s+)|([\s\S])/g
    : lang === "json"
      ? /(\/\/[^\n]*)|("(?:[^"\\\n]|\\.)*"?)|()(-?\b\d+(?:\.\d+)?(?:[eE][+-]?\d+)?\b)|\b(true|false|null)\b|(\s+)|([\s\S])/g
      : /(\/\/[^\n]*)|("(?:[^"\\\n]|\\.)*"?)|(\{[^}\n]*\}?)|(\b\d+(?:\.\d+)?\b)|([A-Za-z_][\w.]*)|(\s+)|([\s\S])/g;
  let m: RegExpExecArray | null;
  while ((m = re.exec(src))) {
    const [t, com, str, third, num, word, space] = m;
    const after = re.lastIndex;
    if (com) out.push(["com", t]);
    else if (str) out.push([lang === "json" && nextNonSpace(src, after) === ":" ? "key" : "str", t]);
    else if (third) out.push(["key", t]); // SQL "quoted identifier", formula {Field}
    else if (num) out.push(["num", t]);
    else if (word) {
      if (lang === "json") out.push(["lit", t]);
      else if (nextNonSpace(src, after) === "(") out.push(["fn", t]);
      else if (lang === "sql" ? SQL_KW.has(t.toLowerCase()) : FORMULA_KW.has(t.toUpperCase())) out.push(["kw", t]);
      else out.push(["id", t]);
    } else if (space) out.push(["plain", t]);
    else out.push([/[(),.;:[\]{}]/.test(t) ? "punc" : "op", t]);
  }
  return out;
}

/** Tokens split into lines, so each line can carry its own mark. */
function toLines(toks: Tok[]): Tok[][] {
  const lines: Tok[][] = [[]];
  for (const [k, t] of toks) {
    const parts = t.split("\n");
    parts.forEach((p, i) => {
      if (i > 0) lines.push([]);
      if (p) lines[lines.length - 1].push([k, p]);
    });
  }
  return lines;
}

function lineEls(code: string, lang: CodeLanguage): HTMLElement[] {
  return toLines(tokenize(code, lang)).map((toks) => h("div", {},
    toks.map(([k, t]) => (k === "plain" || k === "id" ? t : h("span", { class: `fsk-cd-t-${k}` }, t)))));
}

// ---------- the built-in checks ----------

const lineAt = (src: string, i: number): number => src.slice(0, i).split("\n").length;

function checkBrackets(src: string, toks: Tok[]): CodeCanvasProblem | null {
  const stack: { ch: string; line: number }[] = [];
  let pos = 0;
  for (const [k, t] of toks) {
    const line = lineAt(src, pos);
    if (k === "str" && (t.length < 2 || t[0] !== t[t.length - 1])) return { message: "Close the quote that starts here", line };
    if (k === "com" && t.startsWith("/*") && !t.endsWith("*/")) return { message: "Close the comment with */", line };
    if (k === "punc" || k === "op") {
      if (OPEN.includes(t)) stack.push({ ch: t, line });
      else if (CLOSE.includes(t)) {
        const open = stack.pop();
        if (!open) return { message: `Remove the extra ${t}, or open it first`, line };
        if (OPEN.indexOf(open.ch) !== CLOSE.indexOf(t)) return { message: `Expected ${CLOSE[OPEN.indexOf(open.ch)]} to close line ${open.line}, found ${t}`, line };
      }
    }
    pos += t.length;
  }
  const open = stack.pop();
  return open ? { message: `Close the ${open.ch === "(" ? "parenthesis" : "bracket"} opened here`, line: open.line } : null;
}

const CLAUSE = new Set(["from", "where", "group", "order", "limit", "having", "union", "join", "on"]);

function checkSql(src: string): CodeCanvasProblem | null {
  const toks = tokenize(src, "sql");
  const words = toks.map((t, i) => ({ t, i })).filter(({ t }) => t[0] !== "plain" && t[0] !== "com");
  if (!words.length) return { message: "Write a query, starting with SELECT or WITH", line: 1 };
  const first = words[0].t[1].toLowerCase();
  const offset = (idx: number): number => toks.slice(0, idx).reduce((n, t) => n + t[1].length, 0);
  if (first !== "select" && first !== "with") return { message: "Start with SELECT or WITH: this editor runs read-only queries", line: lineAt(src, offset(words[0].i)) };
  const brackets = checkBrackets(src, toks);
  if (brackets) return brackets;
  for (let w = 0; w < words.length - 1; w++) {
    const cur = words[w].t, nxt = words[w + 1].t;
    if (cur[1] === "," && (CLAUSE.has(nxt[1].toLowerCase()) || nxt[1] === ")")) return { message: `Remove the comma before ${nxt[1].toUpperCase()}`, line: lineAt(src, offset(words[w].i)) };
    if (cur[1] === ";") return { message: "Run one statement at a time: remove what follows the ;", line: lineAt(src, offset(words[w + 1].i)) };
    if (cur[0] === "kw" && nxt[0] === "kw" && cur[1].toLowerCase() === nxt[1].toLowerCase() && !["end"].includes(cur[1].toLowerCase())) return { message: `${cur[1].toUpperCase()} is written twice`, line: lineAt(src, offset(words[w + 1].i)) };
  }
  return null;
}

function checkJson(src: string): CodeCanvasProblem | null {
  if (!src.trim()) return { message: "Write a JSON value, like {}", line: 1 };
  try { JSON.parse(src); return null; } catch (err) {
    const msg = err instanceof Error ? err.message : String(err);
    const lc = /line (\d+)/i.exec(msg);
    const pos = /position (\d+)/i.exec(msg);
    const line = lc ? Number(lc[1]) : pos ? lineAt(src, Number(pos[1])) : lineAt(src, src.length);
    const plain = msg.replace(/^JSON\.parse: /, "").replace(/ in JSON at position \d+.*$/, "").replace(/ at line \d+ column \d+.*$/, "");
    return { message: /end of (JSON )?(data|input)/i.test(msg) ? "The JSON ends too early: close every { and [" : plain, line };
  }
}

export function check(code: string, lang: CodeLanguage): CodeCanvasProblem | null {
  if (lang === "sql") return checkSql(code);
  if (lang === "json") return checkJson(code);
  if (lang === "formula") return code.trim() ? checkBrackets(code, tokenize(code, "formula")) : { message: "Write a formula", line: 1 };
  return null;
}

// ---------- line diff (marks what the agent changed) ----------

interface DiffLine {
  op: " " | "+" | "-";
  text: string;
  a?: number;
  b?: number;
}

/** A line diff: common ends trimmed, an LCS on the middle (a few hundred lines at most). */
export function diffLines(a: string[], b: string[]): DiffLine[] {
  let p = 0;
  while (p < a.length && p < b.length && a[p] === b[p]) p++;
  let q = 0;
  while (q < a.length - p && q < b.length - p && a[a.length - 1 - q] === b[b.length - 1 - q]) q++;
  const am = a.slice(p, a.length - q), bm = b.slice(p, b.length - q);
  const dp: number[][] = Array.from({ length: am.length + 1 }, () => new Array<number>(bm.length + 1).fill(0));
  for (let i = am.length - 1; i >= 0; i--) for (let j = bm.length - 1; j >= 0; j--) dp[i][j] = am[i] === bm[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
  const out: DiffLine[] = [];
  for (let i = 0; i < p; i++) out.push({ op: " ", text: a[i], a: i, b: i });
  let i = 0, j = 0;
  while (i < am.length || j < bm.length) {
    if (i < am.length && j < bm.length && am[i] === bm[j]) { out.push({ op: " ", text: am[i], a: p + i, b: p + j }); i++; j++; }
    else if (j < bm.length && (i >= am.length || dp[i][j + 1] >= dp[i + 1][j])) { out.push({ op: "+", text: bm[j], b: p + j }); j++; }
    else { out.push({ op: "-", text: am[i], a: p + i }); i++; }
  }
  for (let k = q; k > 0; k--) out.push({ op: " ", text: a[a.length - k], a: a.length - k, b: b.length - k });
  return out;
}

/** "3", "3–5", "3, 7 and 9" */
function lineList(nums: number[]): string {
  const runs: string[] = [];
  for (let i = 0; i < nums.length; i++) {
    let j = i;
    while (j + 1 < nums.length && nums[j + 1] === nums[j] + 1) j++;
    runs.push(j > i ? `${nums[i]}–${nums[j]}` : String(nums[i]));
    i = j;
  }
  return runs.length > 1 ? `${runs.slice(0, -1).join(", ")} and ${runs[runs.length - 1]}` : runs[0] ?? "";
}

function normalize(raw: unknown): CodeCanvasState {
  const s = (raw ?? {}) as Partial<CodeCanvasState>;
  const lang: CodeLanguage = s.language === "json" || s.language === "formula" || s.language === "text" ? s.language : "sql";
  return { ...s, title: String(s.title ?? ""), language: lang, code: String(s.code ?? "").replace(/\r\n?/g, "\n") };
}

/** Writes the textarea without moving the caret: text before it stays put, text after it shifts with the change. */
function setValue(el: HTMLTextAreaElement, value: string, focused: boolean): void {
  if (el.value === value) return;
  if (!focused) { el.value = value; return; }
  const old = el.value, start = el.selectionStart, end = el.selectionEnd, dir = el.selectionDirection;
  let p = 0;
  while (p < old.length && p < value.length && old[p] === value[p]) p++;
  let q = 0;
  while (q < old.length - p && q < value.length - p && old[old.length - 1 - q] === value[value.length - 1 - q]) q++;
  const map = (c: number): number => (c <= p ? c : c >= old.length - q ? value.length - (old.length - c) : value.length - q);
  el.value = value;
  el.setSelectionRange(map(start), map(end), dir);
}

type Share = "saved" | "pending" | "partial" | "error";
type Res = { kind: "idle" } | { kind: "running" } | { kind: "ok"; result: CodeCanvasResult; at: string; ms: number; code: string } | { kind: "error"; message: string; line?: number; code: string };

const SHARE_DELAY_MS = 600;
const CHECK_DELAY_MS = 250;
let seq = 0;

/**
 * Desktop canvas (CODE, EDIT_MODE). A code editor with line numbers, highlighting, a live check and a Run preview.
 * The user's typing is shared 600 ms after they stop; the agent's edits arrive through onStateChange, keep the caret,
 * and are marked line by line until the user edits those lines.
 */
export function mount({ root, head, canvas, data, actions }: CodeCanvasProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-cd", CSS);
  const doc = root.ownerDocument;
  const win = doc.defaultView ?? window;
  const reduce = !!win.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
  const rootNode = root.getRootNode() as Document | ShadowRoot;
  const n = ++seq;
  const isMac = /Mac|iPhone|iPad/.test(win.navigator?.platform ?? "");

  let shared = normalize(structuredClone(canvas?.state ?? data));
  let model = structuredClone(shared);
  let aiLines = new Set<number>(); // 0-based lines the agent changed, until the user edits them
  let before: string | null = null; // the code before the agent's last edit (Undo, Show changes)
  let replacedLocal = false;
  let showDiff = false;
  let problem: CodeCanvasProblem | null = null;
  let checking = false;
  let checkToken = 0;
  let checkTimer = 0;
  let shareTimer = 0;
  let share: Share = "saved";
  let res: Res = model.lastRun?.ok === false ? { kind: "error", message: model.lastRun.error ?? "The last run failed.", code: model.code } : { kind: "idle" };
  let escaped = false;
  let saving = false;
  let lastTitle = "";

  // ---------- elements ----------
  const ta = h<HTMLTextAreaElement>("textarea", {
    class: "fsk-cd-ta", spellcheck: "false", autocapitalize: "off", autocomplete: "off", wrap: "off",
    "aria-label": `${LANG_LABEL[model.language]} code`, "aria-describedby": `fsk-cd${n}-st fsk-cd${n}-hint`, "aria-multiline": "true",
    placeholder: model.language === "sql" ? "SELECT …" : model.language === "json" ? "{ }" : "",
  });
  ta.value = model.code;
  const hl = h("div", { class: "fsk-cd-hl", "aria-hidden": "true" });
  const gutter = h("div", { class: "fsk-cd-gutter", "aria-hidden": "true" });
  const edArea = h("div", { class: "fsk-cd-ed" }, hl, ta);
  const codeGrid = h("div", { class: "fsk-cd-code" }, gutter, edArea);
  const scroll = h("div", { class: "fsk-cd-scroll" }, codeGrid);
  const note = h("div", { class: "fsk-cd-note", hidden: true });
  const pos = h("span", { class: "fsk-cd-pos" });
  const hint = h("span", { class: "fsk-cd-hint", id: `fsk-cd${n}-hint` }, "Tab indents. Esc, then Tab, leaves the editor.");
  const shareEl = h("span", { class: "fsk-cd-share fsk-cd-long" });
  const problemBtn = h<HTMLButtonElement>("button", { class: "fsk-cd-problem", type: "button", id: `fsk-cd${n}-st`, onclick: () => goToProblem() });
  const box = h("div", { class: "fsk-cd-box" }, note, scroll,
    h("div", { class: "fsk-cd-status" }, h("span", {}, LANG_LABEL[model.language]), pos, hint, shareEl, problemBtn));
  const resMeta = h("span", { class: "fsk-cd-res-meta", role: "status" });
  const resStale = h("span", { class: "fsk-cd-stale", hidden: true }, icon("info", 12), "The code changed since this run");
  const resBody = h("div", { class: "fsk-cd-res-body" });
  const resPanel = h("section", { class: "fsk-cd-res", "aria-labelledby": `fsk-cd${n}-res` },
    h("div", { class: "fsk-cd-res-head" }, h("h3", { id: `fsk-cd${n}-res` }, "Preview"), resMeta, resStale), resBody);
  const runBtn = h<HTMLButtonElement>("button", { class: "fsk-btn fsk-btn--primary", type: "button", onclick: () => void run() });
  const saveBtn = h<HTMLButtonElement>("button", { class: "fsk-btn fsk-btn--ghost", type: "button", onclick: () => void save() }, "Save");
  const live = h("div", { class: "fsk-sr", role: "status", "aria-live": "polite" });
  const titleEl = h("h2", { class: "fsk-cd-title" }, model.title);
  const introEl = h("p", { class: "fsk-cd-intro", hidden: !model.intro }, model.intro ?? "");
  const langEl = h("span", { class: "fsk-cd-lang" }, LANG_LABEL[model.language]);

  // ---------- painting ----------
  function paintCode(flash: number[] = []): void {
    const lines = lineEls(model.code, model.language);
    const bad = problem?.line ? problem.line - 1 : -1;
    const cur = lineAt(ta.value, ta.selectionStart) - 1;
    lines.forEach((el, i) => {
      if (aiLines.has(i)) el.className = "fsk-cd-l--ai";
      if (i === bad) el.className = "fsk-cd-l--bad";
      if (flash.includes(i) && !reduce) el.classList.add("fsk-cd-flash");
    });
    hl.replaceChildren(...lines);
    // focus and caret scrolling must not tuck the code under the sticky gutter
    win.requestAnimationFrame(() => { scroll.style.scrollPaddingLeft = `${gutter.offsetWidth}px`; });
    gutter.replaceChildren(...lines.map((_, i) => h("div", {
      class: [i === cur && "fsk-cd-g--cur", aiLines.has(i) && "fsk-cd-g--ai", i === bad && "fsk-cd-g--bad"].filter(Boolean).join(" ") || null,
    }, String(i + 1))));
  }

  function paintPos(): void {
    const v = ta.value.slice(0, ta.selectionStart);
    const line = v.split("\n").length;
    const col = v.length - v.lastIndexOf("\n");
    pos.textContent = `Ln ${line}, Col ${col}`;
    const cur = line - 1;
    gutter.querySelectorAll(".fsk-cd-g--cur").forEach((e) => e.classList.remove("fsk-cd-g--cur"));
    gutter.children[cur]?.classList.add("fsk-cd-g--cur");
  }

  function paintProblem(): void {
    if (checking) {
      problemBtn.setAttribute("data-busy", "");
      problemBtn.removeAttribute("data-bad");
      problemBtn.replaceChildren(h("span", { class: "fsk-cd-dot", "aria-hidden": "true" }), "Checking…");
    } else if (problem) {
      problemBtn.removeAttribute("data-busy");
      problemBtn.setAttribute("data-bad", "");
      problemBtn.title = "Go to the problem";
      problemBtn.replaceChildren(icon("alert", 13), h("span", {}, `${problem.line ? `Line ${problem.line}: ` : ""}${problem.message}`));
    } else {
      problemBtn.removeAttribute("data-busy");
      problemBtn.removeAttribute("data-bad");
      problemBtn.title = "";
      problemBtn.replaceChildren(icon("check", 13), "Valid");
    }
    if (problem && !checking) box.setAttribute("data-bad", ""); else box.removeAttribute("data-bad");
    ta.setAttribute("aria-invalid", String(!!problem && !checking));
  }

  function paintShare(s: Share): void {
    share = s;
    shareEl.dataset.s = s;
    shareEl.replaceChildren(...(
      s === "pending" ? [h("span", { class: "fsk-cd-dot", "aria-hidden": "true" }), "Sharing…"]
      : s === "partial" ? [icon("alert", 12), "Too long: the agent sees part of it"]
      : s === "error" ? [icon("alert", 12), "Not shared. Keep typing to retry."]
      : [icon("check", 12), "The agent sees this"]));
  }

  function paintNote(): void {
    if (before == null) { note.hidden = true; return; }
    const lines = [...aiLines].sort((a, b) => a - b).map((i) => i + 1);
    const removed = diffLines(before.split("\n"), model.code.split("\n")).filter((d) => d.op === "-").length;
    const what = lines.length ? `changed line${lines.length === 1 ? "" : "s"} ${lineList(lines)}` : removed ? `removed ${removed === 1 ? "a line" : `${removed} lines`}` : "edited the code";
    note.hidden = false;
    note.replaceChildren(icon("sparkle", 14),
      h("span", {}, h("b", {}, "The agent "), `${what}.`, replacedLocal ? " Your unsent edit was replaced; Undo brings it back." : ""),
      h("button", { class: "fsk-cd-link", type: "button", "aria-pressed": String(showDiff), onclick: () => toggleDiff() }, icon(showDiff ? "pencil" : "eye", 13), showDiff ? "Back to editing" : "Show changes"),
      h("button", { class: "fsk-cd-link", type: "button", onclick: () => undoAgent() }, icon("undo", 13), "Undo"),
      h("button", { class: "fsk-cd-link", type: "button", "aria-label": "Dismiss", title: "Dismiss", onclick: () => dismissNote() }, icon("x", 13)));
  }

  function paintDiff(): void {
    if (!showDiff || before == null) {
      if (!edArea.isConnected) scroll.replaceChildren(codeGrid);
      return;
    }
    const d = diffLines(before.split("\n"), model.code.split("\n"));
    scroll.replaceChildren(h("div", { class: "fsk-cd-diff", role: "region", "aria-label": "What the agent changed" },
      d.map((x) => h("div", { class: x.op === "+" ? "fsk-cd-d--add" : x.op === "-" ? "fsk-cd-d--del" : "" },
        h("span", {}, x.a != null ? String(x.a + 1) : ""), h("span", {}, x.b != null ? String(x.b + 1) : ""),
        h("span", { "aria-label": x.op === "+" ? "added" : x.op === "-" ? "removed" : null }, x.op === " " ? "" : x.op === "-" ? "−" : "+"),
        x.text || " "))));
  }

  function paintRun(): void {
    const label = model.runLabel ?? "Run";
    runBtn.disabled = res.kind === "running" || !actions?.run;
    runBtn.replaceChildren(...(res.kind === "running"
      ? [h("span", { class: "fsk-spinner", "aria-hidden": "true" }), "Running…"]
      : [icon("play", 13), label, h("span", { class: "fsk-cd-kbd fsk-cd-long", "aria-hidden": "true" }, isMac ? "⌘↵" : "Ctrl ↵")]));
    runBtn.title = `${label} (${isMac ? "⌘" : "Ctrl"}+Enter)`;
    resStale.hidden = !(res.kind === "ok" || res.kind === "error") || res.code === model.code;
    resMeta.removeAttribute("data-ok");
    resMeta.removeAttribute("data-bad");
    if (res.kind === "idle") {
      resMeta.replaceChildren();
      resBody.replaceChildren(h("div", { class: "fsk-cd-res-empty" }, icon("play", 18),
        h("span", {}, actions?.run ? ["The result shows here when you run it: ", h("kbd", {}, isMac ? "⌘" : "Ctrl"), " ", h("kbd", {}, "Enter")] : "Your app shows a preview here once it can run the code.")));
    } else if (res.kind === "running") {
      resMeta.replaceChildren("Running…");
      resBody.replaceChildren(h("div", { class: "fsk-cd-res-skel", "aria-hidden": "true" },
        Array.from({ length: 4 }, (_, i) => h("div", { style: { display: "flex", gap: "16px" } }, [40, 22, 18, 14].map((w) => bone(`${w}%`, "10px", { i }))))));
    } else if (res.kind === "error") {
      resMeta.setAttribute("data-bad", "");
      resMeta.replaceChildren(icon("alert", 13), "Didn't run");
      resBody.replaceChildren(h("div", { class: "fsk-cd-res-err", role: "alert" }, icon("alert", 16),
        h("div", {}, h("p", {}, "Nothing changed. Fix the code, or ask the agent to, then run it again."), h("pre", {}, res.message),
          h("button", { class: "fsk-btn fsk-btn--ghost", type: "button", onclick: () => void run() }, icon("refresh", 14), "Try again"))));
    } else {
      const r = res.result;
      resMeta.setAttribute("data-ok", "");
      const count = r.rows?.length ?? 0;
      resMeta.replaceChildren(icon("check", 13), r.rows ? `${count} ${count === 1 ? "row" : "rows"}` : "Done", ` · ${Math.round(res.ms)} ms`, r.note ? ` · ${r.note}` : "");
      if (r.rows && r.columns) {
        const numeric = r.columns.map((_, c) => r.rows!.every((row) => row[c] == null || typeof row[c] === "number"));
        resBody.replaceChildren(h("table", {},
          h("thead", {}, h("tr", {}, r.columns.map((c, i) => h("th", { scope: "col", class: numeric[i] ? "fsk-cd-numc" : null }, c)))),
          h("tbody", {}, r.rows.slice(0, 50).map((row) => h("tr", {}, row.map((v, i) =>
            h("td", { class: v == null ? "fsk-cd-null" : numeric[i] ? "fsk-cd-numc" : null, title: v == null ? null : String(v) },
              v == null ? "null" : typeof v === "number" ? v.toLocaleString() : String(v))))))));
      } else resBody.replaceChildren(h("pre", { class: "fsk-cd-out" }, r.output ?? ""));
    }
  }

  function syncTitle(): void {
    const t = (model.canvasTitle ?? model.title).replace(/\s+/g, " ").slice(0, 80);
    if (t !== lastTitle) { lastTitle = t; canvas?.setTitle?.(t); }
    titleEl.textContent = model.title;
    introEl.textContent = model.intro ?? "";
    introEl.hidden = !model.intro;
    langEl.textContent = LANG_LABEL[model.language];
  }

  // ---------- checking ----------
  function scheduleCheck(now = false): void {
    win.clearTimeout(checkTimer);
    if (now) { void runCheck(); return; }
    checkTimer = win.setTimeout(() => void runCheck(), CHECK_DELAY_MS);
  }

  async function runCheck(): Promise<void> {
    const token = ++checkToken;
    const code = model.code;
    const builtIn = check(code, model.language);
    if (!actions?.validate || builtIn) { problem = builtIn; checking = false; paintProblem(); paintCode(); return; }
    checking = true;
    paintProblem();
    let p: CodeCanvasProblem | null = null;
    try { p = await actions.validate(code, model.language); } catch (err) { p = { message: err instanceof Error ? err.message : "Couldn't check the code" }; }
    if (token !== checkToken) return; // the code changed meanwhile
    problem = p;
    checking = false;
    paintProblem();
    paintCode();
  }

  function goToProblem(): void {
    if (!problem?.line) return;
    if (showDiff) toggleDiff();
    const lines = ta.value.split("\n");
    const at = lines.slice(0, problem.line - 1).reduce((n, l) => n + l.length + 1, 0);
    ta.focus();
    ta.setSelectionRange(at, at + (lines[problem.line - 1]?.length ?? 0));
    paintPos();
  }

  // ---------- sharing ----------
  function later(): void {
    paintShare("pending");
    win.clearTimeout(shareTimer);
    shareTimer = win.setTimeout(flush, SHARE_DELAY_MS);
  }

  function flush(): void {
    win.clearTimeout(shareTimer);
    shareTimer = 0;
    if (model.code === shared.code) { paintShare(share === "pending" ? "saved" : share); return; }
    const before = shared;
    shared = { ...shared, code: model.code };
    // In-page answers at once, hosted with a Promise; ok: false means the SDK kept the old state.
    afterSetState(canvas?.setState?.({ code: model.code }), (out) => {
      if (out?.ok === false) { shared = before; paintShare("error"); return; }
      paintShare(out?.notSent?.length ? "partial" : "saved");
    });
    actions?.onChange?.(structuredClone(model));
  }

  // ---------- the user's edits ----------
  function onInput(): void {
    const old = model.code.split("\n");
    model.code = ta.value;
    if (aiLines.size) {
      // keep the marks on lines the user didn't touch
      const next = new Set<number>();
      for (const d of diffLines(old, model.code.split("\n"))) if (d.op === " " && d.a != null && d.b != null && aiLines.has(d.a)) next.add(d.b);
      aiLines = next;
      if (!aiLines.size) { before = null; replacedLocal = false; }
      paintNote();
    }
    if (problem) problem = { ...problem, line: undefined }; // the old line may have moved: re-check first
    paintCode();
    paintPos();
    paintRun();
    scheduleCheck();
    later();
  }

  function replaceSelection(text: string, selStart: number, selEnd: number, caret: number): void {
    ta.focus();
    ta.setSelectionRange(selStart, selEnd);
    // insertText keeps the browser's undo history; setRangeText is the fallback
    const ok = typeof doc.execCommand === "function" && doc.execCommand("insertText", false, text);
    if (!ok) { ta.setRangeText(text, selStart, selEnd, "end"); onInput(); }
    ta.setSelectionRange(caret, caret);
  }

  function onKey(e: KeyboardEvent): void {
    if (e.isComposing) return;
    const v = ta.value, s = ta.selectionStart, end = ta.selectionEnd;
    const lineStart = v.lastIndexOf("\n", s - 1) + 1;
    if (e.key === "Escape") { escaped = true; e.stopPropagation(); return; }
    if (e.key === "Tab" && escaped) { escaped = false; return; } // let focus leave
    escaped = false;
    if ((e.ctrlKey || e.metaKey) && e.key === "Enter") { e.preventDefault(); void run(); return; }
    if (e.key === "Tab") {
      e.preventDefault();
      const multi = v.slice(s, end).includes("\n");
      if (!multi && !e.shiftKey) { replaceSelection("  ", s, end, s + 2); return; }
      // indent or outdent every selected line
      const blockEnd = v.indexOf("\n", end - (end > s && v[end - 1] === "\n" ? 1 : 0));
      const stop = blockEnd < 0 ? v.length : blockEnd;
      const block = v.slice(lineStart, stop);
      const lines = block.split("\n");
      const next = lines.map((l) => (e.shiftKey ? l.replace(/^ {1,2}/, "") : `  ${l}`)).join("\n");
      replaceSelection(next, lineStart, stop, 0);
      ta.setSelectionRange(lineStart, lineStart + next.length);
      return;
    }
    if (e.key === "Enter" && !e.shiftKey && !e.altKey) {
      e.preventDefault();
      const indent = /^[ \t]*/.exec(v.slice(lineStart, s))?.[0] ?? "";
      const prev = v.slice(lineStart, s).trimEnd();
      const extra = /[([{]$/.test(prev) ? "  " : "";
      const ins = `\n${indent}${extra}`;
      replaceSelection(ins, s, end, s + ins.length);
    }
  }

  // ---------- the agent's edits ----------
  function applyRemote(next: Record<string, any>): void {
    const remote = normalize(structuredClone(next));
    const focused = rootNode.activeElement === ta;
    const langChanged = remote.language !== model.language;
    if (remote.code !== shared.code) {
      const prev = model.code;
      replacedLocal = model.code !== shared.code; // the user had typing the agent hadn't seen
      before = prev;
      const d = diffLines(prev.split("\n"), remote.code.split("\n"));
      aiLines = new Set(d.filter((x) => x.op === "+" && x.b != null).map((x) => x.b!));
      model = { ...remote };
      setValue(ta, model.code, focused);
      showDiff = false;
      paintDiff();
      paintCode([...aiLines]);
      paintNote();
      const lines = [...aiLines].sort((a, b) => a - b).map((i) => i + 1);
      live.textContent = `The agent ${lines.length ? `changed line${lines.length === 1 ? "" : "s"} ${lineList(lines)}` : "edited the code"}.`;
      // bring the first change into view without moving the caret
      const first = Math.min(...aiLines);
      if (Number.isFinite(first)) {
        const el = hl.children[first];
        if (el instanceof HTMLElement && !focused) el.scrollIntoView({ block: "nearest", behavior: reduce ? "auto" : "smooth" });
      }
    } else {
      model = { ...remote, code: model.code };
    }
    shared = remote;
    if (langChanged) ta.setAttribute("aria-label", `${LANG_LABEL[model.language]} code`);
    syncTitle();
    paintPos();
    paintRun();
    scheduleCheck(true);
    if (model.code !== shared.code) later(); else paintShare(share === "pending" ? "saved" : share);
  }

  function toggleDiff(): void {
    showDiff = !showDiff;
    paintDiff();
    paintNote();
    if (!showDiff) ta.focus({ preventScroll: true });
  }

  function undoAgent(): void {
    if (before == null) return;
    const text = before;
    before = null;
    aiLines = new Set();
    replacedLocal = false;
    showDiff = false;
    paintDiff();
    paintNote();
    replaceSelection(text, 0, ta.value.length, 0);
    if (model.code !== text) { ta.value = text; onInput(); }
    live.textContent = "Undid the agent's edit.";
  }

  function dismissNote(): void {
    before = null;
    aiLines = new Set();
    replacedLocal = false;
    showDiff = false;
    paintDiff();
    paintNote();
    paintCode();
    ta.focus({ preventScroll: true });
  }

  // ---------- run and save ----------
  async function run(): Promise<void> {
    if (!actions?.run || res.kind === "running") return;
    win.clearTimeout(checkTimer);
    await runCheck();
    if (problem) { goToProblem(); live.textContent = `Not run: ${problem.message}`; return; }
    flush(); // the agent sees what runs
    const code = model.code;
    res = { kind: "running" };
    paintRun();
    const t0 = win.performance.now();
    try {
      const result = await actions.run(code, model.language);
      res = { kind: "ok", result, at: new Date().toISOString(), ms: win.performance.now() - t0, code };
      const lastRun: CodeCanvasRun = { ok: true, at: res.at, rows: result.rows?.length };
      model.lastRun = lastRun;
      canvas?.setState?.({ lastRun });
      live.textContent = result.rows ? `Ran: ${result.rows.length} rows.` : "Ran.";
    } catch (err) {
      const message = (err instanceof Error && err.message) || "It didn't run. Nothing changed.";
      const line = /line (\d+)/i.exec(message);
      res = { kind: "error", message, code, line: line ? Number(line[1]) : undefined };
      if (line) { problem = { message: message.replace(/\s*\(?\bline \d+\)?\.?\s*$/i, ""), line: Number(line[1]) }; paintProblem(); paintCode(); }
      const lastRun: CodeCanvasRun = { ok: false, at: new Date().toISOString(), error: message.slice(0, 300) };
      model.lastRun = lastRun;
      canvas?.setState?.({ lastRun });
    }
    paintRun();
  }

  async function save(): Promise<void> {
    if (!actions?.save || saving) return;
    await runCheck();
    if (problem) { goToProblem(); return; }
    flush();
    saving = true;
    saveBtn.disabled = true;
    saveBtn.replaceChildren(h("span", { class: "fsk-spinner", "aria-hidden": "true" }), "Saving…");
    try {
      await actions.save(model.code);
      saveBtn.replaceChildren(icon("check", 14), "Saved");
      live.textContent = "Saved.";
      win.setTimeout(() => { if (saveBtn.isConnected) saveBtn.replaceChildren("Save"); }, 2000);
    } catch (err) {
      saveBtn.replaceChildren("Save");
      live.textContent = (err instanceof Error && err.message) || "Couldn't save. Your code is kept.";
      problem = { message: live.textContent };
      paintProblem();
    } finally {
      saving = false;
      saveBtn.disabled = false;
    }
  }

  // ---------- draw ----------
  ta.addEventListener("input", onInput);
  ta.addEventListener("keydown", onKey);
  ta.addEventListener("blur", () => { if (shareTimer) flush(); });
  for (const ev of ["keyup", "click", "select", "focus"]) ta.addEventListener(ev, paintPos);
  root.replaceChildren(h("div", { class: "fsk fsk-cd" },
    h("header", { class: "fsk-cd-top" },
      h("div", {},
        h("div", { class: "fsk-cd-badges" }, h("span", { class: "fsk-badge fsk-badge--agent" }, icon("zap", 12), "Code"), langEl),
        titleEl, introEl),
      h("div", { class: "fsk-cd-actions" }, actions?.save && saveBtn, runBtn)),
    box,
    resPanel,
    live));
  syncTitle();
  paintCode();
  paintPos();
  paintShare("saved");
  paintRun();
  scheduleCheck(true);
  const off = canvas?.onStateChange?.((next) => applyRemote(next));

  return () => {
    if (shareTimer) flush(); // closing keeps the state: share the last keystrokes
    win.clearTimeout(checkTimer);
    off?.();
    root.replaceChildren();
  };
}

/** Mobile has no canvas: a read-only card with the first lines, highlighted, and whether it's valid. */
export function mountMobile({ root, head, data, api }: CodeCanvasCardProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-cd", CSS);
  const s = normalize(structuredClone(data));
  const lines = s.code.split("\n");
  const p = check(s.code, s.language);
  const last = s.lastRun;
  root.replaceChildren(h("section", { class: "fsk fsk-card fsk-cdm", "aria-label": s.title },
    h("header", { class: "fsk-head" },
      h("span", { class: "fsk-chip" }, icon("zap", 18)),
      h("div", {}, h("h3", { class: "fsk-title" }, s.title), h("p", { class: "fsk-sub" }, `${LANG_LABEL[s.language]} · ${lines.length} ${lines.length === 1 ? "line" : "lines"}`))),
    h("pre", { class: "fsk-cdm-code", tabindex: "0", "aria-label": `${LANG_LABEL[s.language]} code, first lines` }, lineEls(lines.slice(0, 12).join("\n"), s.language)),
    h("p", { class: "fsk-cdm-row" },
      p ? h("span", { class: "fsk-cdm-bad" }, icon("alert", 13), `${p.line ? `Line ${p.line}: ` : ""}${p.message}`) : h("span", { class: "fsk-cdm-ok" }, icon("check", 13), "Valid"),
      last && h("span", {}, icon("clock", 13), last.ok ? `Ran ${formatRelative(last.at)}${last.rows != null ? `: ${last.rows} rows` : ""}` : `Last run failed ${formatRelative(last.at)}`)),
    h("p", { class: "fsk-cdm-desk" }, icon("expand", 16),
      h("span", {}, h("strong", {}, "Open on desktop"), "Edit and run it beside the chat on a larger screen. The agent keeps what you've written."))));
  api?.displayed?.();
  return () => root.replaceChildren();
}

/** The states this canvas draws besides its data. */
export const states: StateKind[] = ["loading", "empty", "error"];

/**
 * Loading, empty or error. Desktop ("desktop", the default): the canvas panel, with a skeleton in the editor's shape,
 * or the message centered in the panel. Mobile: the snippet card.
 */
export function mountState({ root, head, state, title, subtitle, surface = "desktop", canvas }: CodeCanvasStateProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-cd", CSS);
  if (surface === "mobile") {
    const card = stateCard({ state, cls: "fsk-cdm", icon: "zap", title, subtitle, surface, skeleton: () => h("div", {},
      h("div", { class: "fsk-cdm-code", style: { display: "flex", flexDirection: "column", gap: "9px" } }, [38, 52, 46, 30, 60, 24].map((w, i) => bone(`${w}%`, "9px", { i }))),
      h("div", { style: { marginTop: "12px" } }, bone("100%", "56px", { cls: "fsk-bone--box", i: 3 }))) });
    root.replaceChildren(card.el);
    return () => { card.dispose(); root.replaceChildren(); };
  }
  if (title) canvas?.setTitle(title);
  const loading = state.kind === "loading";
  let dispose = (): void => {};
  let body: HTMLElement;
  if (state.kind === "loading") {
    const widths = [62, 18, 34, 40, 30, 52, 0, 26, 58, 44, 50, 22];
    const indent = [0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0];
    body = h("div", { style: { display: "contents" }, "aria-hidden": "true" },
      h("div", { class: "fsk-cd-box" }, h("div", { class: "fsk-cd-skel" },
        h("div", { class: "fsk-cd-skel-g" }, widths.map((_, i) => bone("14px", "9px", { i }))),
        h("div", { class: "fsk-cd-skel-l" }, widths.map((w, i) => (w ? h("div", { style: { paddingLeft: `${indent[i] * 22}px` } }, bone(`${w}%`, "9px", { i })) : h("div", { style: { height: "9px" } })))))),
      h("div", { class: "fsk-cd-res" }, h("div", { class: "fsk-cd-res-head" }, bone("64px", "10px")),
        h("div", { class: "fsk-cd-res-skel" }, Array.from({ length: 3 }, (_, i) => h("div", { style: { display: "flex", gap: "16px" } }, [40, 22, 18].map((w) => bone(`${w}%`, "10px", { i })))))));
  } else if (state.kind === "empty") {
    body = h("div", { class: "fsk-cd-center" }, h("div", {}, emptyBlock({ icon: "zap", ...state }, surface)));
  } else {
    const e = errorBlock(state, surface);
    dispose = e.dispose;
    body = h("div", { class: "fsk-cd-center" }, h("div", {}, e.el));
  }
  root.replaceChildren(h("div", {
    class: `fsk fsk-cd fsk-cd-state fsk-state--${state.kind}`, "data-state": state.kind,
    role: loading ? "status" : null, "aria-busy": loading ? "true" : null, "aria-live": loading ? "polite" : null,
  },
    loading && h("span", { class: "fsk-sr" }, state.label ?? "Loading…"),
    h("header", { class: "fsk-cd-top" },
      h("div", {},
        h("div", { class: "fsk-cd-badges" }, h("span", { class: "fsk-badge fsk-badge--agent" }, icon("zap", 12), "Code")),
        title ? h("h2", { class: "fsk-cd-title" }, title) : h("div", { style: { margin: "12px 0 6px" } }, bone("38%", "16px")),
        subtitle ? h("p", { class: "fsk-cd-intro" }, subtitle) : loading && bone("52%", "10px")),
      loading && h("div", { class: "fsk-cd-actions", "aria-hidden": "true" }, bone("92px", "36px", { cls: "fsk-bone--box" }))),
    body));
  return () => { dispose(); root.replaceChildren(); };
}

export const fixtures: Record<string, CodeCanvasState> = {
  default: {
    canvasTitle: "Query: churned accounts",
    title: "Churned accounts last quarter",
    intro: "Read-only SQL on your reporting database. Ask me to change it, or edit it here and run a preview.",
    language: "sql",
    runLabel: "Run query",
    code: [
      "-- Accounts that canceled last quarter, with the MRR they took with them",
      "SELECT",
      "  a.name,",
      "  a.plan,",
      "  s.canceled_at::date AS churned_on,",
      "  ROUND(s.mrr_cents / 100.0, 2) AS mrr",
      "FROM accounts a",
      "JOIN subscriptions s ON s.account_id = a.id",
      "WHERE s.status = 'canceled'",
      "  AND s.canceled_at >= date_trunc('quarter', now()) - interval '3 months'",
      "  AND s.canceled_at < date_trunc('quarter', now())",
      "ORDER BY churned_on DESC",
      "LIMIT 100",
    ].join("\n"),
  },
};
```

```js title="agent/ui/code-canvas.js"
// Template: code-canvas. A CODE canvas where the user and the agent write a query, a formula or a JSON payload together (desktop), plus its mobile snippet card.

export const meta = {
  id: "code-canvas",
  title: "Code editor",
  surface: "canvas",
  canvasType: "CODE",
  canvasStatus: "EDIT_MODE",
  kind: "interactive",
  mobile: "fallback-card",
  whenToUse: "A query, a formula, a script or a config the user and the agent write together: a SQL report, a filter formula, a webhook payload. The agent writes it into the editor, keeps it valid, and the user runs a preview before your app saves it.",
  whenNotToUse: "A snippet the agent shows once and the user copies (a chat message with a code block). Settings with fixed choices (form canvas). Mobile: the canvas isn't available; use the snippet card (mountMobile).",
};

const CSS = `
.fsk-cd { container: fsk-cd / inline-size; height: 100%; min-height: 460px; display: flex; flex-direction: column; gap: 12px; padding: 14px 20px 16px; background: var(--k-paper); }
.fsk-cd-top { flex: none; display: flex; align-items: flex-end; gap: 12px; }
.fsk-cd-top > div:first-child { flex: 1; min-width: 0; }
.fsk-cd-badges { display: flex; align-items: center; gap: 6px; }
.fsk-cd-lang { padding: 1px 7px; border-radius: var(--k-r); border: 1px solid var(--k-border); font: 600 .72em/1.6 var(--k-mono); letter-spacing: .04em; color: var(--k-text-2); text-transform: uppercase; }
.fsk-cd-title { margin: 8px 0 2px; font-size: 1.25em; font-weight: 650; letter-spacing: -0.02em; line-height: 1.25; }
.fsk-cd-intro { margin: 0; color: var(--k-text-2); font-size: .93em; max-width: 64ch; }
.fsk-cd-actions { flex: none; display: flex; align-items: center; gap: 8px; }
.fsk-cd-kbd { padding: 0 5px; margin-left: 2px; border-radius: var(--k-r); background: color-mix(in srgb, var(--k-on-primary) 18%, transparent); font: 500 .79em/1.5 var(--k-mono); }

/* The editor */
.fsk-cd-box { position: relative; flex: 1 1 0; min-height: 200px; display: flex; flex-direction: column; overflow: hidden;
  border: 1px solid var(--k-border); border-radius: var(--k-r-lg); background: var(--k-sunken); transition: border-color .15s, box-shadow .15s; }
.fsk-cd-box:focus-within { border-color: color-mix(in srgb, var(--k-primary) 55%, var(--k-border)); box-shadow: 0 0 0 3px color-mix(in srgb, var(--k-primary) 14%, transparent); }
.fsk-cd-box[data-bad] { border-color: color-mix(in srgb, var(--k-error) 50%, var(--k-border)); }
.fsk-cd-note { flex: none; display: flex; align-items: center; flex-wrap: wrap; gap: 4px 10px; padding: 7px 10px 7px 12px; font-size: .86em;
  background: var(--k-tint); color: var(--k-text); border-bottom: 1px solid color-mix(in srgb, var(--k-primary) 22%, var(--k-paper)); animation: fsk-in .25s var(--k-ease) both; }
.fsk-cd-note > .fsk-icon { color: var(--k-primary); }
.fsk-cd-note > span { flex: 1; min-width: 160px; }
.fsk-cd-note b { font-weight: 600; }
.fsk-cd-link { appearance: none; display: inline-flex; align-items: center; gap: 4px; min-height: 26px; padding: 0 8px; border: 0; border-radius: var(--k-r);
  background: transparent; color: var(--k-primary); font: inherit; font-weight: 600; cursor: pointer; white-space: nowrap; }
.fsk-cd-link:hover { background: var(--k-tint-2); }
.fsk-cd-link:focus-visible, .fsk-cd-problem:focus-visible { outline: 2px solid var(--k-primary); outline-offset: 1px; }
.fsk-cd-scroll { position: relative; flex: 1; min-height: 0; overflow: auto; overscroll-behavior: contain; }
.fsk-cd-code { display: grid; grid-template-columns: auto minmax(0, 1fr); min-width: max-content; min-height: 100%;
  font-family: var(--k-mono); font-size: .9em; line-height: 1.6; tab-size: 2; }
.fsk-cd-gutter { position: sticky; left: 0; z-index: 2; padding: 12px 0; min-width: 44px; text-align: right; user-select: none;
  color: color-mix(in srgb, var(--k-text-2) 75%, transparent); background: var(--k-sunken); border-right: 1px solid var(--k-muted-border); font-variant-numeric: tabular-nums; }
.fsk-cd-gutter > div { position: relative; height: 1.6em; padding: 0 12px 0 14px; }
.fsk-cd-gutter > .fsk-cd-g--cur { color: var(--k-text); }
.fsk-cd-gutter > .fsk-cd-g--ai::before { content: ""; position: absolute; left: 4px; top: 2px; bottom: 2px; width: 3px; border-radius: 2px; background: var(--k-primary); }
.fsk-cd-gutter > .fsk-cd-g--bad { color: var(--k-error); font-weight: 700; }
.fsk-cd-gutter > .fsk-cd-g--bad::after { content: "!"; position: absolute; left: 3px; font-weight: 700; }
.fsk-cd-ed { position: relative; display: grid; min-width: 0; }
.fsk-cd-hl, .fsk-cd-ta { grid-area: 1 / 1; margin: 0; padding: 12px 24px 12px 12px; border: 0; font: inherit; line-height: inherit; letter-spacing: 0; tab-size: inherit;
  white-space: pre; overflow-wrap: normal; word-break: normal; }
.fsk-cd-hl { pointer-events: none; color: var(--k-text); min-height: 100%; }
.fsk-cd-hl > div { min-height: 1.6em; margin: 0 -24px 0 -12px; padding: 0 24px 0 12px; }
.fsk-cd-hl > .fsk-cd-l--ai { background: color-mix(in srgb, var(--k-primary) 10%, var(--k-sunken)); }
.fsk-cd-hl > .fsk-cd-l--bad { background: color-mix(in srgb, var(--k-error) 9%, var(--k-sunken)); }
.fsk-cd-flash { animation: fsk-cd-flash 1.6s var(--k-ease); }
.fsk-cd-ta { display: block; width: 100%; height: 100%; min-height: 100%; resize: none; overflow: hidden; outline: none; background: transparent;
  color: transparent; -webkit-text-fill-color: transparent; caret-color: var(--k-text); }
.fsk-cd-ta::selection { background: color-mix(in srgb, var(--k-primary) 28%, transparent); }
.fsk-cd-ta::placeholder { -webkit-text-fill-color: var(--k-text-2); color: var(--k-text-2); }
.fsk-cd-ta[readonly] { caret-color: transparent; }
/* Tokens: one hue (the theme's primary) plus text weights, so any theme reads */
.fsk-cd-t-kw { color: var(--k-primary); font-weight: 600; }
.fsk-cd-t-fn { color: color-mix(in srgb, var(--k-primary) 62%, var(--k-text)); }
.fsk-cd-t-str { color: var(--k-success); }
.fsk-cd-t-num, .fsk-cd-t-lit { color: var(--k-warning); }
.fsk-cd-t-key { color: color-mix(in srgb, var(--k-primary) 70%, var(--k-text)); }
.fsk-cd-t-com { color: var(--k-text-2); font-style: italic; }
.fsk-cd-t-op, .fsk-cd-t-punc { color: var(--k-text-2); }
.fsk-cd-t-err { text-decoration: underline wavy var(--k-error); text-decoration-skip-ink: none; text-underline-offset: 3px; }

/* Diff view */
.fsk-cd-diff { padding: 10px 0; font-family: var(--k-mono); font-size: .9em; line-height: 1.6; }
.fsk-cd-diff > div { display: grid; grid-template-columns: 32px 32px 18px 1fr; white-space: pre; padding-right: 16px; }
.fsk-cd-diff span { color: var(--k-text-2); text-align: right; padding-right: 8px; user-select: none; }
.fsk-cd-diff span:nth-child(3) { text-align: center; padding: 0; font-weight: 700; }
.fsk-cd-diff .fsk-cd-d--add { background: color-mix(in srgb, var(--k-primary) 11%, var(--k-sunken)); }
.fsk-cd-diff .fsk-cd-d--add span:nth-child(3) { color: var(--k-primary); }
.fsk-cd-diff .fsk-cd-d--del { background: color-mix(in srgb, var(--k-error) 9%, var(--k-sunken)); color: var(--k-text-2); }
.fsk-cd-diff .fsk-cd-d--del span:nth-child(3) { color: var(--k-error); }

/* Status bar */
.fsk-cd-status { flex: none; display: flex; align-items: center; gap: 12px; min-height: 32px; padding: 4px 8px 4px 12px; font-size: .79em; color: var(--k-text-2);
  border-top: 1px solid var(--k-muted-border); background: var(--k-paper); }
.fsk-cd-status > span { white-space: nowrap; }
.fsk-cd-pos { font-variant-numeric: tabular-nums; }
.fsk-cd-hint { overflow: hidden; text-overflow: ellipsis; }
.fsk-cd-problem { appearance: none; display: inline-flex; align-items: center; gap: 5px; min-height: 24px; margin-left: auto; padding: 0 8px; border: 0; border-radius: var(--k-r);
  background: none; font: inherit; font-weight: 600; white-space: nowrap; cursor: default; color: var(--k-success); }
.fsk-cd-problem[data-bad] { cursor: pointer; color: var(--k-error); background: color-mix(in srgb, var(--k-error) 10%, var(--k-paper)); }
.fsk-cd-problem[data-bad] > span { overflow: hidden; text-overflow: ellipsis; max-width: 36ch; }
.fsk-cd-problem[data-busy] { color: var(--k-text-2); font-weight: 500; }
.fsk-cd-share { display: inline-flex; align-items: center; gap: 5px; }
.fsk-cd-share[data-s="saved"] .fsk-icon { color: var(--k-success); }
.fsk-cd-share[data-s="partial"] .fsk-icon { color: var(--k-warning); }
.fsk-cd-share[data-s="error"] { color: var(--k-error); }
.fsk-cd-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--k-primary); animation: fsk-cd-pulse 1.1s ease-in-out infinite; }

/* Results */
.fsk-cd-res { flex: 0 0 34%; min-height: 140px; display: flex; flex-direction: column; overflow: hidden; border: 1px solid var(--k-border); border-radius: var(--k-r-lg); background: var(--k-paper); }
.fsk-cd-res-head { flex: none; display: flex; align-items: center; gap: 10px; min-height: 38px; padding: 0 12px; border-bottom: 1px solid var(--k-divider); font-size: .86em; }
.fsk-cd-res-head h3 { margin: 0; font-size: 1em; font-weight: 600; }
.fsk-cd-res-meta { display: inline-flex; align-items: center; gap: 6px; color: var(--k-text-2); }
.fsk-cd-res-meta[data-ok] .fsk-icon { color: var(--k-success); }
.fsk-cd-res-meta[data-bad] { color: var(--k-error); }
.fsk-cd-stale { margin-left: auto; display: inline-flex; align-items: center; gap: 4px; color: var(--k-text-2); font-size: .93em; }
.fsk-cd-res-body { flex: 1; min-height: 0; overflow: auto; }
.fsk-cd-res table { width: 100%; border-collapse: separate; border-spacing: 0; font-size: .86em; }
.fsk-cd-res th { position: sticky; top: 0; z-index: 1; padding: 0 12px; height: 32px; text-align: left; font-weight: 500; color: var(--k-text-2); white-space: nowrap;
  background: var(--k-sunken); border-bottom: 1px solid var(--k-divider); font-family: var(--k-mono); font-size: .93em; }
.fsk-cd-res td { padding: 0 12px; height: 32px; border-bottom: 1px solid var(--k-divider); white-space: nowrap; max-width: 280px; overflow: hidden; text-overflow: ellipsis; }
.fsk-cd-res td.fsk-cd-numc, .fsk-cd-res th.fsk-cd-numc { text-align: right; font-variant-numeric: tabular-nums; }
.fsk-cd-res td.fsk-cd-null { color: var(--k-text-2); font-style: italic; }
.fsk-cd-res tbody tr:hover td { background: var(--k-sunken); }
.fsk-cd-out { margin: 0; padding: 12px; font: .86em/1.6 var(--k-mono); white-space: pre-wrap; overflow-wrap: anywhere; }
.fsk-cd-res-empty { height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px; padding: 16px; text-align: center; color: var(--k-text-2); font-size: .93em; }
.fsk-cd-res-empty .fsk-icon { color: var(--k-text-2); }
.fsk-cd-res-empty kbd { padding: 0 5px; border-radius: var(--k-r); border: 1px solid var(--k-border); border-bottom-width: 2px; font: 500 .9em/1.5 var(--k-mono); color: var(--k-text); }
.fsk-cd-res-err { display: flex; gap: 10px; align-items: flex-start; padding: 14px; font-size: .93em; }
.fsk-cd-res-err > .fsk-icon { color: var(--k-error); margin-top: 2px; }
.fsk-cd-res-err p { margin: 0 0 8px; }
.fsk-cd-res-err pre { margin: 0 0 10px; padding: 8px 10px; border-radius: var(--k-r-md); background: var(--k-sunken); font: .93em/1.5 var(--k-mono); white-space: pre-wrap; color: var(--k-text-2); }
.fsk-cd-res-skel { display: flex; flex-direction: column; gap: 12px; padding: 14px 12px; }

/* States in the panel */
.fsk-cd-center { flex: 1; display: grid; place-items: center; padding: 24px; }
.fsk-cd-center > div { width: 100%; max-width: 420px; }
.fsk-cd-skel { display: flex; flex: 1; gap: 14px; padding: 12px; }
.fsk-cd-skel-g { display: flex; flex-direction: column; gap: 12px; width: 18px; }
.fsk-cd-skel-l { flex: 1; display: flex; flex-direction: column; gap: 12px; }

@keyframes fsk-cd-flash { 0%, 30% { background-color: color-mix(in srgb, var(--k-primary) 22%, var(--k-sunken)); } }
@keyframes fsk-cd-pulse { 50% { opacity: .35; transform: scale(.75); } }
@container fsk-cd (max-width: 560px) {
  .fsk-cd { padding: 12px 14px 14px; }
  .fsk-cd-hint, .fsk-cd-long { display: none; }
}
@media (prefers-reduced-motion: reduce) { .fsk-cd-flash { animation: none; } }

/* Mobile snippet card */
.fsk-cdm .fsk-cdm-code { position: relative; max-height: 220px; overflow: hidden; margin: 0; padding: 10px 12px; border-radius: var(--k-r-md); background: var(--k-sunken);
  border: 1px solid var(--k-muted-border); font: .79em/1.6 var(--k-mono); white-space: pre; }
.fsk-cdm .fsk-cdm-code::after { content: ""; position: absolute; left: 0; right: 0; bottom: 0; height: 48px; background: linear-gradient(to bottom, transparent, var(--k-sunken)); }
.fsk-cdm .fsk-cdm-code > div { min-height: 1.6em; }
.fsk-cdm-row { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 12px; margin: 10px 0 0; font-size: .86em; color: var(--k-text-2); }
.fsk-cdm-row > span { display: inline-flex; align-items: center; gap: 5px; }
.fsk-cdm-ok .fsk-icon { color: var(--k-success); }
.fsk-cdm-bad { color: var(--k-error); }
.fsk-cdm-desk { display: flex; gap: 10px; align-items: flex-start; margin: 12px 0 0; padding: 12px; border-radius: var(--k-r-md); background: var(--k-sunken); font-size: .93em; }
.fsk-cdm-desk .fsk-icon { color: var(--k-primary); margin-top: 2px; }
.fsk-cdm-desk strong { display: block; font-weight: 600; }
.fsk-cdm-desk span { color: var(--k-text-2); }
`;

// ---------- tokenizing (text nodes only: user code is never parsed as HTML) ----------

const SQL_KW = new Set(("select from where and or not in is null as join left right inner outer full cross on using group by order having limit offset distinct " +
  "case when then else end union all insert into values update set delete with asc desc between like ilike exists interval true false returning over partition " +
  "window filter lateral natural nulls first last any some cast").split(" "));
const FORMULA_KW = new Set(["AND", "OR", "NOT", "TRUE", "FALSE", "IF", "BLANK"]);
const LANG_LABEL = { sql: "SQL", json: "JSON", formula: "Formula", text: "Text" };
const OPEN = "([{", CLOSE = ")]}";

function nextNonSpace(src, from) {
  const m = /\S/.exec(src.slice(from, from + 64));
  return m ? m[0] : "";
}

export function tokenize(src, lang) {
  const out = [];
  if (lang === "text") return [["plain", src]];
  const re = lang === "sql"
    ? /(--[^\n]*|\/\*[\s\S]*?(?:\*\/|$))|('(?:[^'\\]|\\.|'')*'?)|("(?:[^"\\\n]|\\.)*"?)|(\b\d+(?:\.\d+)?\b)|([A-Za-z_][\w$]*)|(\s+)|([\s\S])/g
    : lang === "json"
      ? /(\/\/[^\n]*)|("(?:[^"\\\n]|\\.)*"?)|()(-?\b\d+(?:\.\d+)?(?:[eE][+-]?\d+)?\b)|\b(true|false|null)\b|(\s+)|([\s\S])/g
      : /(\/\/[^\n]*)|("(?:[^"\\\n]|\\.)*"?)|(\{[^}\n]*\}?)|(\b\d+(?:\.\d+)?\b)|([A-Za-z_][\w.]*)|(\s+)|([\s\S])/g;
  let m;
  while ((m = re.exec(src))) {
    const [t, com, str, third, num, word, space] = m;
    const after = re.lastIndex;
    if (com) out.push(["com", t]);
    else if (str) out.push([lang === "json" && nextNonSpace(src, after) === ":" ? "key" : "str", t]);
    else if (third) out.push(["key", t]); // SQL "quoted identifier", formula {Field}
    else if (num) out.push(["num", t]);
    else if (word) {
      if (lang === "json") out.push(["lit", t]);
      else if (nextNonSpace(src, after) === "(") out.push(["fn", t]);
      else if (lang === "sql" ? SQL_KW.has(t.toLowerCase()) : FORMULA_KW.has(t.toUpperCase())) out.push(["kw", t]);
      else out.push(["id", t]);
    } else if (space) out.push(["plain", t]);
    else out.push([/[(),.;:[\]{}]/.test(t) ? "punc" : "op", t]);
  }
  return out;
}

/** Tokens split into lines, so each line can carry its own mark. */
function toLines(toks) {
  const lines = [[]];
  for (const [k, t] of toks) {
    const parts = t.split("\n");
    parts.forEach((p, i) => {
      if (i > 0) lines.push([]);
      if (p) lines[lines.length - 1].push([k, p]);
    });
  }
  return lines;
}

function lineEls(code, lang) {
  return toLines(tokenize(code, lang)).map((toks) => h("div", {},
    toks.map(([k, t]) => (k === "plain" || k === "id" ? t : h("span", { class: `fsk-cd-t-${k}` }, t)))));
}

// ---------- the built-in checks ----------

const lineAt = (src, i) => src.slice(0, i).split("\n").length;

function checkBrackets(src, toks) {
  const stack = [];
  let pos = 0;
  for (const [k, t] of toks) {
    const line = lineAt(src, pos);
    if (k === "str" && (t.length < 2 || t[0] !== t[t.length - 1])) return { message: "Close the quote that starts here", line };
    if (k === "com" && t.startsWith("/*") && !t.endsWith("*/")) return { message: "Close the comment with */", line };
    if (k === "punc" || k === "op") {
      if (OPEN.includes(t)) stack.push({ ch: t, line });
      else if (CLOSE.includes(t)) {
        const open = stack.pop();
        if (!open) return { message: `Remove the extra ${t}, or open it first`, line };
        if (OPEN.indexOf(open.ch) !== CLOSE.indexOf(t)) return { message: `Expected ${CLOSE[OPEN.indexOf(open.ch)]} to close line ${open.line}, found ${t}`, line };
      }
    }
    pos += t.length;
  }
  const open = stack.pop();
  return open ? { message: `Close the ${open.ch === "(" ? "parenthesis" : "bracket"} opened here`, line: open.line } : null;
}

const CLAUSE = new Set(["from", "where", "group", "order", "limit", "having", "union", "join", "on"]);

function checkSql(src) {
  const toks = tokenize(src, "sql");
  const words = toks.map((t, i) => ({ t, i })).filter(({ t }) => t[0] !== "plain" && t[0] !== "com");
  if (!words.length) return { message: "Write a query, starting with SELECT or WITH", line: 1 };
  const first = words[0].t[1].toLowerCase();
  const offset = (idx) => toks.slice(0, idx).reduce((n, t) => n + t[1].length, 0);
  if (first !== "select" && first !== "with") return { message: "Start with SELECT or WITH: this editor runs read-only queries", line: lineAt(src, offset(words[0].i)) };
  const brackets = checkBrackets(src, toks);
  if (brackets) return brackets;
  for (let w = 0; w < words.length - 1; w++) {
    const cur = words[w].t, nxt = words[w + 1].t;
    if (cur[1] === "," && (CLAUSE.has(nxt[1].toLowerCase()) || nxt[1] === ")")) return { message: `Remove the comma before ${nxt[1].toUpperCase()}`, line: lineAt(src, offset(words[w].i)) };
    if (cur[1] === ";") return { message: "Run one statement at a time: remove what follows the ;", line: lineAt(src, offset(words[w + 1].i)) };
    if (cur[0] === "kw" && nxt[0] === "kw" && cur[1].toLowerCase() === nxt[1].toLowerCase() && !["end"].includes(cur[1].toLowerCase())) return { message: `${cur[1].toUpperCase()} is written twice`, line: lineAt(src, offset(words[w + 1].i)) };
  }
  return null;
}

function checkJson(src) {
  if (!src.trim()) return { message: "Write a JSON value, like {}", line: 1 };
  try { JSON.parse(src); return null; } catch (err) {
    const msg = err instanceof Error ? err.message : String(err);
    const lc = /line (\d+)/i.exec(msg);
    const pos = /position (\d+)/i.exec(msg);
    const line = lc ? Number(lc[1]) : pos ? lineAt(src, Number(pos[1])) : lineAt(src, src.length);
    const plain = msg.replace(/^JSON\.parse: /, "").replace(/ in JSON at position \d+.*$/, "").replace(/ at line \d+ column \d+.*$/, "");
    return { message: /end of (JSON )?(data|input)/i.test(msg) ? "The JSON ends too early: close every { and [" : plain, line };
  }
}

export function check(code, lang) {
  if (lang === "sql") return checkSql(code);
  if (lang === "json") return checkJson(code);
  if (lang === "formula") return code.trim() ? checkBrackets(code, tokenize(code, "formula")) : { message: "Write a formula", line: 1 };
  return null;
}

// ---------- line diff (marks what the agent changed) ----------

/** A line diff: common ends trimmed, an LCS on the middle (a few hundred lines at most). */
export function diffLines(a, b) {
  let p = 0;
  while (p < a.length && p < b.length && a[p] === b[p]) p++;
  let q = 0;
  while (q < a.length - p && q < b.length - p && a[a.length - 1 - q] === b[b.length - 1 - q]) q++;
  const am = a.slice(p, a.length - q), bm = b.slice(p, b.length - q);
  const dp = Array.from({ length: am.length + 1 }, () => new Array(bm.length + 1).fill(0));
  for (let i = am.length - 1; i >= 0; i--) for (let j = bm.length - 1; j >= 0; j--) dp[i][j] = am[i] === bm[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
  const out = [];
  for (let i = 0; i < p; i++) out.push({ op: " ", text: a[i], a: i, b: i });
  let i = 0, j = 0;
  while (i < am.length || j < bm.length) {
    if (i < am.length && j < bm.length && am[i] === bm[j]) { out.push({ op: " ", text: am[i], a: p + i, b: p + j }); i++; j++; }
    else if (j < bm.length && (i >= am.length || dp[i][j + 1] >= dp[i + 1][j])) { out.push({ op: "+", text: bm[j], b: p + j }); j++; }
    else { out.push({ op: "-", text: am[i], a: p + i }); i++; }
  }
  for (let k = q; k > 0; k--) out.push({ op: " ", text: a[a.length - k], a: a.length - k, b: b.length - k });
  return out;
}

/** "3", "3–5", "3, 7 and 9" */
function lineList(nums) {
  const runs = [];
  for (let i = 0; i < nums.length; i++) {
    let j = i;
    while (j + 1 < nums.length && nums[j + 1] === nums[j] + 1) j++;
    runs.push(j > i ? `${nums[i]}–${nums[j]}` : String(nums[i]));
    i = j;
  }
  return runs.length > 1 ? `${runs.slice(0, -1).join(", ")} and ${runs[runs.length - 1]}` : runs[0] ?? "";
}

function normalize(raw) {
  const s = (raw ?? {});
  const lang = s.language === "json" || s.language === "formula" || s.language === "text" ? s.language : "sql";
  return { ...s, title: String(s.title ?? ""), language: lang, code: String(s.code ?? "").replace(/\r\n?/g, "\n") };
}

/** Writes the textarea without moving the caret: text before it stays put, text after it shifts with the change. */
function setValue(el, value, focused) {
  if (el.value === value) return;
  if (!focused) { el.value = value; return; }
  const old = el.value, start = el.selectionStart, end = el.selectionEnd, dir = el.selectionDirection;
  let p = 0;
  while (p < old.length && p < value.length && old[p] === value[p]) p++;
  let q = 0;
  while (q < old.length - p && q < value.length - p && old[old.length - 1 - q] === value[value.length - 1 - q]) q++;
  const map = (c) => (c <= p ? c : c >= old.length - q ? value.length - (old.length - c) : value.length - q);
  el.value = value;
  el.setSelectionRange(map(start), map(end), dir);
}

const SHARE_DELAY_MS = 600;
const CHECK_DELAY_MS = 250;
let seq = 0;

/**
 * Desktop canvas (CODE, EDIT_MODE). A code editor with line numbers, highlighting, a live check and a Run preview.
 * The user's typing is shared 600 ms after they stop; the agent's edits arrive through onStateChange, keep the caret,
 * and are marked line by line until the user edits those lines.
 */
export function mount({ root, head, canvas, data, actions }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-cd", CSS);
  const doc = root.ownerDocument;
  const win = doc.defaultView ?? window;
  const reduce = !!win.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
  const rootNode = root.getRootNode();
  const n = ++seq;
  const isMac = /Mac|iPhone|iPad/.test(win.navigator?.platform ?? "");

  let shared = normalize(structuredClone(canvas?.state ?? data));
  let model = structuredClone(shared);
  let aiLines = new Set(); // 0-based lines the agent changed, until the user edits them
  let before = null; // the code before the agent's last edit (Undo, Show changes)
  let replacedLocal = false;
  let showDiff = false;
  let problem = null;
  let checking = false;
  let checkToken = 0;
  let checkTimer = 0;
  let shareTimer = 0;
  let share = "saved";
  let res = model.lastRun?.ok === false ? { kind: "error", message: model.lastRun.error ?? "The last run failed.", code: model.code } : { kind: "idle" };
  let escaped = false;
  let saving = false;
  let lastTitle = "";

  // ---------- elements ----------
  const ta = h("textarea", {
    class: "fsk-cd-ta", spellcheck: "false", autocapitalize: "off", autocomplete: "off", wrap: "off",
    "aria-label": `${LANG_LABEL[model.language]} code`, "aria-describedby": `fsk-cd${n}-st fsk-cd${n}-hint`, "aria-multiline": "true",
    placeholder: model.language === "sql" ? "SELECT …" : model.language === "json" ? "{ }" : "",
  });
  ta.value = model.code;
  const hl = h("div", { class: "fsk-cd-hl", "aria-hidden": "true" });
  const gutter = h("div", { class: "fsk-cd-gutter", "aria-hidden": "true" });
  const edArea = h("div", { class: "fsk-cd-ed" }, hl, ta);
  const codeGrid = h("div", { class: "fsk-cd-code" }, gutter, edArea);
  const scroll = h("div", { class: "fsk-cd-scroll" }, codeGrid);
  const note = h("div", { class: "fsk-cd-note", hidden: true });
  const pos = h("span", { class: "fsk-cd-pos" });
  const hint = h("span", { class: "fsk-cd-hint", id: `fsk-cd${n}-hint` }, "Tab indents. Esc, then Tab, leaves the editor.");
  const shareEl = h("span", { class: "fsk-cd-share fsk-cd-long" });
  const problemBtn = h("button", { class: "fsk-cd-problem", type: "button", id: `fsk-cd${n}-st`, onclick: () => goToProblem() });
  const box = h("div", { class: "fsk-cd-box" }, note, scroll,
    h("div", { class: "fsk-cd-status" }, h("span", {}, LANG_LABEL[model.language]), pos, hint, shareEl, problemBtn));
  const resMeta = h("span", { class: "fsk-cd-res-meta", role: "status" });
  const resStale = h("span", { class: "fsk-cd-stale", hidden: true }, icon("info", 12), "The code changed since this run");
  const resBody = h("div", { class: "fsk-cd-res-body" });
  const resPanel = h("section", { class: "fsk-cd-res", "aria-labelledby": `fsk-cd${n}-res` },
    h("div", { class: "fsk-cd-res-head" }, h("h3", { id: `fsk-cd${n}-res` }, "Preview"), resMeta, resStale), resBody);
  const runBtn = h("button", { class: "fsk-btn fsk-btn--primary", type: "button", onclick: () => void run() });
  const saveBtn = h("button", { class: "fsk-btn fsk-btn--ghost", type: "button", onclick: () => void save() }, "Save");
  const live = h("div", { class: "fsk-sr", role: "status", "aria-live": "polite" });
  const titleEl = h("h2", { class: "fsk-cd-title" }, model.title);
  const introEl = h("p", { class: "fsk-cd-intro", hidden: !model.intro }, model.intro ?? "");
  const langEl = h("span", { class: "fsk-cd-lang" }, LANG_LABEL[model.language]);

  // ---------- painting ----------
  function paintCode(flash = []) {
    const lines = lineEls(model.code, model.language);
    const bad = problem?.line ? problem.line - 1 : -1;
    const cur = lineAt(ta.value, ta.selectionStart) - 1;
    lines.forEach((el, i) => {
      if (aiLines.has(i)) el.className = "fsk-cd-l--ai";
      if (i === bad) el.className = "fsk-cd-l--bad";
      if (flash.includes(i) && !reduce) el.classList.add("fsk-cd-flash");
    });
    hl.replaceChildren(...lines);
    // focus and caret scrolling must not tuck the code under the sticky gutter
    win.requestAnimationFrame(() => { scroll.style.scrollPaddingLeft = `${gutter.offsetWidth}px`; });
    gutter.replaceChildren(...lines.map((_, i) => h("div", {
      class: [i === cur && "fsk-cd-g--cur", aiLines.has(i) && "fsk-cd-g--ai", i === bad && "fsk-cd-g--bad"].filter(Boolean).join(" ") || null,
    }, String(i + 1))));
  }

  function paintPos() {
    const v = ta.value.slice(0, ta.selectionStart);
    const line = v.split("\n").length;
    const col = v.length - v.lastIndexOf("\n");
    pos.textContent = `Ln ${line}, Col ${col}`;
    const cur = line - 1;
    gutter.querySelectorAll(".fsk-cd-g--cur").forEach((e) => e.classList.remove("fsk-cd-g--cur"));
    gutter.children[cur]?.classList.add("fsk-cd-g--cur");
  }

  function paintProblem() {
    if (checking) {
      problemBtn.setAttribute("data-busy", "");
      problemBtn.removeAttribute("data-bad");
      problemBtn.replaceChildren(h("span", { class: "fsk-cd-dot", "aria-hidden": "true" }), "Checking…");
    } else if (problem) {
      problemBtn.removeAttribute("data-busy");
      problemBtn.setAttribute("data-bad", "");
      problemBtn.title = "Go to the problem";
      problemBtn.replaceChildren(icon("alert", 13), h("span", {}, `${problem.line ? `Line ${problem.line}: ` : ""}${problem.message}`));
    } else {
      problemBtn.removeAttribute("data-busy");
      problemBtn.removeAttribute("data-bad");
      problemBtn.title = "";
      problemBtn.replaceChildren(icon("check", 13), "Valid");
    }
    if (problem && !checking) box.setAttribute("data-bad", ""); else box.removeAttribute("data-bad");
    ta.setAttribute("aria-invalid", String(!!problem && !checking));
  }

  function paintShare(s) {
    share = s;
    shareEl.dataset.s = s;
    shareEl.replaceChildren(...(
      s === "pending" ? [h("span", { class: "fsk-cd-dot", "aria-hidden": "true" }), "Sharing…"]
      : s === "partial" ? [icon("alert", 12), "Too long: the agent sees part of it"]
      : s === "error" ? [icon("alert", 12), "Not shared. Keep typing to retry."]
      : [icon("check", 12), "The agent sees this"]));
  }

  function paintNote() {
    if (before == null) { note.hidden = true; return; }
    const lines = [...aiLines].sort((a, b) => a - b).map((i) => i + 1);
    const removed = diffLines(before.split("\n"), model.code.split("\n")).filter((d) => d.op === "-").length;
    const what = lines.length ? `changed line${lines.length === 1 ? "" : "s"} ${lineList(lines)}` : removed ? `removed ${removed === 1 ? "a line" : `${removed} lines`}` : "edited the code";
    note.hidden = false;
    note.replaceChildren(icon("sparkle", 14),
      h("span", {}, h("b", {}, "The agent "), `${what}.`, replacedLocal ? " Your unsent edit was replaced; Undo brings it back." : ""),
      h("button", { class: "fsk-cd-link", type: "button", "aria-pressed": String(showDiff), onclick: () => toggleDiff() }, icon(showDiff ? "pencil" : "eye", 13), showDiff ? "Back to editing" : "Show changes"),
      h("button", { class: "fsk-cd-link", type: "button", onclick: () => undoAgent() }, icon("undo", 13), "Undo"),
      h("button", { class: "fsk-cd-link", type: "button", "aria-label": "Dismiss", title: "Dismiss", onclick: () => dismissNote() }, icon("x", 13)));
  }

  function paintDiff() {
    if (!showDiff || before == null) {
      if (!edArea.isConnected) scroll.replaceChildren(codeGrid);
      return;
    }
    const d = diffLines(before.split("\n"), model.code.split("\n"));
    scroll.replaceChildren(h("div", { class: "fsk-cd-diff", role: "region", "aria-label": "What the agent changed" },
      d.map((x) => h("div", { class: x.op === "+" ? "fsk-cd-d--add" : x.op === "-" ? "fsk-cd-d--del" : "" },
        h("span", {}, x.a != null ? String(x.a + 1) : ""), h("span", {}, x.b != null ? String(x.b + 1) : ""),
        h("span", { "aria-label": x.op === "+" ? "added" : x.op === "-" ? "removed" : null }, x.op === " " ? "" : x.op === "-" ? "−" : "+"),
        x.text || " "))));
  }

  function paintRun() {
    const label = model.runLabel ?? "Run";
    runBtn.disabled = res.kind === "running" || !actions?.run;
    runBtn.replaceChildren(...(res.kind === "running"
      ? [h("span", { class: "fsk-spinner", "aria-hidden": "true" }), "Running…"]
      : [icon("play", 13), label, h("span", { class: "fsk-cd-kbd fsk-cd-long", "aria-hidden": "true" }, isMac ? "⌘↵" : "Ctrl ↵")]));
    runBtn.title = `${label} (${isMac ? "⌘" : "Ctrl"}+Enter)`;
    resStale.hidden = !(res.kind === "ok" || res.kind === "error") || res.code === model.code;
    resMeta.removeAttribute("data-ok");
    resMeta.removeAttribute("data-bad");
    if (res.kind === "idle") {
      resMeta.replaceChildren();
      resBody.replaceChildren(h("div", { class: "fsk-cd-res-empty" }, icon("play", 18),
        h("span", {}, actions?.run ? ["The result shows here when you run it: ", h("kbd", {}, isMac ? "⌘" : "Ctrl"), " ", h("kbd", {}, "Enter")] : "Your app shows a preview here once it can run the code.")));
    } else if (res.kind === "running") {
      resMeta.replaceChildren("Running…");
      resBody.replaceChildren(h("div", { class: "fsk-cd-res-skel", "aria-hidden": "true" },
        Array.from({ length: 4 }, (_, i) => h("div", { style: { display: "flex", gap: "16px" } }, [40, 22, 18, 14].map((w) => bone(`${w}%`, "10px", { i }))))));
    } else if (res.kind === "error") {
      resMeta.setAttribute("data-bad", "");
      resMeta.replaceChildren(icon("alert", 13), "Didn't run");
      resBody.replaceChildren(h("div", { class: "fsk-cd-res-err", role: "alert" }, icon("alert", 16),
        h("div", {}, h("p", {}, "Nothing changed. Fix the code, or ask the agent to, then run it again."), h("pre", {}, res.message),
          h("button", { class: "fsk-btn fsk-btn--ghost", type: "button", onclick: () => void run() }, icon("refresh", 14), "Try again"))));
    } else {
      const r = res.result;
      resMeta.setAttribute("data-ok", "");
      const count = r.rows?.length ?? 0;
      resMeta.replaceChildren(icon("check", 13), r.rows ? `${count} ${count === 1 ? "row" : "rows"}` : "Done", ` · ${Math.round(res.ms)} ms`, r.note ? ` · ${r.note}` : "");
      if (r.rows && r.columns) {
        const numeric = r.columns.map((_, c) => r.rows.every((row) => row[c] == null || typeof row[c] === "number"));
        resBody.replaceChildren(h("table", {},
          h("thead", {}, h("tr", {}, r.columns.map((c, i) => h("th", { scope: "col", class: numeric[i] ? "fsk-cd-numc" : null }, c)))),
          h("tbody", {}, r.rows.slice(0, 50).map((row) => h("tr", {}, row.map((v, i) =>
            h("td", { class: v == null ? "fsk-cd-null" : numeric[i] ? "fsk-cd-numc" : null, title: v == null ? null : String(v) },
              v == null ? "null" : typeof v === "number" ? v.toLocaleString() : String(v))))))));
      } else resBody.replaceChildren(h("pre", { class: "fsk-cd-out" }, r.output ?? ""));
    }
  }

  function syncTitle() {
    const t = (model.canvasTitle ?? model.title).replace(/\s+/g, " ").slice(0, 80);
    if (t !== lastTitle) { lastTitle = t; canvas?.setTitle?.(t); }
    titleEl.textContent = model.title;
    introEl.textContent = model.intro ?? "";
    introEl.hidden = !model.intro;
    langEl.textContent = LANG_LABEL[model.language];
  }

  // ---------- checking ----------
  function scheduleCheck(now = false) {
    win.clearTimeout(checkTimer);
    if (now) { void runCheck(); return; }
    checkTimer = win.setTimeout(() => void runCheck(), CHECK_DELAY_MS);
  }

  async function runCheck() {
    const token = ++checkToken;
    const code = model.code;
    const builtIn = check(code, model.language);
    if (!actions?.validate || builtIn) { problem = builtIn; checking = false; paintProblem(); paintCode(); return; }
    checking = true;
    paintProblem();
    let p = null;
    try { p = await actions.validate(code, model.language); } catch (err) { p = { message: err instanceof Error ? err.message : "Couldn't check the code" }; }
    if (token !== checkToken) return; // the code changed meanwhile
    problem = p;
    checking = false;
    paintProblem();
    paintCode();
  }

  function goToProblem() {
    if (!problem?.line) return;
    if (showDiff) toggleDiff();
    const lines = ta.value.split("\n");
    const at = lines.slice(0, problem.line - 1).reduce((n, l) => n + l.length + 1, 0);
    ta.focus();
    ta.setSelectionRange(at, at + (lines[problem.line - 1]?.length ?? 0));
    paintPos();
  }

  // ---------- sharing ----------
  function later() {
    paintShare("pending");
    win.clearTimeout(shareTimer);
    shareTimer = win.setTimeout(flush, SHARE_DELAY_MS);
  }

  function flush() {
    win.clearTimeout(shareTimer);
    shareTimer = 0;
    if (model.code === shared.code) { paintShare(share === "pending" ? "saved" : share); return; }
    const before = shared;
    shared = { ...shared, code: model.code };
    // In-page answers at once, hosted with a Promise; ok: false means the SDK kept the old state.
    afterSetState(canvas?.setState?.({ code: model.code }), (out) => {
      if (out?.ok === false) { shared = before; paintShare("error"); return; }
      paintShare(out?.notSent?.length ? "partial" : "saved");
    });
    actions?.onChange?.(structuredClone(model));
  }

  // ---------- the user's edits ----------
  function onInput() {
    const old = model.code.split("\n");
    model.code = ta.value;
    if (aiLines.size) {
      // keep the marks on lines the user didn't touch
      const next = new Set();
      for (const d of diffLines(old, model.code.split("\n"))) if (d.op === " " && d.a != null && d.b != null && aiLines.has(d.a)) next.add(d.b);
      aiLines = next;
      if (!aiLines.size) { before = null; replacedLocal = false; }
      paintNote();
    }
    if (problem) problem = { ...problem, line: undefined }; // the old line may have moved: re-check first
    paintCode();
    paintPos();
    paintRun();
    scheduleCheck();
    later();
  }

  function replaceSelection(text, selStart, selEnd, caret) {
    ta.focus();
    ta.setSelectionRange(selStart, selEnd);
    // insertText keeps the browser's undo history; setRangeText is the fallback
    const ok = typeof doc.execCommand === "function" && doc.execCommand("insertText", false, text);
    if (!ok) { ta.setRangeText(text, selStart, selEnd, "end"); onInput(); }
    ta.setSelectionRange(caret, caret);
  }

  function onKey(e) {
    if (e.isComposing) return;
    const v = ta.value, s = ta.selectionStart, end = ta.selectionEnd;
    const lineStart = v.lastIndexOf("\n", s - 1) + 1;
    if (e.key === "Escape") { escaped = true; e.stopPropagation(); return; }
    if (e.key === "Tab" && escaped) { escaped = false; return; } // let focus leave
    escaped = false;
    if ((e.ctrlKey || e.metaKey) && e.key === "Enter") { e.preventDefault(); void run(); return; }
    if (e.key === "Tab") {
      e.preventDefault();
      const multi = v.slice(s, end).includes("\n");
      if (!multi && !e.shiftKey) { replaceSelection("  ", s, end, s + 2); return; }
      // indent or outdent every selected line
      const blockEnd = v.indexOf("\n", end - (end > s && v[end - 1] === "\n" ? 1 : 0));
      const stop = blockEnd < 0 ? v.length : blockEnd;
      const block = v.slice(lineStart, stop);
      const lines = block.split("\n");
      const next = lines.map((l) => (e.shiftKey ? l.replace(/^ {1,2}/, "") : `  ${l}`)).join("\n");
      replaceSelection(next, lineStart, stop, 0);
      ta.setSelectionRange(lineStart, lineStart + next.length);
      return;
    }
    if (e.key === "Enter" && !e.shiftKey && !e.altKey) {
      e.preventDefault();
      const indent = /^[ \t]*/.exec(v.slice(lineStart, s))?.[0] ?? "";
      const prev = v.slice(lineStart, s).trimEnd();
      const extra = /[([{]$/.test(prev) ? "  " : "";
      const ins = `\n${indent}${extra}`;
      replaceSelection(ins, s, end, s + ins.length);
    }
  }

  // ---------- the agent's edits ----------
  function applyRemote(next) {
    const remote = normalize(structuredClone(next));
    const focused = rootNode.activeElement === ta;
    const langChanged = remote.language !== model.language;
    if (remote.code !== shared.code) {
      const prev = model.code;
      replacedLocal = model.code !== shared.code; // the user had typing the agent hadn't seen
      before = prev;
      const d = diffLines(prev.split("\n"), remote.code.split("\n"));
      aiLines = new Set(d.filter((x) => x.op === "+" && x.b != null).map((x) => x.b));
      model = { ...remote };
      setValue(ta, model.code, focused);
      showDiff = false;
      paintDiff();
      paintCode([...aiLines]);
      paintNote();
      const lines = [...aiLines].sort((a, b) => a - b).map((i) => i + 1);
      live.textContent = `The agent ${lines.length ? `changed line${lines.length === 1 ? "" : "s"} ${lineList(lines)}` : "edited the code"}.`;
      // bring the first change into view without moving the caret
      const first = Math.min(...aiLines);
      if (Number.isFinite(first)) {
        const el = hl.children[first];
        if (el instanceof HTMLElement && !focused) el.scrollIntoView({ block: "nearest", behavior: reduce ? "auto" : "smooth" });
      }
    } else {
      model = { ...remote, code: model.code };
    }
    shared = remote;
    if (langChanged) ta.setAttribute("aria-label", `${LANG_LABEL[model.language]} code`);
    syncTitle();
    paintPos();
    paintRun();
    scheduleCheck(true);
    if (model.code !== shared.code) later(); else paintShare(share === "pending" ? "saved" : share);
  }

  function toggleDiff() {
    showDiff = !showDiff;
    paintDiff();
    paintNote();
    if (!showDiff) ta.focus({ preventScroll: true });
  }

  function undoAgent() {
    if (before == null) return;
    const text = before;
    before = null;
    aiLines = new Set();
    replacedLocal = false;
    showDiff = false;
    paintDiff();
    paintNote();
    replaceSelection(text, 0, ta.value.length, 0);
    if (model.code !== text) { ta.value = text; onInput(); }
    live.textContent = "Undid the agent's edit.";
  }

  function dismissNote() {
    before = null;
    aiLines = new Set();
    replacedLocal = false;
    showDiff = false;
    paintDiff();
    paintNote();
    paintCode();
    ta.focus({ preventScroll: true });
  }

  // ---------- run and save ----------
  async function run() {
    if (!actions?.run || res.kind === "running") return;
    win.clearTimeout(checkTimer);
    await runCheck();
    if (problem) { goToProblem(); live.textContent = `Not run: ${problem.message}`; return; }
    flush(); // the agent sees what runs
    const code = model.code;
    res = { kind: "running" };
    paintRun();
    const t0 = win.performance.now();
    try {
      const result = await actions.run(code, model.language);
      res = { kind: "ok", result, at: new Date().toISOString(), ms: win.performance.now() - t0, code };
      const lastRun = { ok: true, at: res.at, rows: result.rows?.length };
      model.lastRun = lastRun;
      canvas?.setState?.({ lastRun });
      live.textContent = result.rows ? `Ran: ${result.rows.length} rows.` : "Ran.";
    } catch (err) {
      const message = (err instanceof Error && err.message) || "It didn't run. Nothing changed.";
      const line = /line (\d+)/i.exec(message);
      res = { kind: "error", message, code, line: line ? Number(line[1]) : undefined };
      if (line) { problem = { message: message.replace(/\s*\(?\bline \d+\)?\.?\s*$/i, ""), line: Number(line[1]) }; paintProblem(); paintCode(); }
      const lastRun = { ok: false, at: new Date().toISOString(), error: message.slice(0, 300) };
      model.lastRun = lastRun;
      canvas?.setState?.({ lastRun });
    }
    paintRun();
  }

  async function save() {
    if (!actions?.save || saving) return;
    await runCheck();
    if (problem) { goToProblem(); return; }
    flush();
    saving = true;
    saveBtn.disabled = true;
    saveBtn.replaceChildren(h("span", { class: "fsk-spinner", "aria-hidden": "true" }), "Saving…");
    try {
      await actions.save(model.code);
      saveBtn.replaceChildren(icon("check", 14), "Saved");
      live.textContent = "Saved.";
      win.setTimeout(() => { if (saveBtn.isConnected) saveBtn.replaceChildren("Save"); }, 2000);
    } catch (err) {
      saveBtn.replaceChildren("Save");
      live.textContent = (err instanceof Error && err.message) || "Couldn't save. Your code is kept.";
      problem = { message: live.textContent };
      paintProblem();
    } finally {
      saving = false;
      saveBtn.disabled = false;
    }
  }

  // ---------- draw ----------
  ta.addEventListener("input", onInput);
  ta.addEventListener("keydown", onKey);
  ta.addEventListener("blur", () => { if (shareTimer) flush(); });
  for (const ev of ["keyup", "click", "select", "focus"]) ta.addEventListener(ev, paintPos);
  root.replaceChildren(h("div", { class: "fsk fsk-cd" },
    h("header", { class: "fsk-cd-top" },
      h("div", {},
        h("div", { class: "fsk-cd-badges" }, h("span", { class: "fsk-badge fsk-badge--agent" }, icon("zap", 12), "Code"), langEl),
        titleEl, introEl),
      h("div", { class: "fsk-cd-actions" }, actions?.save && saveBtn, runBtn)),
    box,
    resPanel,
    live));
  syncTitle();
  paintCode();
  paintPos();
  paintShare("saved");
  paintRun();
  scheduleCheck(true);
  const off = canvas?.onStateChange?.((next) => applyRemote(next));

  return () => {
    if (shareTimer) flush(); // closing keeps the state: share the last keystrokes
    win.clearTimeout(checkTimer);
    off?.();
    root.replaceChildren();
  };
}

/** Mobile has no canvas: a read-only card with the first lines, highlighted, and whether it's valid. */
export function mountMobile({ root, head, data, api }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-cd", CSS);
  const s = normalize(structuredClone(data));
  const lines = s.code.split("\n");
  const p = check(s.code, s.language);
  const last = s.lastRun;
  root.replaceChildren(h("section", { class: "fsk fsk-card fsk-cdm", "aria-label": s.title },
    h("header", { class: "fsk-head" },
      h("span", { class: "fsk-chip" }, icon("zap", 18)),
      h("div", {}, h("h3", { class: "fsk-title" }, s.title), h("p", { class: "fsk-sub" }, `${LANG_LABEL[s.language]} · ${lines.length} ${lines.length === 1 ? "line" : "lines"}`))),
    h("pre", { class: "fsk-cdm-code", tabindex: "0", "aria-label": `${LANG_LABEL[s.language]} code, first lines` }, lineEls(lines.slice(0, 12).join("\n"), s.language)),
    h("p", { class: "fsk-cdm-row" },
      p ? h("span", { class: "fsk-cdm-bad" }, icon("alert", 13), `${p.line ? `Line ${p.line}: ` : ""}${p.message}`) : h("span", { class: "fsk-cdm-ok" }, icon("check", 13), "Valid"),
      last && h("span", {}, icon("clock", 13), last.ok ? `Ran ${formatRelative(last.at)}${last.rows != null ? `: ${last.rows} rows` : ""}` : `Last run failed ${formatRelative(last.at)}`)),
    h("p", { class: "fsk-cdm-desk" }, icon("expand", 16),
      h("span", {}, h("strong", {}, "Open on desktop"), "Edit and run it beside the chat on a larger screen. The agent keeps what you've written."))));
  api?.displayed?.();
  return () => root.replaceChildren();
}

/** The states this canvas draws besides its data. */
export const states = ["loading", "empty", "error"];

/**
 * Loading, empty or error. Desktop ("desktop", the default): the canvas panel, with a skeleton in the editor's shape,
 * or the message centered in the panel. Mobile: the snippet card.
 */
export function mountState({ root, head, state, title, subtitle, surface = "desktop", canvas }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-cd", CSS);
  if (surface === "mobile") {
    const card = stateCard({ state, cls: "fsk-cdm", icon: "zap", title, subtitle, surface, skeleton: () => h("div", {},
      h("div", { class: "fsk-cdm-code", style: { display: "flex", flexDirection: "column", gap: "9px" } }, [38, 52, 46, 30, 60, 24].map((w, i) => bone(`${w}%`, "9px", { i }))),
      h("div", { style: { marginTop: "12px" } }, bone("100%", "56px", { cls: "fsk-bone--box", i: 3 }))) });
    root.replaceChildren(card.el);
    return () => { card.dispose(); root.replaceChildren(); };
  }
  if (title) canvas?.setTitle(title);
  const loading = state.kind === "loading";
  let dispose = () => {};
  let body;
  if (state.kind === "loading") {
    const widths = [62, 18, 34, 40, 30, 52, 0, 26, 58, 44, 50, 22];
    const indent = [0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0];
    body = h("div", { style: { display: "contents" }, "aria-hidden": "true" },
      h("div", { class: "fsk-cd-box" }, h("div", { class: "fsk-cd-skel" },
        h("div", { class: "fsk-cd-skel-g" }, widths.map((_, i) => bone("14px", "9px", { i }))),
        h("div", { class: "fsk-cd-skel-l" }, widths.map((w, i) => (w ? h("div", { style: { paddingLeft: `${indent[i] * 22}px` } }, bone(`${w}%`, "9px", { i })) : h("div", { style: { height: "9px" } })))))),
      h("div", { class: "fsk-cd-res" }, h("div", { class: "fsk-cd-res-head" }, bone("64px", "10px")),
        h("div", { class: "fsk-cd-res-skel" }, Array.from({ length: 3 }, (_, i) => h("div", { style: { display: "flex", gap: "16px" } }, [40, 22, 18].map((w) => bone(`${w}%`, "10px", { i })))))));
  } else if (state.kind === "empty") {
    body = h("div", { class: "fsk-cd-center" }, h("div", {}, emptyBlock({ icon: "zap", ...state }, surface)));
  } else {
    const e = errorBlock(state, surface);
    dispose = e.dispose;
    body = h("div", { class: "fsk-cd-center" }, h("div", {}, e.el));
  }
  root.replaceChildren(h("div", {
    class: `fsk fsk-cd fsk-cd-state fsk-state--${state.kind}`, "data-state": state.kind,
    role: loading ? "status" : null, "aria-busy": loading ? "true" : null, "aria-live": loading ? "polite" : null,
  },
    loading && h("span", { class: "fsk-sr" }, state.label ?? "Loading…"),
    h("header", { class: "fsk-cd-top" },
      h("div", {},
        h("div", { class: "fsk-cd-badges" }, h("span", { class: "fsk-badge fsk-badge--agent" }, icon("zap", 12), "Code")),
        title ? h("h2", { class: "fsk-cd-title" }, title) : h("div", { style: { margin: "12px 0 6px" } }, bone("38%", "16px")),
        subtitle ? h("p", { class: "fsk-cd-intro" }, subtitle) : loading && bone("52%", "10px")),
      loading && h("div", { class: "fsk-cd-actions", "aria-hidden": "true" }, bone("92px", "36px", { cls: "fsk-bone--box" }))),
    body));
  return () => { dispose(); root.replaceChildren(); };
}

export const fixtures = {
  default: {
    canvasTitle: "Query: churned accounts",
    title: "Churned accounts last quarter",
    intro: "Read-only SQL on your reporting database. Ask me to change it, or edit it here and run a preview.",
    language: "sql",
    runLabel: "Run query",
    code: [
      "-- Accounts that canceled last quarter, with the MRR they took with them",
      "SELECT",
      "  a.name,",
      "  a.plan,",
      "  s.canceled_at::date AS churned_on,",
      "  ROUND(s.mrr_cents / 100.0, 2) AS mrr",
      "FROM accounts a",
      "JOIN subscriptions s ON s.account_id = a.id",
      "WHERE s.status = 'canceled'",
      "  AND s.canceled_at >= date_trunc('quarter', now()) - interval '3 months'",
      "  AND s.canceled_at < date_trunc('quarter', now())",
      "ORDER BY churned_on DESC",
      "LIMIT 100",
    ].join("\n"),
  },
};
```

### fs-kit (shared by every template)

TypeScript: /ui-catalog/files/ts/fs-kit.ts, JavaScript: /ui-catalog/files/js/fs-kit.js
