# Progress

A job the agent started (import, export, sync, bulk update) as it runs: overall progress, each step, elapsed and estimated time. The user can stop it, and when it ends, open the result, download the error report or retry what failed. The agent doesn't wait for it.

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

A job the agent started (import, export, sync, bulk update) as it runs: overall progress, each step, elapsed and estimated time. The user can stop it, and when it ends, open the result, download the error report or retry what failed. The agent doesn't wait for it.

## When to use it

**Use it when:** The agent started a job that takes more than a few seconds and runs on its own: an import, an export, a sync, a bulk update. The user wants to see it move, stop it, and act on what failed.

**Use something else when:** A change that finishes in a second or two (do it, then show the result). A yes or no before the job starts (confirm card first). Setup steps the user does by hand (onboarding guide). A job whose result the agent must read before it answers (wait in execute instead).

## What the agent receives

| The template calls | The agent gets | When |
| --- | --- | --- |
| `displayed()` | `FUNCTION_TOOL_DISPLAYED` | As soon as the card shows. The agent goes on and isn't told when the job ends: the user sees the outcome here, and the agent learns it on a later turn (a status action that reads the job) or from your app. |

## 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 the card starts the job again in place, for example after Try again. While execute runs, the SDK shows its own loader. |
| Empty | execute found nothing to run, here a file with no rows. Nothing started, and the card says why. |
| Error | The job didn't start, and execute returned the failure as data, so the agent can explain it. Try again starts 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

### ProgressData

| Field | Type | Notes |
| --- | --- | --- |
| `title` | `string` | Name the job as it runs, "Importing contacts"; send a new title when it ends, "Contacts imported". |
| `subtitle` (optional) | `string` |  |
| `icon` (optional) | `IconName` |  |
| `status` | `JobStatus` |  |
| `done` | `number` | Items handled so far. |
| `total` | `number` |  |
| `unit` (optional) | `string` | What's counted, plural: "rows", "files". Default "items". |
| `failed` (optional) | `number` | Items that failed. With status "partial" they're what Retry sends again. |
| `steps` | `ProgressStep[]` |  |
| `startedAt` (optional) | `string \| number` | When the job started (ISO string or ms). Default: when the card mounted. Elapsed time counts from it. |
| `finishedAt` (optional) | `string \| number` | When it ended. Default: when the card saw it end. Freezes elapsed time. |
| `etaSeconds` (optional) | `number` | Seconds left, when your job knows. Otherwise the card estimates it from the rate so far. |
| `summary` (optional) | `string` | The outcome in a sentence, under the result title: what happened, what failed and why. |
| `link` (optional) | `{ label: string; href: string }` | Where the result lives, e.g. "Open contacts". Shown when the job is done or partly done. |
| `reportHref` (optional) | `string` | A file of the failed items and why (CSV). Shows "Download error report". |
| `error` (optional) | `string` | status "failed": what went wrong, in the user's words, and whether anything changed. |
| `notice` (optional) | `string` | A passing problem while it runs, e.g. "Can't reach the import service. Retrying…". An empty string clears it. |
| `cancelable` (optional) | `boolean` | Show Cancel while running. Default: when actions.cancel is set. |
| `jobNoun` (optional) | `string` | The noun in buttons and the stop question, e.g. "import". Default "job". |

### ProgressStep

| Field | Type | Notes |
| --- | --- | --- |
| `id` | `string` |  |
| `label` | `string` |  |
| `status` | `StepStatus` |  |
| `detail` (optional) | `string` | One short line under the label: "214 merged", or why it failed or was skipped. |
| `failed` (optional) | `number` | Items this step couldn't handle. A done step with failures shows a warning mark and "12 failed". |

### ProgressActions

| Field | Type | Notes |
| --- | --- | --- |
| `subscribe()` (optional) | `(onChange: (patch: ProgressPatch) => void) => () => void` | Your job's updates (app events, polling). Call onChange with each change; the card redraws and announces step changes. Return the unsubscribe. |
| `cancel()` (optional) | `() => Promise<unknown>` | Stops the job. Throw to keep it running and show why. Without it, there's no Cancel. |
| `retry()` (optional) | `() => Promise<unknown>` | Runs again what failed: the failed items for "partial", the job for "failed". New progress arrives through subscribe. |
| `download()` (optional) | `(href: string) => void` | Downloads the error report. Hosted actions pass ctx.ui.download (the sandbox blocks native downloads). Without it, a download link. |

## 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/progress.hosted.ts), [JavaScript](/ui-catalog/files/js/usage/progress.hosted.js)
- In-page handler: [TypeScript](/ui-catalog/files/ts/usage/progress.component.ts), [JavaScript](/ui-catalog/files/js/usage/progress.component.js)
- progress: [TypeScript](/ui-catalog/files/ts/progress.ts), [JavaScript](/ui-catalog/files/js/progress.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/import_contacts/index.ts"
// agent/actions/import_contacts/index.ts: a hosted action.
// Copy the template (progress.ts) and fs-kit.ts into agent/ui/.

interface Job { id: string; state: "running" | "done" | "partial" | "failed" | "cancelled"; processed: number; total: number; failed: number;
  startedAt: string; finishedAt?: string; steps: { key: string; name: string; state: StepStatus; note?: string; failed?: number }[];
  errorReportUrl?: string; message?: string }
type Result = (ProgressData & { jobId: string }) | { error: string };

// The job's state, in the card's terms. Your import service's names stay on this side.
const toPatch = (j: Job) => ({
  status: j.state, done: j.processed, total: j.total, failed: j.failed, startedAt: j.startedAt, finishedAt: j.finishedAt,
  title: j.state === "running" ? "Importing contacts" : j.state === "cancelled" ? "Import stopped" : "Contacts imported",
  steps: j.steps.map((s): ProgressStep => ({ id: s.key, label: s.name, status: s.state, detail: s.note, failed: s.failed })),
  summary: j.message, error: j.state === "failed" ? j.message : undefined, reportHref: j.errorReportUrl,
  link: j.state === "done" || j.state === "partial" ? { label: "Open contacts", href: `/contacts?import=${j.id}` } : undefined,
});

// execute starts the job and returns at once with its id. It doesn't wait for the job to finish.
export async function execute(args: { fileId: string; listId?: string }, ctx: ActionContext): Promise<Result> {
  const res = await ctx.fetch("/api/imports", { method: "POST", body: JSON.stringify(args), headers: { "content-type": "application/json" } });
  // A failure goes back as data: the agent explains it, and the card shows it.
  if (!res.ok) return { error: `The import didn't start (${res.status}). Nothing was imported.` };
  const job: Job = await res.json();
  // The agent reads this: the job id, so it can check on the job later with get_import_status.
  return { jobId: job.id, subtitle: "Contacts to your CRM", icon: "users", unit: "rows", jobNoun: "import", ...toPatch(job) };
}

// The agent doesn't wait: the card reports displayed() at once with the job id, and the conversation goes on.
// The agent isn't told when the job ends. The user sees it here; if they ask, the agent calls get_import_status.
export function render(result: Result, ctx: RenderContext) {
  const { root, head } = ctx.card;
  // jobId, not "error" in result: a job's own data has an error field (a failed job's message).
  if (!("jobId" in result)) {
    mountState({ root, head, title: "Import contacts", state: { kind: "error", text: result.error } });
    return ctx.card.displayed(result);
  }
  if (result.total === 0) {
    mountState({ root, head, title: "Import contacts", state: { kind: "empty", icon: "doc", title: "No rows to import", text: "The file has a header row but no contacts under it." } });
    return ctx.card.displayed({ jobId: result.jobId, status: result.status, total: 0 });
  }

  // Hosted cards can't hear your app's events, so they poll: every 2 s while the job runs, then stop.
  // Retry starts polling again. Five failed polls in a row show a notice; the card keeps trying.
  let onChange: (patch: ProgressPatch) => void = () => {};
  let timer: ReturnType<typeof setTimeout> | undefined;
  let misses = 0;
  const poll = async (): Promise<void> => {
    clearTimeout(timer);
    try {
      const r = await ctx.fetch(`/api/imports/${result.jobId}`);
      if (!r.ok) throw new Error(String(r.status));
      const job: Job = await r.json();
      misses = 0;
      onChange({ ...toPatch(job), notice: "" });
      if (job.state !== "running") return; // final: stop polling until a retry
    } catch {
      if (++misses >= 5) onChange({ notice: "Can't reach the import service. The import keeps running; this card catches up when it's back." });
    }
    timer = setTimeout(poll, misses ? 5000 : 2000);
  };

  ctx.card.onTeardown(() => clearTimeout(timer)); // render()'s return is ignored: stop polling when the card goes
  mount({
    root, head, data: result,
    api: { displayed: () => ctx.card.displayed({ jobId: result.jobId, status: result.status, total: result.total }) },
    actions: {
      subscribe: (cb) => { onChange = cb; timer = setTimeout(poll, 2000); return () => clearTimeout(timer); },
      // The sandbox blocks native downloads: the page downloads the report.
      download: (url) => { void ctx.ui.download({ url, filename: "import-errors.csv" }); },
      cancel: async () => {
        const r = await ctx.fetch(`/api/imports/${result.jobId}/cancel`, { method: "POST" });
        if (!r.ok) throw new Error("The import didn't stop. It's still running.");
        await poll();
      },
      retry: async () => {
        const r = await ctx.fetch(`/api/imports/${result.jobId}/retry`, { method: "POST" });
        if (!r.ok) throw new Error("The retry didn't start. The failed rows are unchanged.");
        await poll();
      },
    },
  });
}
```

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

// The job's state, in the card's terms. Your import service's names stay on this side.
const toPatch = (j) => ({
  status: j.state, done: j.processed, total: j.total, failed: j.failed, startedAt: j.startedAt, finishedAt: j.finishedAt,
  title: j.state === "running" ? "Importing contacts" : j.state === "cancelled" ? "Import stopped" : "Contacts imported",
  steps: j.steps.map((s) => ({ id: s.key, label: s.name, status: s.state, detail: s.note, failed: s.failed })),
  summary: j.message, error: j.state === "failed" ? j.message : undefined, reportHref: j.errorReportUrl,
  link: j.state === "done" || j.state === "partial" ? { label: "Open contacts", href: `/contacts?import=${j.id}` } : undefined,
});

// execute starts the job and returns at once with its id. It doesn't wait for the job to finish.
export async function execute(args, ctx) {
  const res = await ctx.fetch("/api/imports", { method: "POST", body: JSON.stringify(args), headers: { "content-type": "application/json" } });
  // A failure goes back as data: the agent explains it, and the card shows it.
  if (!res.ok) return { error: `The import didn't start (${res.status}). Nothing was imported.` };
  const job = await res.json();
  // The agent reads this: the job id, so it can check on the job later with get_import_status.
  return { jobId: job.id, subtitle: "Contacts to your CRM", icon: "users", unit: "rows", jobNoun: "import", ...toPatch(job) };
}

