# AI prompt redaction

> Privacy-aware AI composer with You see and Model sees views, toggleable entity redaction chips, locked secrets and restored replies.

- Kind: block · Category: AI · Interactivity: script
- Install: `npx shadcn@latest add @haze/ai-redact`
- File: `src/components/haze/blocks/ai-redact.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/blocks/ai-redact

## Use when
- Sending customer support or financial prompts to an LLM while keeping PII and API keys redacted
- Showing users an interactive You see versus Model sees preview before submitting sensitive data

## Avoid when
- Collecting a single password or token field without conversational prompt masking; use password-input
- Building a general prompt input without entity detection or redaction controls; use ai-prompt

## Alternatives
- [ai-prompt](https://hazeui.com/blocks/ai-prompt.md)
- [ai-send](https://hazeui.com/blocks/ai-send.md)
- [password-input](https://hazeui.com/ui/password-input.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` | "haze-ai-redact" | no | Unique prefix for headings and prompt labels. |
| title | `string` | "Support assistant" | no | Header title for the privacy-aware composer. |
| initialMessage | `string` | Demo support prompt | no | Prefilled message containing sample sensitive entities. |
| entities | `RedactEntity[]` | 5 demo entities | no | Detected entities with token names, values and lock state. |
| class | `string` |  | no | Extra classes on the outer section. |

## Accessibility
- The You see and Model sees controls plus every entity chip expose aria-pressed states, while locked API secrets carry disabled and a clear lock icon.
- Mode switches, chip redaction toggles and local reply restoration announce cleanly via a polite role="status" region.
- Key Tab: Move across visibility toggle buttons, prompt textarea, redaction chips, Mask all and Send
- Key Enter / Space: Switch between You see and Model sees, toggle an entity chip or submit the redacted prompt

## Agent prompts

### Install and use

Install the Haze UI block "AI prompt redaction" with `npx shadcn@latest add @haze/ai-redact`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import AiRedact from "@/components/haze/blocks/ai-redact.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/blocks/ai-redact.md

### Customize with real content

Adapt the Haze ai-redact block for our product. Replace the demo values of these props with our real content: id, title, initialMessage, entities, class. Keep the layout, the heading level rules and these accessibility details: The You see and Model sees controls plus every entity chip expose aria-pressed states, while locked API secrets carry disabled and a clear lock icon. Mode switches, chip redaction toggles and local reply restoration announce cleanly via a polite role="status" region. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using ai-redact, check it fits: use it when sending customer support or financial prompts to an llm while keeping pii and api keys redacted; showing users an interactive you see versus model sees preview before submitting sensitive data. Avoid it when collecting a single password or token field without conversational prompt masking; use password-input; building a general prompt input without entity detection or redaction controls; use ai-prompt. Alternatives: @haze/ai-prompt, @haze/ai-send, @haze/password-input.

## Example requests that should lead here
- Build a privacy-aware AI prompt redaction card with You see and Model sees previews, toggleable PII chips and locked API key masking
- Add an LLM composer that previews masked tokens before send and restores real values in the assistant response

## Source