// The agent doesn't wait: the card reports displayed() at once with the job id, and the conversation goes on.
// The agent isn't told when the job ends. The user sees it here; if they ask, the agent calls get_import_status.
export function render(result, ctx) {
  const { root, head } = ctx.card;
  // jobId, not "error" in result: a job's own data has an error field (a failed job's message).
  if (!("jobId" in result)) {
    mountState({ root, head, title: "Import contacts", state: { kind: "error", text: result.error } });
    return ctx.card.displayed(result);
  }
  if (result.total === 0) {
    mountState({ root, head, title: "Import contacts", state: { kind: "empty", icon: "doc", title: "No rows to import", text: "The file has a header row but no contacts under it." } });
    return ctx.card.displayed({ jobId: result.jobId, status: result.status, total: 0 });
  }

  // Hosted cards can't hear your app's events, so they poll: every 2 s while the job runs, then stop.
  // Retry starts polling again. Five failed polls in a row show a notice; the card keeps trying.
  let onChange = () => {};
  let timer;
  let misses = 0;
  const poll = async () => {
    clearTimeout(timer);
    try {
      const r = await ctx.fetch(`/api/imports/${result.jobId}`);
      if (!r.ok) throw new Error(String(r.status));
      const job = await r.json();
      misses = 0;
      onChange({ ...toPatch(job), notice: "" });
      if (job.state !== "running") return; // final: stop polling until a retry
    } catch {
      if (++misses >= 5) onChange({ notice: "Can't reach the import service. The import keeps running; this card catches up when it's back." });
    }
    timer = setTimeout(poll, misses ? 5000 : 2000);
  };

  ctx.card.onTeardown(() => clearTimeout(timer)); // render()'s return is ignored: stop polling when the card goes
  mount({
    root, head, data: result,
    api: { displayed: () => ctx.card.displayed({ jobId: result.jobId, status: result.status, total: result.total }) },
    actions: {
      subscribe: (cb) => { onChange = cb; timer = setTimeout(poll, 2000); return () => clearTimeout(timer); },
      // The sandbox blocks native downloads: the page downloads the report.
      download: (url) => { void ctx.ui.download({ url, filename: "import-errors.csv" }); },
      cancel: async () => {
        const r = await ctx.fetch(`/api/imports/${result.jobId}/cancel`, { method: "POST" });
        if (!r.ok) throw new Error("The import didn't stop. It's still running.");
        await poll();
      },
      retry: async () => {
        const r = await ctx.fetch(`/api/imports/${result.jobId}/retry`, { method: "POST" });
        if (!r.ok) throw new Error("The retry didn't start. The failed rows are unchanged.");
        await poll();
      },
    },
  });
}
```

### In-page handler

```ts title="in-page handler.ts"
// An in-page action handler: the template runs in your page.

interface Params { fileId: string; listId?: string }
type Result = (ProgressData & { jobId: string }) | { error: string; params: Params };

foldspace("when", "ready", () => {
  foldspace.agent({ /* …common setup… */ }).addActionHandlers({
    import_contacts: {
      // Starts the job and returns at once with its id and first state. It doesn't wait for the job to finish.
      // A failure goes back as data, so the agent can explain it.
      execute: async (params: Params): Promise<Result> =>
        importJobs.start(params).catch(() => ({ error: "The import didn't start. Nothing was imported.", params })),

      // Declares readyState only: the agent goes on once the card reports it's shown, and the card stays live.
      // The agent isn't told when the job ends. The user sees it here; if they ask, the agent calls get_import_status.
      renderComponent: ({ data, host, header, readyState }: ComponentContext<Result>) => {
        // Once: on desktop a second readyState (after Retry) would start a new agent turn.
        const shown = once(readyState);
        const show = (result: Result): void => {
          // jobId, not "error" in result: a job's own data has an error field (a failed job's message).
          if ("jobId" in result) {
            return void mount({
              root: host, head: header, data: result,
              api: { displayed: () => shown({ jobId: result.jobId, status: result.status, total: result.total }) },
              actions: {
                // Your app already hears the job: pass its events straight in. Return the unsubscribe.
                subscribe: (onChange) => importJobs.on(result.jobId, (job: ProgressData) => onChange(job)),
                cancel: () => importJobs.cancel(result.jobId), // throw to keep it running and show why
                retry: () => importJobs.retryFailed(result.jobId), // new progress arrives through subscribe
              },
            });
          }
          mountState({
            root: host, head: header, title: "Import contacts",
            state: {
              kind: "error", text: result.error,
              // Retry in the card: bones while it starts, then the live job (or the error again).
              retry: async () => {
                mountState({ root: host, head: header, title: "Import contacts", state: { kind: "loading", label: "Starting the import…" } });
                show(await importJobs.start(result.params).catch(() => ({ error: "Still not starting. Try again in a minute.", params: result.params })));
              },
            },
          });
          shown(result);
        };
        show(data);
      },
    },
  });
});
```

```js title="in-page handler.js"
// An in-page action handler: the template runs in your page.

foldspace("when", "ready", () => {
  foldspace.agent({ /* …common setup… */ }).addActionHandlers({
    import_contacts: {
      // Starts the job and returns at once with its id and first state. It doesn't wait for the job to finish.
      // A failure goes back as data, so the agent can explain it.
      execute: async (params) =>
        importJobs.start(params).catch(() => ({ error: "The import didn't start. Nothing was imported.", params })),

      // Declares readyState only: the agent goes on once the card reports it's shown, and the card stays live.
      // The agent isn't told when the job ends. The user sees it here; if they ask, the agent calls get_import_status.
      renderComponent: ({ data, host, header, readyState }) => {
        // Once: on desktop a second readyState (after Retry) would start a new agent turn.
        const shown = once(readyState);
        const show = (result) => {
          // jobId, not "error" in result: a job's own data has an error field (a failed job's message).
          if ("jobId" in result) {
            return void mount({
              root: host, head: header, data: result,
              api: { displayed: () => shown({ jobId: result.jobId, status: result.status, total: result.total }) },
              actions: {
                // Your app already hears the job: pass its events straight in. Return the unsubscribe.
                subscribe: (onChange) => importJobs.on(result.jobId, (job) => onChange(job)),
                cancel: () => importJobs.cancel(result.jobId), // throw to keep it running and show why
                retry: () => importJobs.retryFailed(result.jobId), // new progress arrives through subscribe
              },
            });
          }
          mountState({
            root: host, head: header, title: "Import contacts",
            state: {
              kind: "error", text: result.error,
              // Retry in the card: bones while it starts, then the live job (or the error again).
              retry: async () => {
                mountState({ root: host, head: header, title: "Import contacts", state: { kind: "loading", label: "Starting the import…" } });
                show(await importJobs.start(result.params).catch(() => ({ error: "Still not starting. Try again in a minute.", params: result.params })));
              },
            },
          });
          shown(result);
        };
        show(data);
      },
    },
  });
});
```

### progress

```ts title="agent/ui/progress.ts"
// Template: progress. A long job the agent started (import, export, sync, bulk update), with its steps and live progress.

export const meta = {
  id: "progress",
  title: "Progress",
  surface: "card",
  kind: "interactive",
  mobile: "variant",
  whenToUse: "The agent started a job that takes more than a few seconds and runs on its own: an import, an export, a sync, a bulk update. The user wants to see it move, stop it, and act on what failed.",
  whenNotToUse: "A change that finishes in a second or two (do it, then show the result). A yes or no before the job starts (confirm card first). Setup steps the user does by hand (onboarding guide). A job whose result the agent must read before it answers (wait in execute instead).",
};

const CSS = `
.fsk-prog { container-type: inline-size; }
.fsk-prog:not(.fsk-state) .fsk-head { margin-bottom: 0; }
.fsk-prog .fsk-head > div { flex: 1; min-width: 0; }
.fsk-prog .fsk-head .fsk-pill { align-self: flex-start; margin-top: 2px; }
.fsk-prog .fsk-prog-live i { animation: fsk-prog-pulse 1.4s ease-in-out infinite; }

/* The meter: big percent, count, time, bar */
.fsk-prog .fsk-prog-figs { display: flex; align-items: flex-end; justify-content: space-between; flex-wrap: wrap; gap: 4px 12px; margin-top: 16px; }
.fsk-prog .fsk-prog-main { display: flex; align-items: baseline; flex-wrap: wrap; gap: 2px 8px; min-width: 0; }
.fsk-prog .fsk-prog-pct { font-size: 2em; font-weight: 650; letter-spacing: -0.03em; line-height: 1; }
.fsk-prog .fsk-prog-pct small { font-size: .55em; font-weight: 600; margin-left: 1px; color: var(--k-text-2); }
.fsk-prog .fsk-prog-count { font-size: .86em; color: var(--k-text-2); }
.fsk-prog .fsk-prog-count b { color: var(--k-text); font-weight: 600; }
.fsk-prog .fsk-prog-time { display: flex; align-items: center; flex-wrap: wrap; gap: 2px 10px; font-size: .82em; color: var(--k-text-2); }
.fsk-prog .fsk-prog-time > span { display: inline-flex; align-items: center; gap: 4px; white-space: nowrap; }
.fsk-prog .fsk-prog-time b { font-weight: 600; color: var(--k-text); }
.fsk-prog .fsk-prog-bar {
  position: relative; display: flex; height: 8px; margin-top: 10px; overflow: hidden;
  border-radius: calc(var(--k-r) * 100); background: color-mix(in srgb, var(--k-text) 9%, var(--k-paper));
}
.fsk-prog .fsk-prog-fill { position: relative; flex: none; height: 100%; overflow: hidden; background: var(--k-primary); transition: width .5s var(--k-ease), background .3s; }
.fsk-prog[data-status="running"] .fsk-prog-fill::after {
  content: ""; position: absolute; inset: 0; transform: translateX(-100%);
  background: linear-gradient(90deg, transparent, color-mix(in srgb, var(--k-on-primary) 45%, transparent), transparent);
  animation: fsk-shimmer 1.8s ease-in-out infinite;
}
.fsk-prog .fsk-prog-fail {
  flex: none; height: 100%; transition: width .5s var(--k-ease);
  background: repeating-linear-gradient(-45deg, var(--k-error) 0 3px, color-mix(in srgb, var(--k-error) 55%, var(--k-paper)) 3px 6px);
}
.fsk-prog[data-status="done"] .fsk-prog-fill, .fsk-prog[data-status="partial"] .fsk-prog-fill { background: var(--k-success); }
.fsk-prog[data-status="cancelled"] .fsk-prog-fill, .fsk-prog[data-status="failed"] .fsk-prog-fill { background: color-mix(in srgb, var(--k-text) 32%, var(--k-paper)); }
.fsk-prog .fsk-prog-key { display: flex; flex-wrap: wrap; gap: 2px 12px; margin-top: 6px; font-size: .79em; color: var(--k-text-2); }
.fsk-prog .fsk-prog-key span { display: inline-flex; align-items: center; gap: 5px; }
.fsk-prog .fsk-prog-key i { width: 10px; height: 6px; border-radius: calc(var(--k-r) * 100); background: var(--k-success); }
.fsk-prog .fsk-prog-key i.is-fail { background: repeating-linear-gradient(-45deg, var(--k-error) 0 2px, color-mix(in srgb, var(--k-error) 55%, var(--k-paper)) 2px 4px); }

.fsk-prog .fsk-prog-notice {
  display: flex; gap: 8px; align-items: flex-start; margin: 12px 0 0; padding: 8px 10px; font-size: .86em;
  border-radius: var(--k-r-md); color: var(--k-text);
  background: color-mix(in srgb, var(--k-warning) 10%, var(--k-paper)); border: 1px solid color-mix(in srgb, var(--k-warning) 30%, var(--k-paper));
}
.fsk-prog .fsk-prog-notice .fsk-icon { color: var(--k-warning); margin-top: 2px; }

/* Steps: a timeline. Each status has its own mark shape and a word, never colour alone */
.fsk-prog .fsk-prog-steps { list-style: none; margin: 16px 0 0; padding: 0; }
.fsk-prog .fsk-prog-step { position: relative; display: grid; grid-template-columns: 20px minmax(0, 1fr) auto; column-gap: 10px; padding: 0 0 12px; }
.fsk-prog .fsk-prog-step:last-child { padding-bottom: 0; }
.fsk-prog .fsk-prog-step::before { content: ""; position: absolute; left: 9.25px; top: 23px; bottom: 3px; width: 1.5px; border-radius: 1px; background: var(--k-divider); }
.fsk-prog .fsk-prog-step:last-child::before { display: none; }
.fsk-prog .fsk-prog-step.is-done::before, .fsk-prog .fsk-prog-step.is-warn::before { background: color-mix(in srgb, var(--k-success) 50%, var(--k-paper)); }
.fsk-prog .fsk-prog-mark {
  position: relative; display: grid; place-items: center; width: 20px; height: 20px; border-radius: 50%;
  color: var(--k-paper); font-size: 12px; font-weight: 800; line-height: 1;
}
.fsk-prog .is-pending .fsk-prog-mark { border: 1.5px solid color-mix(in srgb, var(--k-text) 24%, var(--k-paper)); background: var(--k-paper); }
.fsk-prog .is-running .fsk-prog-mark { border: 2px solid color-mix(in srgb, var(--k-primary) 22%, var(--k-paper)); border-top-color: var(--k-primary); animation: fsk-spin .9s linear infinite; }
.fsk-prog .is-running .fsk-prog-mark::after { content: ""; width: 6px; height: 6px; border-radius: 50%; background: var(--k-primary); }
.fsk-prog .is-done .fsk-prog-mark { background: var(--k-success); }
.fsk-prog .is-warn .fsk-prog-mark { background: var(--k-warning); }
.fsk-prog .is-failed .fsk-prog-mark { background: var(--k-error); }
.fsk-prog .is-skipped .fsk-prog-mark { border: 1.5px dashed color-mix(in srgb, var(--k-text) 30%, var(--k-paper)); color: var(--k-text-2); }
.fsk-prog .fsk-prog-mark .fsk-icon { stroke-width: 3; }
.fsk-prog .fsk-prog-stext { min-width: 0; }
.fsk-prog .fsk-prog-slabel { display: block; font-weight: 500; line-height: 20px; overflow-wrap: anywhere; }
.fsk-prog .is-pending .fsk-prog-slabel, .fsk-prog .is-skipped .fsk-prog-slabel { color: var(--k-text-2); }
.fsk-prog .is-running .fsk-prog-slabel { font-weight: 600; }
.fsk-prog .fsk-prog-sdetail { display: block; margin-top: 1px; font-size: .82em; color: var(--k-text-2); overflow-wrap: anywhere; }
.fsk-prog .fsk-prog-stag {
  align-self: start; margin-top: 1px; padding: 0 7px; border-radius: var(--k-r); white-space: nowrap;
  font-size: .75em; font-weight: 600; line-height: 18px; color: var(--k-text-2); background: var(--k-hover);
}
.fsk-prog .is-running .fsk-prog-stag { color: var(--k-primary); background: var(--k-tint); }
.fsk-prog .is-warn .fsk-prog-stag { color: color-mix(in srgb, var(--k-warning) 70%, var(--k-text)); background: color-mix(in srgb, var(--k-warning) 13%, var(--k-paper)); }
.fsk-prog .is-failed .fsk-prog-stag { color: var(--k-error); background: color-mix(in srgb, var(--k-error) 11%, var(--k-paper)); }
.fsk-prog .fsk-prog-fold { margin-top: 14px; }
.fsk-prog .fsk-prog-fold > summary {
  display: inline-flex; align-items: center; gap: 4px; min-height: 28px; cursor: pointer; list-style: none;
  font-size: .86em; font-weight: 500; color: var(--k-text-2); border-radius: var(--k-r);
}
.fsk-prog .fsk-prog-fold > summary::-webkit-details-marker { display: none; }
.fsk-prog .fsk-prog-fold > summary:focus-visible { outline: 2px solid var(--k-primary); outline-offset: 2px; }
.fsk-prog .fsk-prog-fold[open] > summary .fsk-icon { transform: rotate(90deg); }
.fsk-prog .fsk-prog-fold .fsk-prog-steps { margin-top: 10px; }

/* The outcome */
.fsk-prog .fsk-prog-result {
  display: flex; gap: 10px; align-items: flex-start; margin-top: 16px; padding: 12px;
  border-radius: var(--k-r-md); --tone: var(--k-success);
  background: color-mix(in srgb, var(--tone) 8%, var(--k-paper)); border: 1px solid color-mix(in srgb, var(--tone) 28%, var(--k-paper));
  animation: fsk-in .32s var(--k-ease) both;
}
.fsk-prog .fsk-prog-result--warning { --tone: var(--k-warning); }
.fsk-prog .fsk-prog-result--error { --tone: var(--k-error); }
.fsk-prog .fsk-prog-result--neutral { --tone: var(--k-text-2); }
.fsk-prog .fsk-prog-rchip {
  flex: none; display: grid; place-items: center; width: 28px; height: 28px; border-radius: var(--k-r-md);
  color: var(--tone); background: color-mix(in srgb, var(--tone) 15%, var(--k-paper));
}
.fsk-prog .fsk-prog-rtext { flex: 1; min-width: 0; }
.fsk-prog .fsk-prog-rtitle { margin: 0; font-weight: 600; line-height: 1.35; }
.fsk-prog .fsk-prog-rbody { margin: 2px 0 0; font-size: .9em; color: var(--k-text-2); }
.fsk-prog .fsk-prog-err { margin: 10px 0 0; font-size: .86em; color: var(--k-error); }

/* Footer: cancel while running (confirmed in place), the outcome's actions after */
.fsk-prog .fsk-prog-actions {
  display: flex; align-items: center; flex-wrap: wrap; gap: 8px; margin: 16px -16px -16px; padding: 12px 16px;
  border-top: 1px solid var(--k-divider); background: var(--k-sunken); border-radius: 0 0 var(--k-r-lg) var(--k-r-lg);
}
.fsk-prog .fsk-prog-hintline { flex: 1; min-width: 0; display: flex; align-items: center; gap: 6px; font-size: .82em; color: var(--k-text-2); }
.fsk-prog .fsk-prog-actions--confirm { background: color-mix(in srgb, var(--k-error) 6%, var(--k-paper)); border-top-color: color-mix(in srgb, var(--k-error) 25%, var(--k-paper)); }
.fsk-prog .fsk-prog-ask { flex: 1 1 100%; min-width: 0; margin: 0 0 2px; font-size: .9em; }
.fsk-prog .fsk-prog-actions--confirm .fsk-btn--ghost { margin-left: auto; }
.fsk-prog .fsk-prog-ask b { display: block; font-weight: 600; }
.fsk-prog .fsk-prog-ask span { color: var(--k-text-2); font-size: .93em; }
.fsk-prog .fsk-prog-stop { background: var(--k-error); color: var(--k-on-error); }
.fsk-prog .fsk-prog-stop:hover { background: color-mix(in srgb, var(--k-error) 86%, var(--k-text)); }
.fsk-prog .fsk-prog-stop:focus-visible { outline-color: var(--k-error); }
.fsk-prog .fsk-prog-quiet { color: var(--k-text-2); }
.fsk-prog .fsk-prog-quiet:hover { color: var(--k-error); border-color: color-mix(in srgb, var(--k-error) 40%, var(--k-border)); }
.fsk-prog .fsk-prog-grow { flex: 1; }
.fsk-prog a.fsk-btn { text-decoration: none; }
.fsk-prog .fsk-prog-rlink { display: inline-flex; align-items: center; gap: 4px; margin-top: 6px; font-size: .9em; font-weight: 500; color: var(--k-primary); text-decoration: none; }
.fsk-prog .fsk-prog-rlink:hover { text-decoration: underline; text-underline-offset: 3px; }
.fsk-prog .fsk-prog-rlink:focus-visible { outline: 2px solid var(--k-primary); outline-offset: 2px; border-radius: var(--k-r); }

@container (max-width: 300px) {
  .fsk-prog .fsk-prog-hintline { display: none; }
}
/* Two outcome buttons don't fit side by side in a chat-width card: stack them, the main one first */
@container (max-width: 440px) {
  .fsk-prog .fsk-prog-actions--final.is-pair { flex-direction: column; align-items: stretch; }
  .fsk-prog .fsk-prog-actions--final.is-pair .fsk-btn { width: 100%; }
  .fsk-prog .fsk-prog-actions--final.is-pair .fsk-prog-main-btn { order: -1; }
  .fsk-prog .fsk-prog-actions--final.is-pair .fsk-prog-grow { display: none; }
}
/* Mobile variant: 44px targets, stacked full-width buttons, the main one first */
.fsk-prog[data-surface="mobile"] .fsk-btn, .fsk-prog[data-surface="mobile"] .fsk-prog-fold > summary { min-height: 44px; }
.fsk-prog[data-surface="mobile"] .fsk-prog-actions { flex-direction: column; align-items: stretch; }
.fsk-prog[data-surface="mobile"] .fsk-prog-actions .fsk-btn { width: 100%; }
.fsk-prog[data-surface="mobile"] .fsk-prog-actions .fsk-prog-main-btn { order: -1; }
.fsk-prog[data-surface="mobile"] .fsk-prog-hintline { justify-content: center; order: 2; }
.fsk-prog[data-surface="mobile"] .fsk-prog-grow { display: none; }
@keyframes fsk-prog-pulse { 50% { opacity: .35; } }
`;

let seq = 0;

/** pending: not started. running: now. done: finished. failed: stopped the job. skipped: not needed this time. */
export type StepStatus = "pending" | "running" | "done" | "failed" | "skipped";
/** partial: finished, some items failed. cancelled: the user stopped it. */
export type JobStatus = "running" | "done" | "partial" | "failed" | "cancelled";

export interface ProgressStep {
  id: string;
  label: string;
  status: StepStatus;
  /** One short line under the label: "214 merged", or why it failed or was skipped. */
  detail?: string;
  /** Items this step couldn't handle. A done step with failures shows a warning mark and "12 failed". */
  failed?: number;
}

export interface ProgressData {
  /** Name the job as it runs, "Importing contacts"; send a new title when it ends, "Contacts imported". */
  title: string;
  subtitle?: string;
  icon?: IconName;
  status: JobStatus;
  /** Items handled so far. */
  done: number;
  total: number;
  /** What's counted, plural: "rows", "files". Default "items". */
  unit?: string;
  /** Items that failed. With status "partial" they're what Retry sends again. */
  failed?: number;
  steps: ProgressStep[];
  /** When the job started (ISO string or ms). Default: when the card mounted. Elapsed time counts from it. */
  startedAt?: string | number;
  /** When it ended. Default: when the card saw it end. Freezes elapsed time. */
  finishedAt?: string | number;
  /** Seconds left, when your job knows. Otherwise the card estimates it from the rate so far. */
  etaSeconds?: number;
  /** The outcome in a sentence, under the result title: what happened, what failed and why. */
  summary?: string;
  /** Where the result lives, e.g. "Open contacts". Shown when the job is done or partly done. */
  link?: { label: string; href: string };
  /** A file of the failed items and why (CSV). Shows "Download error report". */
  reportHref?: string;
  /** status "failed": what went wrong, in the user's words, and whether anything changed. */
  error?: string;
  /** A passing problem while it runs, e.g. "Can't reach the import service. Retrying…". An empty string clears it. */
  notice?: string;
  /** Show Cancel while running. Default: when actions.cancel is set. */
  cancelable?: boolean;
  /** The noun in buttons and the stop question, e.g. "import". Default "job". */
  jobNoun?: string;
}

/** A change to the job. Top-level fields replace; steps merge by id, and an unknown id is added at the end. */
export type ProgressPatch = Partial<Omit<ProgressData, "steps">> & { steps?: (Partial<ProgressStep> & { id: string })[] };

export interface ProgressActions {
  /** Your job's updates (app events, polling). Call onChange with each change; the card redraws and announces step changes. Return the unsubscribe. */
  subscribe?(onChange: (patch: ProgressPatch) => void): () => void;
  /** Stops the job. Throw to keep it running and show why. Without it, there's no Cancel. */
  cancel?(): Promise<unknown>;
  /** Runs again what failed: the failed items for "partial", the job for "failed". New progress arrives through subscribe. */
  retry?(): Promise<unknown>;
  /** Downloads the error report. Hosted actions pass ctx.ui.download (the sandbox blocks native downloads). Without it, a download link. */
  download?(href: string): void;
}