```astro
---
import { ArrowUp, CreditCard, KeyRound, Lock, Mail, Phone, ShieldCheck, User } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface RedactEntity {
  id: string;
  token: string;
  value: string;
  locked?: boolean;
  masked: boolean;
}

interface Props {
  id?: string;
  title?: string;
  initialMessage?: string;
  entities?: RedactEntity[];
  class?: string;
}

const {
  id = "haze-ai-redact",
  title = "Support assistant",
  initialMessage = "Draft a reply to Elena Novak (elena@bracken.io, +41 44 555 0192) confirming the refund to card 4532 8910 2214 4242. The charge failed with key sk_live_94k2m8x1q7, what does that error mean?",
  entities = [
    { id: "ent-person", token: "PERSON_1", value: "Elena Novak", masked: true },
    { id: "ent-email", token: "EMAIL_1", value: "elena@bracken.io", masked: true },
    { id: "ent-phone", token: "PHONE_1", value: "+41 44 555 0192", masked: true },
    { id: "ent-card", token: "CARD_1", value: "4532 8910 2214 4242", masked: true },
    { id: "ent-secret", token: "SECRET_1", value: "sk_live_94k2m8x1q7", locked: true, masked: true },
  ],
  class: className,
} = Astro.props;

const maskedTotal = entities.filter((e) => e.masked || e.locked).length;
---

<section
  aria-labelledby={`${id}-title`}
  data-haze-ai-redact
  data-initial-message={initialMessage}
  data-initial-entities={JSON.stringify(entities)}
  class={cn("bg-background px-4 py-10 sm:px-6 sm:py-14", className)}
>
  <div class="mx-auto max-w-lg overflow-hidden rounded-2xl border border-border bg-card shadow-key">
    <header class="flex flex-wrap items-center justify-between gap-3 border-b border-border px-5 py-3.5">
      <div class="flex min-w-0 items-center gap-2">
        <ShieldCheck class="size-4 shrink-0 text-muted-foreground" aria-hidden="true" />
        <h2 id={`${id}-title`} class="truncate text-sm/5 font-semibold tracking-tight text-foreground">
          {title}
        </h2>
      </div>

      <div
        role="group"
        aria-label="Prompt visibility mode"
        class="inline-flex rounded-full border border-frame bg-muted/50 p-0.5"
      >
        <button
          type="button"
          data-view-mode="user"
          aria-pressed="true"
          class="inline-flex h-7 cursor-pointer items-center rounded-full px-3 text-xs font-medium text-muted-foreground transition-colors duration-150 ease-snappy hover:text-foreground aria-pressed:bg-background aria-pressed:text-foreground aria-pressed:shadow-key focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
        >
          You see
        </button>
        <button
          type="button"
          data-view-mode="model"
          aria-pressed="false"
          class="inline-flex h-7 cursor-pointer items-center rounded-full px-3 text-xs font-medium text-muted-foreground transition-colors duration-150 ease-snappy hover:text-foreground aria-pressed:bg-background aria-pressed:text-foreground aria-pressed:shadow-key focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
        >
          Model sees
        </button>
      </div>
    </header>

    <div class="flex min-h-48 flex-col justify-center px-6 py-8">
      <p data-empty-explainer class="mx-auto max-w-xs text-center text-xs/5 text-pretty text-muted-foreground">
        Names, emails, numbers and keys are swapped for placeholders before anything leaves the browser. Replies are filled back in here.
      </p>

      <div data-exchange-thread hidden class="space-y-4">
        <div class="flex justify-end">
          <div
            data-sent-bubble
            class="max-w-[90%] rounded-2xl bg-muted px-4 py-2.5 text-sm/6 break-words text-foreground"
          ></div>
        </div>
        <div data-reply-bubble class="text-sm/6 break-words text-pretty text-foreground"></div>
      </div>
    </div>

    <form data-redact-form class="mx-4 mb-2.5 space-y-3 rounded-2xl border border-border bg-muted/30 p-3.5">
      <div
        data-prompt-display
        aria-label="Prompt preview with sensitive items highlighted"
        class="text-sm/7 break-words text-foreground"
      >
        {initialMessage}
      </div>

      <div class="flex flex-wrap items-center justify-between gap-2 pt-0.5">
        <div data-chip-list class="flex min-w-0 flex-wrap items-center gap-1.5">
          {
            entities.map((ent) => (
              <button
                type="button"
                data-entity-chip={ent.id}
                disabled={ent.locked ? true : undefined}
                aria-pressed={ent.masked || ent.locked ? "true" : "false"}
                class={cn(
                  "inline-flex h-7 items-center gap-1.5 rounded-full border px-2.5 font-mono text-[0.6875rem] transition-colors duration-150 ease-snappy focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring",
                  ent.locked
                    ? "cursor-not-allowed border-frame bg-card/60 text-muted-foreground opacity-80"
                    : "cursor-pointer border-frame-strong bg-field text-foreground hover:border-frame-hover",
                )}
              >
                <span class="truncate">{ent.token}</span>
                {ent.locked && <Lock class="size-3 shrink-0 text-muted-foreground" aria-hidden="true" />}
              </button>
            ))
          }
        </div>

        <button
          type="submit"
          aria-label="Send redacted prompt"
          class="inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-full bg-primary text-primary-foreground transition-[opacity,scale] duration-150 ease-snappy hover:opacity-90 active:scale-95 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
        >
          <ArrowUp class="size-4" aria-hidden="true" />
        </button>
      </div>
    </form>

    <p data-redact-caption class="px-5 pb-3.5 text-xs/4 text-muted-foreground">
      {maskedTotal} {maskedTotal === 1 ? "item" : "items"} will be masked. Click one to send it as is.
    </p>

    <p data-redact-status role="status" class="sr-only"></p>
  </div>

  <template data-redact-icons>
    <span data-ic-person><User class="size-3 shrink-0 text-muted-foreground" aria-hidden="true" /></span>
    <span data-ic-email><Mail class="size-3 shrink-0 text-muted-foreground" aria-hidden="true" /></span>
    <span data-ic-phone><Phone class="size-3 shrink-0 text-muted-foreground" aria-hidden="true" /></span>
    <span data-ic-card><CreditCard class="size-3 shrink-0 text-muted-foreground" aria-hidden="true" /></span>
    <span data-ic-secret><KeyRound class="size-3 shrink-0 text-muted-foreground" aria-hidden="true" /></span>
    <span data-ic-lock><Lock class="size-3 shrink-0 text-muted-foreground" aria-hidden="true" /></span>
  </template>
</section>

<script>
  interface RedactEntity {
    id: string;
    token: string;
    value: string;
    locked?: boolean;
    masked: boolean;
  }

  function initAiRedact() {
    document.querySelectorAll<HTMLElement>("[data-haze-ai-redact]").forEach((root) => {
      if (root.hasAttribute("data-enhanced")) return;
      root.setAttribute("data-enhanced", "");

      const raw = root.dataset.initialEntities;
      const sourceMessage = root.dataset.initialMessage ?? "";
      const promptDisplay = root.querySelector<HTMLElement>("[data-prompt-display]");
      const chipList = root.querySelector<HTMLElement>("[data-chip-list]");
      const captionEl = root.querySelector<HTMLElement>("[data-redact-caption]");
      const emptyExplainer = root.querySelector<HTMLElement>("[data-empty-explainer]");
      const exchangeThread = root.querySelector<HTMLElement>("[data-exchange-thread]");
      const sentBubble = root.querySelector<HTMLElement>("[data-sent-bubble]");
      const replyBubble = root.querySelector<HTMLElement>("[data-reply-bubble]");
      const form = root.querySelector<HTMLFormElement>("[data-redact-form]");
      const statusEl = root.querySelector<HTMLElement>("[data-redact-status]");
      const iconTpl = root.querySelector<HTMLTemplateElement>("[data-redact-icons]");

      if (!raw || !promptDisplay || !chipList) return;

      let entities: RedactEntity[] = [];
      try {
        entities = JSON.parse(raw) as RedactEntity[];
      } catch {
        return;
      }

      let mode: "user" | "model" = "user";
      let hasSent = false;

      const cloneIcon = (sel: string): Node | null => {
        const el = iconTpl?.content.querySelector(sel)?.firstElementChild;
        return el ? el.cloneNode(true) : null;
      };

      const iconSelectorForToken = (token: string): string => {
        if (token.startsWith("PERSON")) return "[data-ic-person]";
        if (token.startsWith("EMAIL")) return "[data-ic-email]";
        if (token.startsWith("PHONE")) return "[data-ic-phone]";
        if (token.startsWith("CARD")) return "[data-ic-card]";
        return "[data-ic-secret]";
      };

      const renderPromptInto = (container: HTMLElement, interactive: boolean) => {
        const present = entities
          .map((ent) => ({ ent, idx: sourceMessage.indexOf(ent.value) }))
          .filter((hit) => hit.ent.value.length > 0 && hit.idx !== -1)
          .sort((a, b) => a.idx - b.idx);

        const frag = document.createDocumentFragment();
        let cursor = 0;

        for (const hit of present) {
          const idx = sourceMessage.indexOf(hit.ent.value, cursor);
          if (idx === -1) continue;
          if (idx > cursor) {
            frag.append(document.createTextNode(sourceMessage.slice(cursor, idx)));
          }

          const isProtected = Boolean(hit.ent.masked || hit.ent.locked);

          if (mode === "model" && isProtected) {
            const span = document.createElement("span");
            span.className = hit.ent.locked
              ? "mx-0.5 inline-block rounded-sm bg-destructive/14 px-1.5 font-mono text-xs text-destructive"
              : "mx-0.5 inline-block rounded-sm bg-muted px-1.5 font-mono text-xs text-foreground";
            span.textContent = `[${hit.ent.token}]`;
            frag.append(span);
          } else if (interactive && !hit.ent.locked) {
            const btn = document.createElement("button");
            btn.type = "button";
            btn.className = isProtected
              ? "inline cursor-pointer rounded-sm bg-warning/14 px-1 text-left text-warning transition-colors duration-150 ease-snappy hover:bg-warning/20 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
              : "inline cursor-pointer rounded-sm px-0.5 text-left text-foreground underline decoration-dashed decoration-border-strong underline-offset-4 transition-colors duration-150 ease-snappy hover:bg-muted focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring";
            btn.textContent = hit.ent.value;
            btn.title = isProtected ? `Masked as ${hit.ent.token}. Click to send as is.` : `Sending raw. Click to mask as ${hit.ent.token}.`;
            btn.addEventListener("click", () => {
              hit.ent.masked = !hit.ent.masked;
              renderAll();
              if (statusEl) {
                statusEl.textContent = hit.ent.masked
                  ? `${hit.ent.token} will be masked before sending.`
                  : `${hit.ent.token} will be sent as is.`;
              }
            });
            frag.append(btn);
          } else {
            const span = document.createElement("span");
            span.className = isProtected
              ? "rounded-sm bg-warning/14 px-1 text-warning"
              : "text-foreground underline decoration-dashed decoration-border-strong underline-offset-4";
            span.textContent = hit.ent.value;
            frag.append(span);
          }

          cursor = idx + hit.ent.value.length;
        }

        if (cursor < sourceMessage.length) {
          frag.append(document.createTextNode(sourceMessage.slice(cursor)));
        }
        container.replaceChildren(frag);
      };

      const renderReply = () => {
        if (!replyBubble) return;
        const person = entities.find((e) => e.token === "PERSON_1");
        const email = entities.find((e) => e.token === "EMAIL_1");
        const card = entities.find((e) => e.token === "CARD_1");
        const secret = entities.find((e) => e.token === "SECRET_1");

        const parts: { text: string; ent?: RedactEntity }[] = [
          { text: "Hi " },
          { text: person?.value ?? "there", ent: person },
          { text: " — your refund to card " },
          { text: card?.value ?? "on file", ent: card },
          { text: " is confirmed, and a receipt is headed to " },
          { text: email?.value ?? "your inbox", ent: email },
          { text: ". The decline on " },
          { text: secret?.value ?? "the API key", ent: secret },
          { text: " usually means a rotated key was still cached in the retry worker." },
        ];

        const frag = document.createDocumentFragment();
        parts.forEach((part) => {
          if (!part.ent) {
            frag.append(document.createTextNode(part.text));
            return;
          }
          const isProtected = Boolean(part.ent.masked || part.ent.locked);
          const span = document.createElement("span");
          if (mode === "model" && isProtected) {
            span.className = part.ent.locked
              ? "mx-0.5 inline-block rounded-sm bg-destructive/14 px-1 font-mono text-xs text-destructive"
              : "mx-0.5 inline-block rounded-sm bg-muted px-1 font-mono text-xs text-foreground";
            span.textContent = `[${part.ent.token}]`;
          } else if (isProtected) {
            span.className = "rounded-sm bg-success/14 px-1 text-success";
            span.textContent = part.ent.value;
          } else {
            span.textContent = part.ent.value;
          }
          frag.append(span);
        });
        replyBubble.replaceChildren(frag);
      };

      const renderChips = () => {
        const maskedCount = entities.filter((e) => e.masked || e.locked).length;
        if (captionEl) {
          captionEl.textContent = `${maskedCount} ${maskedCount === 1 ? "item" : "items"} will be masked. Click one to send it as is.`;
        }

        const frag = document.createDocumentFragment();
        entities.forEach((ent) => {
          const btn = document.createElement("button");
          btn.type = "button";
          const isProtected = Boolean(ent.masked || ent.locked);
          btn.setAttribute("aria-pressed", String(isProtected));

          if (ent.locked) {
            btn.disabled = true;
            btn.title = "Secrets stay locked and are always masked";
            btn.className =
              "inline-flex h-7 cursor-not-allowed items-center gap-1.5 rounded-full border border-frame bg-card/60 px-2.5 font-mono text-[0.6875rem] text-muted-foreground opacity-80 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring";
          } else if (isProtected) {
            btn.title = `Masked as ${ent.token}. Click to send as is.`;
            btn.className =
              "inline-flex h-7 cursor-pointer items-center gap-1.5 rounded-full border border-frame-strong bg-field px-2.5 font-mono text-[0.6875rem] text-foreground transition-colors duration-150 ease-snappy hover:border-frame-hover focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring";
          } else {
            btn.title = `Unmasked (${ent.value}). Click to mask again.`;
            btn.className =
              "inline-flex h-7 cursor-pointer items-center gap-1.5 rounded-full border border-border bg-transparent px-2.5 font-mono text-[0.6875rem] text-muted-foreground line-through transition-colors duration-150 ease-snappy hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring";
          }

          const leadIc = cloneIcon(iconSelectorForToken(ent.token));
          if (leadIc) btn.append(leadIc);

          const label = document.createElement("span");
          label.textContent = ent.token;
          btn.append(label);

          if (ent.locked) {
            const lockIc = cloneIcon("[data-ic-lock]");
            if (lockIc) btn.append(lockIc);
          } else {
            btn.addEventListener("click", () => {
              ent.masked = !ent.masked;
              renderAll();
              if (statusEl) {
                statusEl.textContent = ent.masked
                  ? `${ent.token} will be masked before sending.`
                  : `${ent.token} will be sent as is.`;
              }
            });
          }

          frag.append(btn);
        });
        chipList.replaceChildren(frag);
      };

      const renderAll = () => {
        renderPromptInto(promptDisplay, true);
        renderChips();
        if (hasSent && sentBubble) {
          renderPromptInto(sentBubble, false);
          renderReply();
        }
      };

      root.querySelectorAll<HTMLButtonElement>("[data-view-mode]").forEach((btn) => {
        btn.addEventListener("click", () => {
          mode = btn.dataset.viewMode === "model" ? "model" : "user";
          root.querySelectorAll<HTMLButtonElement>("[data-view-mode]").forEach((b) => {
            b.setAttribute("aria-pressed", String(b === btn));
          });
          renderAll();
          if (statusEl) {
            statusEl.textContent = mode === "model" ? "Showing redacted model view." : "Showing local browser view.";
          }
        });
      });

      form?.addEventListener("submit", (ev) => {
        ev.preventDefault();
        hasSent = true;
        if (emptyExplainer) emptyExplainer.hidden = true;
        if (exchangeThread) exchangeThread.hidden = false;
        renderAll();
        const protectedCount = entities.filter((e) => e.masked || e.locked).length;
        if (statusEl) {
          statusEl.textContent = `Sent with ${protectedCount} of ${entities.length} items masked. Local values restored in reply.`;
        }
      });

      renderAll();
    });
  }

  initAiRedact();
  document.addEventListener("astro:page-load", initAiRedact);
</script>
```