export interface ProgressProps {
  root: HTMLElement;
  head: StyleHost;
  data: ProgressData;
  api?: CardApi;
  actions?: ProgressActions;
  /** "mobile": 44px targets, stacked full-width buttons. */
  surface?: "desktop" | "mobile";
}

const FINAL: JobStatus[] = ["done", "partial", "failed", "cancelled"];
const STATUS_PILL: Record<JobStatus, [string, Tone]> = {
  running: ["Running", "primary"], done: ["Done", "success"], partial: ["Done with errors", "warning"], failed: ["Failed", "error"], cancelled: ["Stopped", "neutral"],
};
const num = (n: number): string => formatValue(n);
const time = (v: string | number | undefined, fallback: number): number => {
  const t = v === undefined ? NaN : typeof v === "number" ? v : Date.parse(v);
  return Number.isFinite(t) ? t : fallback;
};

/** "42 s", "1 min 12 s", "1 h 4 min". */
export function formatDuration(sec: number): string {
  const s = Math.max(0, Math.round(sec));
  if (s < 60) return `${s} s`;
  const m = Math.floor(s / 60);
  if (m < 60) return s % 60 ? `${m} min ${s % 60} s` : `${m} min`;
  return m % 60 ? `${Math.floor(m / 60)} h ${m % 60} min` : `${Math.floor(m / 60)} h`;
}
function timeLeft(sec: number): string {
  if (sec < 45) return "Under a minute left";
  const m = Math.round(sec / 60);
  return m < 90 ? `About ${m} min left` : `About ${Math.round(m / 6) / 10} h left`;
}

/** Interactive, and the agent doesn't wait: reports displayed() at once. Updates arrive through actions.subscribe. */
export function mount({ root, head, data, api, actions, surface = "desktop" }: ProgressProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-prog", CSS);
  const uid = `fsk-prog${++seq}`;
  const win = root.ownerDocument.defaultView ?? window;
  let state: ProgressData = { ...data, steps: data.steps.map((s) => ({ ...s })) };
  let start = time(state.startedAt, Date.now());
  let end: number | null = FINAL.includes(state.status) ? time(state.finishedAt, Date.now()) : null;
  let confirming = false;
  let busy: "cancel" | "retry" | null = null;
  let actionError = "";
  let ticker = 0;
  let alive = true;
  const noun = () => state.jobNoun ?? "job";
  const unit = () => state.unit ?? "items";

  const chip = h("span", { class: "fsk-chip" }, icon(state.icon ?? "refresh", 18));
  const titleEl = h("h3", { class: "fsk-title", id: `${uid}-title` });
  const subEl = h("p", { class: "fsk-sub" });
  const pillSlot = h("span", {});
  const pct = h("span", { class: "fsk-prog-pct fsk-num" });
  const count = h("span", { class: "fsk-prog-count fsk-num", id: `${uid}-count` });
  const timeEl = h("div", { class: "fsk-prog-time fsk-num" });
  const fill = h("span", { class: "fsk-prog-fill" });
  const fail = h("span", { class: "fsk-prog-fail" });
  const bar = h("div", { class: "fsk-prog-bar", role: "progressbar", "aria-labelledby": `${uid}-title`, "aria-valuemin": 0 }, fill, fail);
  const key = h("div", { class: "fsk-prog-key", hidden: true });
  const notice = h("p", { class: "fsk-prog-notice", role: "status", hidden: true });
  const stepsSlot = h("div", {});
  const resultSlot = h("div", {});
  const footer = h("div", { class: "fsk-prog-actions" });
  // Escape backs out of the stop question.
  footer.addEventListener("keydown", (e) => { if (e.key === "Escape" && confirming && !busy) { e.stopPropagation(); confirming = false; paintFooter(true); } });
  // One polite live region for step changes and the outcome. Ticks of the count are never announced.
  const live = h("span", { class: "fsk-sr", role: "status", "aria-live": "polite" });

  const card = h("section", { class: "fsk fsk-card fsk-prog", "data-surface": surface, "aria-labelledby": `${uid}-title` },
    h("header", { class: "fsk-head" }, chip, h("div", {}, titleEl, subEl), pillSlot),
    h("div", { class: "fsk-prog-figs" }, h("div", { class: "fsk-prog-main" }, pct, count), timeEl),
    bar, key, notice, stepsSlot, resultSlot, footer, live);
  root.replaceChildren(card);

  render(true);
  // A chat card gets no unmount call (renderComponent's return is ignored): stop once the card leaves the page.
  const gone = (): boolean => { if (alive && !root.isConnected) stop(); return !alive; };
  let off: (() => void) | undefined;
  off = actions?.subscribe?.((patch) => { if (!gone()) apply(patch); });
  api?.displayed?.(); // the agent doesn't wait; the outcome reaches it through the next turn or your app

  function apply(patch: ProgressPatch, local = false): void {
    const prev = state;
    const steps = prev.steps.map((s) => ({ ...s }));
    for (const p of patch.steps ?? []) {
      const at = steps.findIndex((s) => s.id === p.id);
      if (at >= 0) steps[at] = { ...steps[at], ...p };
      else steps.push({ label: p.id, status: "pending", ...p });
    }
    state = { ...prev, ...patch, steps };
    if (patch.startedAt !== undefined) start = time(patch.startedAt, start);
    const wasFinal = FINAL.includes(prev.status), isFinal = FINAL.includes(state.status);
    if (isFinal && (!wasFinal || patch.finishedAt !== undefined)) end = time(state.finishedAt, Date.now());
    if (!isFinal) end = null;
    if (prev.status !== state.status) { confirming = false; if (!local) busy = null; actionError = ""; }
    announce(prev);
    render(prev.status !== state.status || JSON.stringify(prev.steps) !== JSON.stringify(steps));
  }

  function announce(prev: ProgressData): void {
    const said: string[] = [];
    const total = state.steps.length;
    state.steps.forEach((s, i) => {
      const was = prev.steps.find((p) => p.id === s.id);
      if (was?.status === s.status) return;
      if (s.status === "running") said.push(`Step ${i + 1} of ${total}: ${s.label}.`);
      else if (s.status === "failed") said.push(`${s.label} failed.${s.detail ? ` ${s.detail}` : ""}`);
      else if (s.status === "skipped") said.push(`${s.label} skipped.`);
      else if (s.status === "done" && s.failed) said.push(`${s.label} done, ${num(s.failed)} failed.`);
    });
    if (prev.status !== state.status && FINAL.includes(state.status)) said.push(`${state.title}. ${outcomeTitle()}.${state.summary ? ` ${state.summary}` : ""}`);
    if (state.notice && state.notice !== prev.notice) said.push(state.notice);
    if (said.length) live.textContent = said.join(" ");
  }

  function outcomeTitle(): string {
    const failed = state.failed ?? 0;
    if (state.status === "done") return `${num(state.done)} ${unit()} done`;
    if (state.status === "partial") return `${num(Math.max(0, state.done - failed))} done, ${num(failed)} failed`;
    if (state.status === "cancelled") return `Stopped at ${num(state.done)} of ${num(state.total)} ${unit()}`;
    if (state.status === "failed") return `The ${noun()} failed`;
    return "";
  }

  function render(structure: boolean): void {
    const s = state;
    const final = FINAL.includes(s.status);
    card.dataset.status = s.status;
    titleEl.textContent = s.title;
    subEl.textContent = s.subtitle ?? "";
    subEl.hidden = !s.subtitle;
    const [label, tone] = STATUS_PILL[s.status];
    const p = pill(label, tone);
    if (s.status === "running") p.classList.add("fsk-prog-live");
    pillSlot.replaceChildren(p);

    const total = Math.max(0, s.total);
    const failed = Math.min(s.failed ?? 0, s.done);
    const ratio = total ? Math.min(1, s.done / total) : 0;
    const okRatio = total ? Math.min(1, (s.done - (s.status === "partial" ? failed : 0)) / total) : 0;
    const percent = Math.floor(ratio * 100);
    pct.replaceChildren(String(s.status === "done" ? 100 : percent), h("small", {}, "%"));
    count.replaceChildren(h("b", {}, num(s.done)), ` of ${num(total)} ${unit()}`);
    fill.style.width = `${(s.status === "partial" ? okRatio : s.status === "done" ? 1 : ratio) * 100}%`;
    fail.style.width = s.status === "partial" && total ? `${(failed / total) * 100}%` : "0";
    bar.setAttribute("aria-valuemax", String(total));
    bar.setAttribute("aria-valuenow", String(Math.min(s.done, total)));
    bar.setAttribute("aria-valuetext", `${num(s.done)} of ${num(total)} ${unit()}${failed && s.status === "partial" ? `, ${num(failed)} failed` : ""}`);
    key.hidden = s.status !== "partial" || !failed;
    if (!key.hidden) key.replaceChildren(h("span", {}, h("i", {}), `${num(s.done - failed)} done`), h("span", {}, h("i", { class: "is-fail" }), `${num(failed)} failed`));
    notice.hidden = !s.notice || final;
    notice.replaceChildren(icon("alert", 14), h("span", {}, s.notice ?? ""));
    paintTime();

    if (!final && !ticker) ticker = win.setInterval(() => { if (!gone()) paintTime(); }, 1000);
    if (final && ticker) { win.clearInterval(ticker); ticker = 0; }
    if (!structure) return;
    const list = h("ol", { class: "fsk-prog-steps", "aria-label": "Steps" }, s.steps.map(step));
    // A clean finish folds the steps away; anything that went wrong keeps them open.
    stepsSlot.replaceChildren(s.status === "done"
      ? h("details", { class: "fsk-prog-fold" }, h("summary", {}, icon("chevron", 12), `Show the ${s.steps.length} steps`), list)
      : list);
    resultSlot.replaceChildren(result() ?? "");
    paintFooter();
  }

  function paintTime(): void {
    const s = state;
    const now = end ?? Date.now();
    const elapsed = (now - start) / 1000;
    const final = FINAL.includes(s.status);
    const parts: Node[] = [h("span", {}, icon("clock", 12), final ? "Took " : "", h("b", {}, formatDuration(elapsed)), final ? "" : " elapsed")];
    if (s.status === "running") {
      const rate = elapsed > 3 && s.done > 0 ? s.done / elapsed : 0;
      const eta = s.etaSeconds ?? (rate ? (s.total - s.done) / rate : null);
      if (eta != null && s.done < s.total) parts.push(h("span", {}, timeLeft(eta)));
    }
    timeEl.replaceChildren(...parts);
  }

  function step(st: ProgressStep, i: number): HTMLElement {
    const warn = st.status === "done" && (st.failed ?? 0) > 0;
    const cls = warn ? "warn" : st.status;
    const mark = st.status === "done" && !warn ? icon("check", 12)
      : warn ? "!"
      : st.status === "failed" ? icon("x", 12)
      : st.status === "skipped" ? icon("minus", 12)
      : null;
    const word = warn ? `Done, ${num(st.failed ?? 0)} failed` : { pending: "Not started", running: "Running", done: "Done", failed: "Failed", skipped: "Skipped" }[st.status];
    const tag = warn ? `${num(st.failed ?? 0)} failed` : st.status === "running" ? "Running" : st.status === "failed" ? "Failed" : st.status === "skipped" ? "Skipped" : null;
    return h("li", { class: `fsk-prog-step is-${cls}`, "aria-current": st.status === "running" ? "step" : null },
      h("span", { class: "fsk-prog-mark", "aria-hidden": "true" }, mark),
      h("span", { class: "fsk-prog-stext" },
        h("span", { class: "fsk-prog-slabel" }, h("span", { class: "fsk-sr" }, `Step ${i + 1}, ${word}: `), st.label),
        st.detail && h("span", { class: "fsk-prog-sdetail" }, st.detail)),
      tag ? h("span", { class: "fsk-prog-stag", "aria-hidden": "true" }, tag) : h("span", {}));
  }

  function result(): HTMLElement | null {
    const s = state;
    if (!FINAL.includes(s.status)) return null;
    const look: Record<string, [string, IconName]> = { done: ["success", "check"], partial: ["warning", "alert"], failed: ["error", "x"], cancelled: ["neutral", "minus"] };
    const [tone, ic] = look[s.status];
    const body = s.status === "failed" ? s.error ?? s.summary : s.summary;
    return h<HTMLElement>("div", { class: `fsk-prog-result fsk-prog-result--${tone}`, role: s.status === "failed" ? "alert" : null },
      h("span", { class: "fsk-prog-rchip", "aria-hidden": "true" }, icon(ic, 16)),
      h("div", { class: "fsk-prog-rtext" },
        h("p", { class: "fsk-prog-rtitle" }, outcomeTitle()),
        body && h("p", { class: "fsk-prog-rbody" }, body),
        // Partly done: the result link sits here, so the footer keeps to what to do about the failures.
        s.status === "partial" && s.link && h("a", { class: "fsk-prog-rlink", href: s.link.href, target: "_top" }, s.link.label, icon("arrowRight", 14)),
        actionError && h("p", { class: "fsk-prog-err", role: "alert" }, actionError)));
  }

  function paintFooter(focusIt = false): void {
    const s = state;
    const hadFocus = footer.contains(root.ownerDocument.activeElement);
    let focus: HTMLElement | null = null;
    const parts: (Node | null)[] = [];
    footer.classList.toggle("fsk-prog-actions--confirm", confirming);
    if (s.status === "running") {
      const canCancel = !!actions?.cancel && (s.cancelable ?? true);
      if (confirming) {
        const keep = h<HTMLButtonElement>("button", { class: "fsk-btn fsk-btn--ghost", type: "button", disabled: busy === "cancel", onclick: () => { confirming = false; paintFooter(true); } }, "Keep going");
        const stop = h<HTMLButtonElement>("button", { class: "fsk-btn fsk-prog-stop fsk-prog-main-btn", type: "button", disabled: busy === "cancel", onclick: onStop },
          ...(busy === "cancel" ? [h("span", { class: "fsk-spinner", "aria-hidden": "true" }), "Stopping…"] : [icon("x", 15), `Stop ${noun()}`]));
        parts.push(h("p", { class: "fsk-prog-ask", id: `${uid}-ask` }, h("b", {}, `Stop the ${noun()}?`),
          h("span", {}, `${unit().charAt(0).toUpperCase()}${unit().slice(1)} already done stay. The rest won't run.`)), keep, stop);
        footer.setAttribute("role", "group");
        footer.setAttribute("aria-labelledby", `${uid}-ask`);
        focus = keep;
      } else {
        footer.removeAttribute("role");
        footer.removeAttribute("aria-labelledby");
        parts.push(h("span", { class: "fsk-prog-hintline" }, icon("info", 13), "Runs in the background. Keep chatting."));
        if (canCancel) {
          const cancel = h<HTMLButtonElement>("button", { class: "fsk-btn fsk-btn--ghost fsk-prog-quiet", type: "button", onclick: () => { confirming = true; paintFooter(true); } }, `Cancel ${noun()}`);
          parts.push(cancel);
          focus = cancel;
        }
        if (actionError) parts.unshift(h("p", { class: "fsk-prog-err", role: "alert", style: { flexBasis: "100%", margin: "0" } }, actionError));
      }
    } else {
      footer.removeAttribute("role");
      footer.removeAttribute("aria-labelledby");
      const failedN = s.failed ?? 0;
      const canRetry = !!actions?.retry && (s.status === "failed" || (s.status === "partial" && failedN > 0));
      if (s.reportHref && (s.status === "partial" || s.status === "failed")) {
        const href = s.reportHref;
        parts.push(actions?.download
          ? h("button", { class: "fsk-btn fsk-btn--ghost", type: "button", onclick: () => actions.download?.(href) }, icon("doc", 15), "Download error report")
          : h("a", { class: "fsk-btn fsk-btn--ghost", href, download: "" }, icon("doc", 15), "Download error report"));
      }
      if (s.status === "done" && s.link) {
        parts.push(h("a", { class: "fsk-btn fsk-btn--primary fsk-prog-main-btn", href: s.link.href, target: "_top" }, s.link.label, icon("arrowRight", 15)));
      }
      parts.unshift(h("span", { class: "fsk-prog-grow" }));
      if (canRetry) {
        const label = s.status === "partial" ? `Retry ${num(failedN)} failed ${unit()}` : "Try again";
        const retry = h<HTMLButtonElement>("button", { class: "fsk-btn fsk-btn--primary fsk-prog-main-btn", type: "button", disabled: busy === "retry", onclick: onRetry },
          ...(busy === "retry" ? [h("span", { class: "fsk-spinner", "aria-hidden": "true" }), "Retrying…"] : [icon("refresh", 15), label]));
        parts.push(retry);
        focus = retry;
      }
      if (parts.length === 1) parts.length = 0;
      footer.classList.toggle("is-pair", parts.length > 2);
    }
    footer.classList.toggle("fsk-prog-actions--final", FINAL.includes(s.status));
    footer.hidden = parts.length === 0;
    footer.replaceChildren(...parts.filter((x): x is Node => !!x));
    if ((focusIt || hadFocus) && !footer.hidden) (focus && !focus.hasAttribute("disabled") ? focus : footer.querySelector<HTMLElement>("button:not([disabled]), a"))?.focus();
  }

  async function onStop(): Promise<void> {
    if (busy || !actions?.cancel) return;
    busy = "cancel";
    actionError = "";
    paintFooter();
    try {
      await actions.cancel();
      busy = null;
      if (state.status === "running") apply({ status: "cancelled" }, true);
    } catch (err) {
      busy = null;
      confirming = false;
      actionError = (err instanceof Error && err.message) || `The ${noun()} didn't stop. It's still running.`;
      paintFooter(true);
    }
  }

  async function onRetry(): Promise<void> {
    if (busy || !actions?.retry) return;
    busy = "retry";
    actionError = "";
    paintFooter();
    try {
      await actions.retry();
      busy = null;
      if (FINAL.includes(state.status)) apply({ status: "running" }, true);
    } catch (err) {
      busy = null;
      actionError = (err instanceof Error && err.message) || "That didn't start. Nothing changed. Try again in a minute.";
      render(true);
    }
  }

  function stop(): void {
    alive = false;
    off?.();
    if (ticker) win.clearInterval(ticker);
    ticker = 0;
  }

  return () => {
    stop();
    root.replaceChildren();
  };
}

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

/** Loading (meter and step bones in the card's shape), empty or error, drawn as this card. Report displayed() yourself. */
export function mountState({ root, head, state, title, subtitle, surface = "desktop" }: StateProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-prog", CSS);
  const skeleton = () => h("div", {},
    h("div", { class: "fsk-prog-figs" }, h("div", { class: "fsk-prog-main" }, bone("58px", "26px"), bone("110px", "10px", { i: 1 })), bone("84px", "10px", { i: 2 })),
    h("div", { style: { marginTop: "12px" } }, bone("100%", "8px", { i: 3 })),
    h("div", { class: "fsk-prog-steps" }, Array.from({ length: 4 }, (_, i) =>
      h("div", { class: "fsk-prog-step is-pending", style: { alignItems: "center" } },
        bone("20px", "20px", { cls: "fsk-bone--round", i: i + 4 }), bone(`${[52, 38, 60, 44][i]}%`, "10px", { i: i + 4 }), h("span", {})))));
  const card = stateCard({ state, cls: "fsk-prog", icon: "refresh", title, subtitle, surface, skeleton });
  root.replaceChildren(card.el);
  return () => { card.dispose(); root.replaceChildren(); };
}

const STEPS: ProgressStep[] = [
  { id: "read", label: "Read the file", status: "done", detail: "3,000 rows, 14 columns" },
  { id: "map", label: "Match columns", status: "done", detail: "14 of 14 mapped" },
  { id: "dedupe", label: "Merge duplicates", status: "done", detail: "214 merged into existing contacts" },
  { id: "import", label: "Import contacts", status: "running", detail: "1,240 of 3,000" },
  { id: "list", label: "Add to the Q4 webinar list", status: "pending" },
  { id: "notify", label: "Notify contact owners", status: "pending" },
];

export const fixtures: Record<string, ProgressData> = {
  default: {
    title: "Importing contacts",
    subtitle: "contacts-november.csv · to the Q4 webinar list",
    icon: "users",
    status: "running",
    done: 1240,
    total: 3000,
    unit: "rows",
    jobNoun: "import",
    steps: STEPS,
  },
  done: {
    title: "Contacts imported",
    subtitle: "contacts-november.csv · to the Q4 webinar list",
    icon: "users",
    status: "done",
    done: 3000,
    total: 3000,
    unit: "rows",
    jobNoun: "import",
    summary: "3,000 contacts are in the Q4 webinar list. 214 were merged into contacts you already had.",
    link: { label: "Open contacts", href: "https://app.example.com/contacts?list=q4-webinar" },
    steps: STEPS.map((s): ProgressStep => ({ ...s, status: "done", detail: s.id === "import" ? "3,000 imported" : s.id === "list" ? "3,000 added" : s.id === "notify" ? "6 owners emailed" : s.detail })),
  },
  partial: {
    title: "Contacts imported",
    subtitle: "contacts-november.csv · to the Q4 webinar list",
    icon: "users",
    status: "partial",
    done: 3000,
    total: 3000,
    failed: 12,
    unit: "rows",
    jobNoun: "import",
    summary: "12 rows have a missing or invalid email. Fix them from the error report, or retry them as they are.",
    reportHref: "data:text/csv;charset=utf-8,row%2Cemail%2Cerror%0A118%2C%2Cmissing%20email%0A409%2Cdana%40acme%2Cinvalid%20email%0A",
    link: { label: "Open contacts", href: "https://app.example.com/contacts?list=q4-webinar" },
    steps: [
      ...STEPS.slice(0, 3),
      { id: "import", label: "Import contacts", status: "done", detail: "2,988 imported", failed: 12 },
      { id: "list", label: "Add to the Q4 webinar list", status: "done", detail: "2,988 added" },
      { id: "notify", label: "Notify contact owners", status: "skipped", detail: "The file has no owner column" },
    ],
  },
  failed: {
    title: "Import stopped",
    subtitle: "contacts-november.csv · to the Q4 webinar list",
    icon: "users",
    status: "failed",
    done: 1240,
    total: 3000,
    unit: "rows",
    jobNoun: "import",
    error: "The CRM stopped answering after 1,240 rows. Those rows are in; nothing else changed.",
    steps: [
      ...STEPS.slice(0, 3),
      { id: "import", label: "Import contacts", status: "failed", detail: "CRM timed out at row 1,241" },
      { id: "list", label: "Add to the Q4 webinar list", status: "pending" },
      { id: "notify", label: "Notify contact owners", status: "pending" },
    ],
  },
};
```

```js title="agent/ui/progress.js"
// Template: progress. A long job the agent started (import, export, sync, bulk update), with its steps and live progress.

export const meta = {
  id: "progress",
  title: "Progress",
  surface: "card",
  kind: "interactive",
  mobile: "variant",
  whenToUse: "The agent started a job that takes more than a few seconds and runs on its own: an import, an export, a sync, a bulk update. The user wants to see it move, stop it, and act on what failed.",
  whenNotToUse: "A change that finishes in a second or two (do it, then show the result). A yes or no before the job starts (confirm card first). Setup steps the user does by hand (onboarding guide). A job whose result the agent must read before it answers (wait in execute instead).",
};

const CSS = `
.fsk-prog { container-type: inline-size; }
.fsk-prog:not(.fsk-state) .fsk-head { margin-bottom: 0; }
.fsk-prog .fsk-head > div { flex: 1; min-width: 0; }
.fsk-prog .fsk-head .fsk-pill { align-self: flex-start; margin-top: 2px; }
.fsk-prog .fsk-prog-live i { animation: fsk-prog-pulse 1.4s ease-in-out infinite; }

/* The meter: big percent, count, time, bar */
.fsk-prog .fsk-prog-figs { display: flex; align-items: flex-end; justify-content: space-between; flex-wrap: wrap; gap: 4px 12px; margin-top: 16px; }
.fsk-prog .fsk-prog-main { display: flex; align-items: baseline; flex-wrap: wrap; gap: 2px 8px; min-width: 0; }
.fsk-prog .fsk-prog-pct { font-size: 2em; font-weight: 650; letter-spacing: -0.03em; line-height: 1; }
.fsk-prog .fsk-prog-pct small { font-size: .55em; font-weight: 600; margin-left: 1px; color: var(--k-text-2); }
.fsk-prog .fsk-prog-count { font-size: .86em; color: var(--k-text-2); }
.fsk-prog .fsk-prog-count b { color: var(--k-text); font-weight: 600; }
.fsk-prog .fsk-prog-time { display: flex; align-items: center; flex-wrap: wrap; gap: 2px 10px; font-size: .82em; color: var(--k-text-2); }
.fsk-prog .fsk-prog-time > span { display: inline-flex; align-items: center; gap: 4px; white-space: nowrap; }
.fsk-prog .fsk-prog-time b { font-weight: 600; color: var(--k-text); }
.fsk-prog .fsk-prog-bar {
  position: relative; display: flex; height: 8px; margin-top: 10px; overflow: hidden;
  border-radius: calc(var(--k-r) * 100); background: color-mix(in srgb, var(--k-text) 9%, var(--k-paper));
}
.fsk-prog .fsk-prog-fill { position: relative; flex: none; height: 100%; overflow: hidden; background: var(--k-primary); transition: width .5s var(--k-ease), background .3s; }
.fsk-prog[data-status="running"] .fsk-prog-fill::after {
  content: ""; position: absolute; inset: 0; transform: translateX(-100%);
  background: linear-gradient(90deg, transparent, color-mix(in srgb, var(--k-on-primary) 45%, transparent), transparent);
  animation: fsk-shimmer 1.8s ease-in-out infinite;
}
.fsk-prog .fsk-prog-fail {
  flex: none; height: 100%; transition: width .5s var(--k-ease);
  background: repeating-linear-gradient(-45deg, var(--k-error) 0 3px, color-mix(in srgb, var(--k-error) 55%, var(--k-paper)) 3px 6px);
}
.fsk-prog[data-status="done"] .fsk-prog-fill, .fsk-prog[data-status="partial"] .fsk-prog-fill { background: var(--k-success); }
.fsk-prog[data-status="cancelled"] .fsk-prog-fill, .fsk-prog[data-status="failed"] .fsk-prog-fill { background: color-mix(in srgb, var(--k-text) 32%, var(--k-paper)); }
.fsk-prog .fsk-prog-key { display: flex; flex-wrap: wrap; gap: 2px 12px; margin-top: 6px; font-size: .79em; color: var(--k-text-2); }
.fsk-prog .fsk-prog-key span { display: inline-flex; align-items: center; gap: 5px; }
.fsk-prog .fsk-prog-key i { width: 10px; height: 6px; border-radius: calc(var(--k-r) * 100); background: var(--k-success); }
.fsk-prog .fsk-prog-key i.is-fail { background: repeating-linear-gradient(-45deg, var(--k-error) 0 2px, color-mix(in srgb, var(--k-error) 55%, var(--k-paper)) 2px 4px); }

.fsk-prog .fsk-prog-notice {
  display: flex; gap: 8px; align-items: flex-start; margin: 12px 0 0; padding: 8px 10px; font-size: .86em;
  border-radius: var(--k-r-md); color: var(--k-text);
  background: color-mix(in srgb, var(--k-warning) 10%, var(--k-paper)); border: 1px solid color-mix(in srgb, var(--k-warning) 30%, var(--k-paper));
}
.fsk-prog .fsk-prog-notice .fsk-icon { color: var(--k-warning); margin-top: 2px; }

/* Steps: a timeline. Each status has its own mark shape and a word, never colour alone */
.fsk-prog .fsk-prog-steps { list-style: none; margin: 16px 0 0; padding: 0; }
.fsk-prog .fsk-prog-step { position: relative; display: grid; grid-template-columns: 20px minmax(0, 1fr) auto; column-gap: 10px; padding: 0 0 12px; }
.fsk-prog .fsk-prog-step:last-child { padding-bottom: 0; }
.fsk-prog .fsk-prog-step::before { content: ""; position: absolute; left: 9.25px; top: 23px; bottom: 3px; width: 1.5px; border-radius: 1px; background: var(--k-divider); }
.fsk-prog .fsk-prog-step:last-child::before { display: none; }
.fsk-prog .fsk-prog-step.is-done::before, .fsk-prog .fsk-prog-step.is-warn::before { background: color-mix(in srgb, var(--k-success) 50%, var(--k-paper)); }
.fsk-prog .fsk-prog-mark {
  position: relative; display: grid; place-items: center; width: 20px; height: 20px; border-radius: 50%;
  color: var(--k-paper); font-size: 12px; font-weight: 800; line-height: 1;
}
.fsk-prog .is-pending .fsk-prog-mark { border: 1.5px solid color-mix(in srgb, var(--k-text) 24%, var(--k-paper)); background: var(--k-paper); }
.fsk-prog .is-running .fsk-prog-mark { border: 2px solid color-mix(in srgb, var(--k-primary) 22%, var(--k-paper)); border-top-color: var(--k-primary); animation: fsk-spin .9s linear infinite; }
.fsk-prog .is-running .fsk-prog-mark::after { content: ""; width: 6px; height: 6px; border-radius: 50%; background: var(--k-primary); }
.fsk-prog .is-done .fsk-prog-mark { background: var(--k-success); }
.fsk-prog .is-warn .fsk-prog-mark { background: var(--k-warning); }
.fsk-prog .is-failed .fsk-prog-mark { background: var(--k-error); }
.fsk-prog .is-skipped .fsk-prog-mark { border: 1.5px dashed color-mix(in srgb, var(--k-text) 30%, var(--k-paper)); color: var(--k-text-2); }
.fsk-prog .fsk-prog-mark .fsk-icon { stroke-width: 3; }
.fsk-prog .fsk-prog-stext { min-width: 0; }
.fsk-prog .fsk-prog-slabel { display: block; font-weight: 500; line-height: 20px; overflow-wrap: anywhere; }
.fsk-prog .is-pending .fsk-prog-slabel, .fsk-prog .is-skipped .fsk-prog-slabel { color: var(--k-text-2); }
.fsk-prog .is-running .fsk-prog-slabel { font-weight: 600; }
.fsk-prog .fsk-prog-sdetail { display: block; margin-top: 1px; font-size: .82em; color: var(--k-text-2); overflow-wrap: anywhere; }
.fsk-prog .fsk-prog-stag {
  align-self: start; margin-top: 1px; padding: 0 7px; border-radius: var(--k-r); white-space: nowrap;
  font-size: .75em; font-weight: 600; line-height: 18px; color: var(--k-text-2); background: var(--k-hover);
}
.fsk-prog .is-running .fsk-prog-stag { color: var(--k-primary); background: var(--k-tint); }
.fsk-prog .is-warn .fsk-prog-stag { color: color-mix(in srgb, var(--k-warning) 70%, var(--k-text)); background: color-mix(in srgb, var(--k-warning) 13%, var(--k-paper)); }
.fsk-prog .is-failed .fsk-prog-stag { color: var(--k-error); background: color-mix(in srgb, var(--k-error) 11%, var(--k-paper)); }
.fsk-prog .fsk-prog-fold { margin-top: 14px; }
.fsk-prog .fsk-prog-fold > summary {
  display: inline-flex; align-items: center; gap: 4px; min-height: 28px; cursor: pointer; list-style: none;
  font-size: .86em; font-weight: 500; color: var(--k-text-2); border-radius: var(--k-r);
}
.fsk-prog .fsk-prog-fold > summary::-webkit-details-marker { display: none; }
.fsk-prog .fsk-prog-fold > summary:focus-visible { outline: 2px solid var(--k-primary); outline-offset: 2px; }
.fsk-prog .fsk-prog-fold[open] > summary .fsk-icon { transform: rotate(90deg); }
.fsk-prog .fsk-prog-fold .fsk-prog-steps { margin-top: 10px; }

/* The outcome */
.fsk-prog .fsk-prog-result {
  display: flex; gap: 10px; align-items: flex-start; margin-top: 16px; padding: 12px;
  border-radius: var(--k-r-md); --tone: var(--k-success);
  background: color-mix(in srgb, var(--tone) 8%, var(--k-paper)); border: 1px solid color-mix(in srgb, var(--tone) 28%, var(--k-paper));
  animation: fsk-in .32s var(--k-ease) both;
}
.fsk-prog .fsk-prog-result--warning { --tone: var(--k-warning); }
.fsk-prog .fsk-prog-result--error { --tone: var(--k-error); }
.fsk-prog .fsk-prog-result--neutral { --tone: var(--k-text-2); }
.fsk-prog .fsk-prog-rchip {
  flex: none; display: grid; place-items: center; width: 28px; height: 28px; border-radius: var(--k-r-md);
  color: var(--tone); background: color-mix(in srgb, var(--tone) 15%, var(--k-paper));
}
.fsk-prog .fsk-prog-rtext { flex: 1; min-width: 0; }
.fsk-prog .fsk-prog-rtitle { margin: 0; font-weight: 600; line-height: 1.35; }
.fsk-prog .fsk-prog-rbody { margin: 2px 0 0; font-size: .9em; color: var(--k-text-2); }
.fsk-prog .fsk-prog-err { margin: 10px 0 0; font-size: .86em; color: var(--k-error); }

/* Footer: cancel while running (confirmed in place), the outcome's actions after */
.fsk-prog .fsk-prog-actions {
  display: flex; align-items: center; flex-wrap: wrap; gap: 8px; margin: 16px -16px -16px; padding: 12px 16px;
  border-top: 1px solid var(--k-divider); background: var(--k-sunken); border-radius: 0 0 var(--k-r-lg) var(--k-r-lg);
}
.fsk-prog .fsk-prog-hintline { flex: 1; min-width: 0; display: flex; align-items: center; gap: 6px; font-size: .82em; color: var(--k-text-2); }
.fsk-prog .fsk-prog-actions--confirm { background: color-mix(in srgb, var(--k-error) 6%, var(--k-paper)); border-top-color: color-mix(in srgb, var(--k-error) 25%, var(--k-paper)); }
.fsk-prog .fsk-prog-ask { flex: 1 1 100%; min-width: 0; margin: 0 0 2px; font-size: .9em; }
.fsk-prog .fsk-prog-actions--confirm .fsk-btn--ghost { margin-left: auto; }
.fsk-prog .fsk-prog-ask b { display: block; font-weight: 600; }
.fsk-prog .fsk-prog-ask span { color: var(--k-text-2); font-size: .93em; }
.fsk-prog .fsk-prog-stop { background: var(--k-error); color: var(--k-on-error); }
.fsk-prog .fsk-prog-stop:hover { background: color-mix(in srgb, var(--k-error) 86%, var(--k-text)); }
.fsk-prog .fsk-prog-stop:focus-visible { outline-color: var(--k-error); }
.fsk-prog .fsk-prog-quiet { color: var(--k-text-2); }
.fsk-prog .fsk-prog-quiet:hover { color: var(--k-error); border-color: color-mix(in srgb, var(--k-error) 40%, var(--k-border)); }
.fsk-prog .fsk-prog-grow { flex: 1; }
.fsk-prog a.fsk-btn { text-decoration: none; }
.fsk-prog .fsk-prog-rlink { display: inline-flex; align-items: center; gap: 4px; margin-top: 6px; font-size: .9em; font-weight: 500; color: var(--k-primary); text-decoration: none; }
.fsk-prog .fsk-prog-rlink:hover { text-decoration: underline; text-underline-offset: 3px; }
.fsk-prog .fsk-prog-rlink:focus-visible { outline: 2px solid var(--k-primary); outline-offset: 2px; border-radius: var(--k-r); }

@container (max-width: 300px) {
  .fsk-prog .fsk-prog-hintline { display: none; }
}
/* Two outcome buttons don't fit side by side in a chat-width card: stack them, the main one first */
@container (max-width: 440px) {
  .fsk-prog .fsk-prog-actions--final.is-pair { flex-direction: column; align-items: stretch; }
  .fsk-prog .fsk-prog-actions--final.is-pair .fsk-btn { width: 100%; }
  .fsk-prog .fsk-prog-actions--final.is-pair .fsk-prog-main-btn { order: -1; }
  .fsk-prog .fsk-prog-actions--final.is-pair .fsk-prog-grow { display: none; }
}
/* Mobile variant: 44px targets, stacked full-width buttons, the main one first */
.fsk-prog[data-surface="mobile"] .fsk-btn, .fsk-prog[data-surface="mobile"] .fsk-prog-fold > summary { min-height: 44px; }
.fsk-prog[data-surface="mobile"] .fsk-prog-actions { flex-direction: column; align-items: stretch; }
.fsk-prog[data-surface="mobile"] .fsk-prog-actions .fsk-btn { width: 100%; }
.fsk-prog[data-surface="mobile"] .fsk-prog-actions .fsk-prog-main-btn { order: -1; }
.fsk-prog[data-surface="mobile"] .fsk-prog-hintline { justify-content: center; order: 2; }
.fsk-prog[data-surface="mobile"] .fsk-prog-grow { display: none; }
@keyframes fsk-prog-pulse { 50% { opacity: .35; } }
`;

let seq = 0;

const FINAL = ["done", "partial", "failed", "cancelled"];
const STATUS_PILL = {
  running: ["Running", "primary"], done: ["Done", "success"], partial: ["Done with errors", "warning"], failed: ["Failed", "error"], cancelled: ["Stopped", "neutral"],
};
const num = (n) => formatValue(n);
const time = (v, fallback) => {
  const t = v === undefined ? NaN : typeof v === "number" ? v : Date.parse(v);
  return Number.isFinite(t) ? t : fallback;
};

/** "42 s", "1 min 12 s", "1 h 4 min". */
export function formatDuration(sec) {
  const s = Math.max(0, Math.round(sec));
  if (s < 60) return `${s} s`;
  const m = Math.floor(s / 60);
  if (m < 60) return s % 60 ? `${m} min ${s % 60} s` : `${m} min`;
  return m % 60 ? `${Math.floor(m / 60)} h ${m % 60} min` : `${Math.floor(m / 60)} h`;
}
function timeLeft(sec) {
  if (sec < 45) return "Under a minute left";
  const m = Math.round(sec / 60);
  return m < 90 ? `About ${m} min left` : `About ${Math.round(m / 6) / 10} h left`;
}

/** Interactive, and the agent doesn't wait: reports displayed() at once. Updates arrive through actions.subscribe. */
export function mount({ root, head, data, api, actions, surface = "desktop" }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-prog", CSS);
  const uid = `fsk-prog${++seq}`;
  const win = root.ownerDocument.defaultView ?? window;
  let state = { ...data, steps: data.steps.map((s) => ({ ...s })) };
  let start = time(state.startedAt, Date.now());
  let end = FINAL.includes(state.status) ? time(state.finishedAt, Date.now()) : null;
  let confirming = false;
  let busy = null;
  let actionError = "";
  let ticker = 0;
  let alive = true;
  const noun = () => state.jobNoun ?? "job";
  const unit = () => state.unit ?? "items";

  const chip = h("span", { class: "fsk-chip" }, icon(state.icon ?? "refresh", 18));
  const titleEl = h("h3", { class: "fsk-title", id: `${uid}-title` });
  const subEl = h("p", { class: "fsk-sub" });
  const pillSlot = h("span", {});
  const pct = h("span", { class: "fsk-prog-pct fsk-num" });
  const count = h("span", { class: "fsk-prog-count fsk-num", id: `${uid}-count` });
  const timeEl = h("div", { class: "fsk-prog-time fsk-num" });
  const fill = h("span", { class: "fsk-prog-fill" });
  const fail = h("span", { class: "fsk-prog-fail" });
  const bar = h("div", { class: "fsk-prog-bar", role: "progressbar", "aria-labelledby": `${uid}-title`, "aria-valuemin": 0 }, fill, fail);
  const key = h("div", { class: "fsk-prog-key", hidden: true });
  const notice = h("p", { class: "fsk-prog-notice", role: "status", hidden: true });
  const stepsSlot = h("div", {});
  const resultSlot = h("div", {});
  const footer = h("div", { class: "fsk-prog-actions" });
  // Escape backs out of the stop question.
  footer.addEventListener("keydown", (e) => { if (e.key === "Escape" && confirming && !busy) { e.stopPropagation(); confirming = false; paintFooter(true); } });
  // One polite live region for step changes and the outcome. Ticks of the count are never announced.
  const live = h("span", { class: "fsk-sr", role: "status", "aria-live": "polite" });

  const card = h("section", { class: "fsk fsk-card fsk-prog", "data-surface": surface, "aria-labelledby": `${uid}-title` },
    h("header", { class: "fsk-head" }, chip, h("div", {}, titleEl, subEl), pillSlot),
    h("div", { class: "fsk-prog-figs" }, h("div", { class: "fsk-prog-main" }, pct, count), timeEl),
    bar, key, notice, stepsSlot, resultSlot, footer, live);
  root.replaceChildren(card);

  render(true);
  // A chat card gets no unmount call (renderComponent's return is ignored): stop once the card leaves the page.
  const gone = () => { if (alive && !root.isConnected) stop(); return !alive; };
  let off;
  off = actions?.subscribe?.((patch) => { if (!gone()) apply(patch); });
  api?.displayed?.(); // the agent doesn't wait; the outcome reaches it through the next turn or your app

  function apply(patch, local = false) {
    const prev = state;
    const steps = prev.steps.map((s) => ({ ...s }));
    for (const p of patch.steps ?? []) {
      const at = steps.findIndex((s) => s.id === p.id);
      if (at >= 0) steps[at] = { ...steps[at], ...p };
      else steps.push({ label: p.id, status: "pending", ...p });
    }
    state = { ...prev, ...patch, steps };
    if (patch.startedAt !== undefined) start = time(patch.startedAt, start);
    const wasFinal = FINAL.includes(prev.status), isFinal = FINAL.includes(state.status);
    if (isFinal && (!wasFinal || patch.finishedAt !== undefined)) end = time(state.finishedAt, Date.now());
    if (!isFinal) end = null;
    if (prev.status !== state.status) { confirming = false; if (!local) busy = null; actionError = ""; }
    announce(prev);
    render(prev.status !== state.status || JSON.stringify(prev.steps) !== JSON.stringify(steps));
  }

  function announce(prev) {
    const said = [];
    const total = state.steps.length;
    state.steps.forEach((s, i) => {
      const was = prev.steps.find((p) => p.id === s.id);
      if (was?.status === s.status) return;
      if (s.status === "running") said.push(`Step ${i + 1} of ${total}: ${s.label}.`);
      else if (s.status === "failed") said.push(`${s.label} failed.${s.detail ? ` ${s.detail}` : ""}`);
      else if (s.status === "skipped") said.push(`${s.label} skipped.`);
      else if (s.status === "done" && s.failed) said.push(`${s.label} done, ${num(s.failed)} failed.`);
    });
    if (prev.status !== state.status && FINAL.includes(state.status)) said.push(`${state.title}. ${outcomeTitle()}.${state.summary ? ` ${state.summary}` : ""}`);
    if (state.notice && state.notice !== prev.notice) said.push(state.notice);
    if (said.length) live.textContent = said.join(" ");
  }

  function outcomeTitle() {
    const failed = state.failed ?? 0;
    if (state.status === "done") return `${num(state.done)} ${unit()} done`;
    if (state.status === "partial") return `${num(Math.max(0, state.done - failed))} done, ${num(failed)} failed`;
    if (state.status === "cancelled") return `Stopped at ${num(state.done)} of ${num(state.total)} ${unit()}`;
    if (state.status === "failed") return `The ${noun()} failed`;
    return "";
  }

  function render(structure) {
    const s = state;
    const final = FINAL.includes(s.status);
    card.dataset.status = s.status;
    titleEl.textContent = s.title;
    subEl.textContent = s.subtitle ?? "";
    subEl.hidden = !s.subtitle;
    const [label, tone] = STATUS_PILL[s.status];
    const p = pill(label, tone);
    if (s.status === "running") p.classList.add("fsk-prog-live");
    pillSlot.replaceChildren(p);

    const total = Math.max(0, s.total);
    const failed = Math.min(s.failed ?? 0, s.done);
    const ratio = total ? Math.min(1, s.done / total) : 0;
    const okRatio = total ? Math.min(1, (s.done - (s.status === "partial" ? failed : 0)) / total) : 0;
    const percent = Math.floor(ratio * 100);
    pct.replaceChildren(String(s.status === "done" ? 100 : percent), h("small", {}, "%"));
    count.replaceChildren(h("b", {}, num(s.done)), ` of ${num(total)} ${unit()}`);
    fill.style.width = `${(s.status === "partial" ? okRatio : s.status === "done" ? 1 : ratio) * 100}%`;
    fail.style.width = s.status === "partial" && total ? `${(failed / total) * 100}%` : "0";
    bar.setAttribute("aria-valuemax", String(total));
    bar.setAttribute("aria-valuenow", String(Math.min(s.done, total)));
    bar.setAttribute("aria-valuetext", `${num(s.done)} of ${num(total)} ${unit()}${failed && s.status === "partial" ? `, ${num(failed)} failed` : ""}`);
    key.hidden = s.status !== "partial" || !failed;
    if (!key.hidden) key.replaceChildren(h("span", {}, h("i", {}), `${num(s.done - failed)} done`), h("span", {}, h("i", { class: "is-fail" }), `${num(failed)} failed`));
    notice.hidden = !s.notice || final;
    notice.replaceChildren(icon("alert", 14), h("span", {}, s.notice ?? ""));
    paintTime();

    if (!final && !ticker) ticker = win.setInterval(() => { if (!gone()) paintTime(); }, 1000);
    if (final && ticker) { win.clearInterval(ticker); ticker = 0; }
    if (!structure) return;
    const list = h("ol", { class: "fsk-prog-steps", "aria-label": "Steps" }, s.steps.map(step));
    // A clean finish folds the steps away; anything that went wrong keeps them open.
    stepsSlot.replaceChildren(s.status === "done"
      ? h("details", { class: "fsk-prog-fold" }, h("summary", {}, icon("chevron", 12), `Show the ${s.steps.length} steps`), list)
      : list);
    resultSlot.replaceChildren(result() ?? "");
    paintFooter();
  }

  function paintTime() {
    const s = state;
    const now = end ?? Date.now();
    const elapsed = (now - start) / 1000;
    const final = FINAL.includes(s.status);
    const parts = [h("span", {}, icon("clock", 12), final ? "Took " : "", h("b", {}, formatDuration(elapsed)), final ? "" : " elapsed")];
    if (s.status === "running") {
      const rate = elapsed > 3 && s.done > 0 ? s.done / elapsed : 0;
      const eta = s.etaSeconds ?? (rate ? (s.total - s.done) / rate : null);
      if (eta != null && s.done < s.total) parts.push(h("span", {}, timeLeft(eta)));
    }
    timeEl.replaceChildren(...parts);
  }

  function step(st, i) {
    const warn = st.status === "done" && (st.failed ?? 0) > 0;
    const cls = warn ? "warn" : st.status;
    const mark = st.status === "done" && !warn ? icon("check", 12)
      : warn ? "!"
      : st.status === "failed" ? icon("x", 12)
      : st.status === "skipped" ? icon("minus", 12)
      : null;
    const word = warn ? `Done, ${num(st.failed ?? 0)} failed` : { pending: "Not started", running: "Running", done: "Done", failed: "Failed", skipped: "Skipped" }[st.status];
    const tag = warn ? `${num(st.failed ?? 0)} failed` : st.status === "running" ? "Running" : st.status === "failed" ? "Failed" : st.status === "skipped" ? "Skipped" : null;
    return h("li", { class: `fsk-prog-step is-${cls}`, "aria-current": st.status === "running" ? "step" : null },
      h("span", { class: "fsk-prog-mark", "aria-hidden": "true" }, mark),
      h("span", { class: "fsk-prog-stext" },
        h("span", { class: "fsk-prog-slabel" }, h("span", { class: "fsk-sr" }, `Step ${i + 1}, ${word}: `), st.label),
        st.detail && h("span", { class: "fsk-prog-sdetail" }, st.detail)),
      tag ? h("span", { class: "fsk-prog-stag", "aria-hidden": "true" }, tag) : h("span", {}));
  }

  function result() {
    const s = state;
    if (!FINAL.includes(s.status)) return null;
    const look = { done: ["success", "check"], partial: ["warning", "alert"], failed: ["error", "x"], cancelled: ["neutral", "minus"] };
    const [tone, ic] = look[s.status];
    const body = s.status === "failed" ? s.error ?? s.summary : s.summary;
    return h("div", { class: `fsk-prog-result fsk-prog-result--${tone}`, role: s.status === "failed" ? "alert" : null },
      h("span", { class: "fsk-prog-rchip", "aria-hidden": "true" }, icon(ic, 16)),
      h("div", { class: "fsk-prog-rtext" },
        h("p", { class: "fsk-prog-rtitle" }, outcomeTitle()),
        body && h("p", { class: "fsk-prog-rbody" }, body),
        // Partly done: the result link sits here, so the footer keeps to what to do about the failures.
        s.status === "partial" && s.link && h("a", { class: "fsk-prog-rlink", href: s.link.href, target: "_top" }, s.link.label, icon("arrowRight", 14)),
        actionError && h("p", { class: "fsk-prog-err", role: "alert" }, actionError)));
  }

  function paintFooter(focusIt = false) {
    const s = state;
    const hadFocus = footer.contains(root.ownerDocument.activeElement);
    let focus = null;
    const parts = [];
    footer.classList.toggle("fsk-prog-actions--confirm", confirming);
    if (s.status === "running") {
      const canCancel = !!actions?.cancel && (s.cancelable ?? true);
      if (confirming) {
        const keep = h("button", { class: "fsk-btn fsk-btn--ghost", type: "button", disabled: busy === "cancel", onclick: () => { confirming = false; paintFooter(true); } }, "Keep going");
        const stop = h("button", { class: "fsk-btn fsk-prog-stop fsk-prog-main-btn", type: "button", disabled: busy === "cancel", onclick: onStop },
          ...(busy === "cancel" ? [h("span", { class: "fsk-spinner", "aria-hidden": "true" }), "Stopping…"] : [icon("x", 15), `Stop ${noun()}`]));
        parts.push(h("p", { class: "fsk-prog-ask", id: `${uid}-ask` }, h("b", {}, `Stop the ${noun()}?`),
          h("span", {}, `${unit().charAt(0).toUpperCase()}${unit().slice(1)} already done stay. The rest won't run.`)), keep, stop);
        footer.setAttribute("role", "group");
        footer.setAttribute("aria-labelledby", `${uid}-ask`);
        focus = keep;
      } else {
        footer.removeAttribute("role");
        footer.removeAttribute("aria-labelledby");
        parts.push(h("span", { class: "fsk-prog-hintline" }, icon("info", 13), "Runs in the background. Keep chatting."));
        if (canCancel) {
          const cancel = h("button", { class: "fsk-btn fsk-btn--ghost fsk-prog-quiet", type: "button", onclick: () => { confirming = true; paintFooter(true); } }, `Cancel ${noun()}`);
          parts.push(cancel);
          focus = cancel;
        }
        if (actionError) parts.unshift(h("p", { class: "fsk-prog-err", role: "alert", style: { flexBasis: "100%", margin: "0" } }, actionError));
      }
    } else {
      footer.removeAttribute("role");
      footer.removeAttribute("aria-labelledby");
      const failedN = s.failed ?? 0;
      const canRetry = !!actions?.retry && (s.status === "failed" || (s.status === "partial" && failedN > 0));
      if (s.reportHref && (s.status === "partial" || s.status === "failed")) {
        const href = s.reportHref;
        parts.push(actions?.download
          ? h("button", { class: "fsk-btn fsk-btn--ghost", type: "button", onclick: () => actions.download?.(href) }, icon("doc", 15), "Download error report")
          : h("a", { class: "fsk-btn fsk-btn--ghost", href, download: "" }, icon("doc", 15), "Download error report"));
      }
      if (s.status === "done" && s.link) {
        parts.push(h("a", { class: "fsk-btn fsk-btn--primary fsk-prog-main-btn", href: s.link.href, target: "_top" }, s.link.label, icon("arrowRight", 15)));
      }
      parts.unshift(h("span", { class: "fsk-prog-grow" }));
      if (canRetry) {
        const label = s.status === "partial" ? `Retry ${num(failedN)} failed ${unit()}` : "Try again";
        const retry = h("button", { class: "fsk-btn fsk-btn--primary fsk-prog-main-btn", type: "button", disabled: busy === "retry", onclick: onRetry },
          ...(busy === "retry" ? [h("span", { class: "fsk-spinner", "aria-hidden": "true" }), "Retrying…"] : [icon("refresh", 15), label]));
        parts.push(retry);
        focus = retry;
      }
      if (parts.length === 1) parts.length = 0;
      footer.classList.toggle("is-pair", parts.length > 2);
    }
    footer.classList.toggle("fsk-prog-actions--final", FINAL.includes(s.status));
    footer.hidden = parts.length === 0;
    footer.replaceChildren(...parts.filter((x) => !!x));
    if ((focusIt || hadFocus) && !footer.hidden) (focus && !focus.hasAttribute("disabled") ? focus : footer.querySelector("button:not([disabled]), a"))?.focus();
  }

  async function onStop() {
    if (busy || !actions?.cancel) return;
    busy = "cancel";
    actionError = "";
    paintFooter();
    try {
      await actions.cancel();
      busy = null;
      if (state.status === "running") apply({ status: "cancelled" }, true);
    } catch (err) {
      busy = null;
      confirming = false;
      actionError = (err instanceof Error && err.message) || `The ${noun()} didn't stop. It's still running.`;
      paintFooter(true);
    }
  }

  async function onRetry() {
    if (busy || !actions?.retry) return;
    busy = "retry";
    actionError = "";
    paintFooter();
    try {
      await actions.retry();
      busy = null;
      if (FINAL.includes(state.status)) apply({ status: "running" }, true);
    } catch (err) {
      busy = null;
      actionError = (err instanceof Error && err.message) || "That didn't start. Nothing changed. Try again in a minute.";
      render(true);
    }
  }

  function stop() {
    alive = false;
    off?.();
    if (ticker) win.clearInterval(ticker);
    ticker = 0;
  }

  return () => {
    stop();
    root.replaceChildren();
  };
}

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

/** Loading (meter and step bones in the card's shape), empty or error, drawn as this card. Report displayed() yourself. */
export function mountState({ root, head, state, title, subtitle, surface = "desktop" }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-prog", CSS);
  const skeleton = () => h("div", {},
    h("div", { class: "fsk-prog-figs" }, h("div", { class: "fsk-prog-main" }, bone("58px", "26px"), bone("110px", "10px", { i: 1 })), bone("84px", "10px", { i: 2 })),
    h("div", { style: { marginTop: "12px" } }, bone("100%", "8px", { i: 3 })),
    h("div", { class: "fsk-prog-steps" }, Array.from({ length: 4 }, (_, i) =>
      h("div", { class: "fsk-prog-step is-pending", style: { alignItems: "center" } },
        bone("20px", "20px", { cls: "fsk-bone--round", i: i + 4 }), bone(`${[52, 38, 60, 44][i]}%`, "10px", { i: i + 4 }), h("span", {})))));
  const card = stateCard({ state, cls: "fsk-prog", icon: "refresh", title, subtitle, surface, skeleton });
  root.replaceChildren(card.el);
  return () => { card.dispose(); root.replaceChildren(); };
}

const STEPS = [
  { id: "read", label: "Read the file", status: "done", detail: "3,000 rows, 14 columns" },
  { id: "map", label: "Match columns", status: "done", detail: "14 of 14 mapped" },
  { id: "dedupe", label: "Merge duplicates", status: "done", detail: "214 merged into existing contacts" },
  { id: "import", label: "Import contacts", status: "running", detail: "1,240 of 3,000" },
  { id: "list", label: "Add to the Q4 webinar list", status: "pending" },
  { id: "notify", label: "Notify contact owners", status: "pending" },
];

export const fixtures = {
  default: {
    title: "Importing contacts",
    subtitle: "contacts-november.csv · to the Q4 webinar list",
    icon: "users",
    status: "running",
    done: 1240,
    total: 3000,
    unit: "rows",
    jobNoun: "import",
    steps: STEPS,
  },
  done: {
    title: "Contacts imported",
    subtitle: "contacts-november.csv · to the Q4 webinar list",
    icon: "users",
    status: "done",
    done: 3000,
    total: 3000,
    unit: "rows",
    jobNoun: "import",
    summary: "3,000 contacts are in the Q4 webinar list. 214 were merged into contacts you already had.",
    link: { label: "Open contacts", href: "https://app.example.com/contacts?list=q4-webinar" },
    steps: STEPS.map((s) => ({ ...s, status: "done", detail: s.id === "import" ? "3,000 imported" : s.id === "list" ? "3,000 added" : s.id === "notify" ? "6 owners emailed" : s.detail })),
  },
  partial: {
    title: "Contacts imported",
    subtitle: "contacts-november.csv · to the Q4 webinar list",
    icon: "users",
    status: "partial",
    done: 3000,
    total: 3000,
    failed: 12,
    unit: "rows",
    jobNoun: "import",
    summary: "12 rows have a missing or invalid email. Fix them from the error report, or retry them as they are.",
    reportHref: "data:text/csv;charset=utf-8,row%2Cemail%2Cerror%0A118%2C%2Cmissing%20email%0A409%2Cdana%40acme%2Cinvalid%20email%0A",
    link: { label: "Open contacts", href: "https://app.example.com/contacts?list=q4-webinar" },
    steps: [
      ...STEPS.slice(0, 3),
      { id: "import", label: "Import contacts", status: "done", detail: "2,988 imported", failed: 12 },
      { id: "list", label: "Add to the Q4 webinar list", status: "done", detail: "2,988 added" },
      { id: "notify", label: "Notify contact owners", status: "skipped", detail: "The file has no owner column" },
    ],
  },
  failed: {
    title: "Import stopped",
    subtitle: "contacts-november.csv · to the Q4 webinar list",
    icon: "users",
    status: "failed",
    done: 1240,
    total: 3000,
    unit: "rows",
    jobNoun: "import",
    error: "The CRM stopped answering after 1,240 rows. Those rows are in; nothing else changed.",
    steps: [
      ...STEPS.slice(0, 3),
      { id: "import", label: "Import contacts", status: "failed", detail: "CRM timed out at row 1,241" },
      { id: "list", label: "Add to the Q4 webinar list", status: "pending" },
      { id: "notify", label: "Notify contact owners", status: "pending" },
    ],
  },
};
```

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

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