# AI message queue

> Live running agent panel paired with a reorderable follow-up queue, inline edit, immediate interrupt send and keyboard composer.

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

## Use when
- Letting users stack follow-up prompts while a long-running coding or research agent is still working
- Supporting queue reordering, inline prompt edits, pause/resume controls and immediate Ctrl+Enter interrupts

## Avoid when
- Showing a static checklist of agent subtasks without a live composer; use agent-tasks instead
- Providing a single standalone prompt box without a running queue; use ai-prompt

## Alternatives
- [agent-tasks](https://hazeui.com/blocks/agent-tasks.md)
- [ai-prompt](https://hazeui.com/blocks/ai-prompt.md)
- [sortable-list](https://hazeui.com/ui/sortable-list.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` | "haze-ai-message-queue" | no | Unique prefix for headings and composer labels. |
| title | `string` | "Auth refactor" | no | Active task title shown in the running agent header. |
| activePrompt | `string` | Demo refactor prompt | no | Prompt currently being executed by the agent. |
| steps | `string[]` | 4 demo steps | no | Progress steps cycled while the agent is working. |
| queue | `QueueItem[]` | 2 demo follow-ups | no | Initial queued follow-up prompts waiting to run. |
| placeholder | `string` | "Queue a follow-up…" | no | Composer textarea placeholder text. |
| class | `string` |  | no | Extra classes on the outer section. |

## Accessibility
- Every queue row exposes explicit Move up, Move down, Edit, Send now and Remove controls with item-specific aria-labels.
- Queue changes, reorder steps, agent pause/resume and immediate sends are announced via a polite role="status" live region.
- Key Enter: Queue the follow-up message currently typed in the composer
- Key Ctrl+Enter: Interrupt the active run and send the composer message immediately
- Key Tab: Move across Stop/Resume, Clear, per-row reorder/edit/send/remove actions and composer

## Agent prompts

### Install and use

Install the Haze UI block "AI message queue" with `npx shadcn@latest add @haze/ai-message-queue`. 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 AiMessageQueue from "@/components/haze/blocks/ai-message-queue.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-message-queue.md

### Customize with real content

Adapt the Haze ai-message-queue block for our product. Replace the demo values of these props with our real content: id, title, activePrompt, steps, queue, placeholder, class. Keep the layout, the heading level rules and these accessibility details: Every queue row exposes explicit Move up, Move down, Edit, Send now and Remove controls with item-specific aria-labels. Queue changes, reorder steps, agent pause/resume and immediate sends are announced via a polite role="status" live region. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using ai-message-queue, check it fits: use it when letting users stack follow-up prompts while a long-running coding or research agent is still working; supporting queue reordering, inline prompt edits, pause/resume controls and immediate ctrl+enter interrupts. Avoid it when showing a static checklist of agent subtasks without a live composer; use agent-tasks instead; providing a single standalone prompt box without a running queue; use ai-prompt. Alternatives: @haze/agent-tasks, @haze/ai-prompt, @haze/sortable-list.

## Example requests that should lead here
- Create an AI message queue block with a live running agent panel, reorderable follow-ups, Send now interrupts and Enter/Ctrl+Enter composer
- Build an agent prompt queue where users can edit, move up/down, remove or clear pending follow-up instructions

## Source

```astro
---
import { ArrowDown, ArrowUp, Check, GripVertical, Pencil, Play, Square, Trash2, X, Zap } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface QueueItem {
  id: string;
  text: string;
}

interface Props {
  id?: string;
  title?: string;
  activePrompt?: string;
  steps?: string[];
  queue?: QueueItem[];
  placeholder?: string;
  class?: string;
}

const {
  id = "haze-ai-message-queue",
  title = "Auth refactor",
  activePrompt = "Move session handling onto the new token store",
  steps = [
    "Reading src/auth/session.ts",
    "Checking token verification middleware",
    "Updating session rotation unit tests",
    "Verifying cookie expiry headers",
  ],
  queue = [
    { id: "q-1", text: "Also add a test for expired tokens" },
    { id: "q-2", text: "Keep the old cookie name for now" },
  ],
  placeholder = "Queue a follow-up...",
  class: className,
} = Astro.props;
---

<section
  aria-labelledby={`${id}-title`}
  data-haze-ai-message-queue
  data-instance-id={id}
  data-initial-prompt={activePrompt}
  data-initial-steps={JSON.stringify(steps)}
  data-initial-queue={JSON.stringify(queue)}
  class={cn("bg-background px-4 py-10 sm:px-6 sm:py-14", className)}
>
  <div class="mx-auto max-w-md overflow-hidden rounded-2xl border border-border bg-card shadow-key">
    <header class="flex items-center justify-between gap-3 border-b border-border px-5 py-3.5">
      <h2 id={`${id}-title`} class="truncate text-sm/5 font-semibold tracking-tight text-foreground">
        {title}
      </h2>
      <span data-agent-badge class="inline-flex shrink-0 items-center gap-1.5 text-xs/4 font-medium text-foreground">
        <span data-agent-dot class="size-1.5 rounded-full bg-brand animate-pulse" aria-hidden="true"></span>
        <span data-agent-state>Working</span>
      </span>
    </header>

    <div class="flex min-h-48 flex-col justify-end space-y-4 px-5 pt-16 pb-4">
      <div class="flex justify-end">
        <div
          data-active-prompt
          class="max-w-[88%] rounded-2xl bg-muted px-4 py-2.5 text-sm/6 break-words text-foreground"
        >
          {activePrompt}
        </div>
      </div>

      <div class="flex items-center justify-between gap-3 text-xs/5">
        <div class="flex min-w-0 items-center gap-2 text-muted-foreground">
          <span data-step-dot class="size-1.5 shrink-0 rounded-full bg-foreground/70 animate-pulse" aria-hidden="true"></span>
          <span data-step-label class="truncate">{steps[0]}</span>
        </div>
        <span data-step-meta class="shrink-0 font-mono text-xs text-muted-foreground tabular-nums">
          1/{steps.length} · 1s
        </span>
      </div>
    </div>

    <div class="mx-3 mb-2.5 overflow-hidden rounded-2xl border border-border bg-muted/30">
      <div data-queue-section class="space-y-1.5 border-b border-border p-2.5">
        <div class="flex items-center justify-between gap-2 px-1 pb-0.5 text-xs text-muted-foreground">
          <span>
            Queued <span data-queue-count class="tabular-nums">{queue.length}</span>
          </span>
          <button
            type="button"
            data-queue-clear
            class="inline-flex min-h-6 cursor-pointer items-center rounded-sm px-1.5 text-xs text-muted-foreground transition-colors duration-150 ease-snappy hover:text-foreground disabled:cursor-not-allowed disabled:opacity-40 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
          >
            Clear
          </button>
        </div>

        <ul role="list" data-queue-list class="space-y-1.5">
          {
            queue.map((item, idx) => (
              <li class="group relative flex items-center gap-2 overflow-hidden rounded-xl border border-border bg-card px-3 py-2 text-xs">
                <GripVertical class="size-3.5 shrink-0 text-muted-foreground/50" aria-hidden="true" />
                <span class="w-3.5 shrink-0 text-center font-mono text-[0.6875rem] text-muted-foreground tabular-nums">
                  {idx + 1}
                </span>
                <span class="min-w-0 flex-1 truncate text-foreground">{item.text}</span>
                {idx === 0 && (
                  <span
                    data-next-progress
                    style="width: 28%;"
                    aria-hidden="true"
                    class="pointer-events-none absolute bottom-0 left-0 h-0.5 bg-primary transition-[width] duration-300 ease-smooth"
                  ></span>
                )}
              </li>
            ))
          }
        </ul>
      </div>

      <form data-queue-form class="flex items-center gap-2 px-3 py-2.5">
        <label for={`${id}-composer`} class="sr-only">Queue a follow-up message</label>
        <input
          id={`${id}-composer`}
          data-queue-input
          type="text"
          placeholder={placeholder}
          class="-m-px border border-frame-input min-w-0 flex-1 rounded-md bg-transparent px-1 py-1 text-sm text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/24 focus-visible:outline-hidden"
        />
        <button
          type="button"
          data-dock-action
          aria-label="Stop agent"
          class="inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-full border border-frame bg-muted text-foreground transition-colors duration-150 ease-snappy hover:border-frame-strong hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-95"
        >
          <span data-act-stop><Square class="size-3 fill-current" aria-hidden="true" /></span>
          <span data-act-play hidden><Play class="size-3 fill-current" aria-hidden="true" /></span>
          <span data-act-send hidden><ArrowUp class="size-3.5" aria-hidden="true" /></span>
        </button>
      </form>
    </div>

    <p class="px-5 pb-3.5 text-[0.6875rem]/4 text-muted-foreground">
      ↵ to queue · Ctrl ↵ to send now
    </p>

    <p data-queue-status role="status" class="sr-only"></p>
  </div>

  <template data-queue-icons>
    <span data-q-grip><GripVertical class="size-3.5 shrink-0 text-muted-foreground/50" aria-hidden="true" /></span>
    <span data-q-up><ArrowUp class="size-3" aria-hidden="true" /></span>
    <span data-q-down><ArrowDown class="size-3" aria-hidden="true" /></span>
    <span data-q-edit><Pencil class="size-3" aria-hidden="true" /></span>
    <span data-q-zap><Zap class="size-3" aria-hidden="true" /></span>
    <span data-q-trash><Trash2 class="size-3" aria-hidden="true" /></span>
    <span data-q-check><Check class="size-3" aria-hidden="true" /></span>
    <span data-q-close><X class="size-3" aria-hidden="true" /></span>
  </template>
</section>

<script>
  interface QueueItem {
    id: string;
    text: string;
  }

  function initAiMessageQueue() {
    document.querySelectorAll<HTMLElement>("[data-haze-ai-message-queue]").forEach((root) => {
      if (root.hasAttribute("data-enhanced")) return;
      root.setAttribute("data-enhanced", "");

      const instanceId = root.dataset.instanceId ?? "haze-ai-message-queue";
      const rawSteps = root.dataset.initialSteps;
      const rawQueue = root.dataset.initialQueue;
      const listEl = root.querySelector<HTMLUListElement>("[data-queue-list]");
      const queueSection = root.querySelector<HTMLElement>("[data-queue-section]");
      const countEl = root.querySelector<HTMLElement>("[data-queue-count]");
      const clearBtn = root.querySelector<HTMLButtonElement>("[data-queue-clear]");
      const agentBadge = root.querySelector<HTMLElement>("[data-agent-badge]");
      const agentDot = root.querySelector<HTMLElement>("[data-agent-dot]");
      const agentState = root.querySelector<HTMLElement>("[data-agent-state]");
      const stepDot = root.querySelector<HTMLElement>("[data-step-dot]");
      const stepLabel = root.querySelector<HTMLElement>("[data-step-label]");
      const stepMeta = root.querySelector<HTMLElement>("[data-step-meta]");
      const activePromptEl = root.querySelector<HTMLElement>("[data-active-prompt]");
      const form = root.querySelector<HTMLFormElement>("[data-queue-form]");
      const input = root.querySelector<HTMLInputElement>("[data-queue-input]");
      const dockAction = root.querySelector<HTMLButtonElement>("[data-dock-action]");
      const stopIc = root.querySelector<HTMLElement>("[data-act-stop]");
      const playIc = root.querySelector<HTMLElement>("[data-act-play]");
      const sendIc = root.querySelector<HTMLElement>("[data-act-send]");
      const statusEl = root.querySelector<HTMLElement>("[data-queue-status]");
      const iconTpl = root.querySelector<HTMLTemplateElement>("[data-queue-icons]");

      if (!listEl || !rawSteps || !rawQueue) return;

      let steps: string[] = [];
      let queue: QueueItem[] = [];
      try {
        steps = JSON.parse(rawSteps) as string[];
        queue = JSON.parse(rawQueue) as QueueItem[];
      } catch {
        return;
      }

      let activePrompt = root.dataset.initialPrompt ?? "";
      let working = true;
      let stepIndex = 0;
      let elapsedSec = 1;
      let editingId: string | null = null;
      let counter = queue.length + 1;

      const cloneIcon = (sel: string): Node | null => {
        const el = iconTpl?.content.querySelector(sel)?.firstElementChild;
        return el ? el.cloneNode(true) : null;
      };

      const stepsForPrompt = (prompt: string): string[] => {
        const lower = prompt.toLowerCase();
        if (lower.includes("test")) {
          return [
            "Scanning tests/auth/tokens.spec.ts",
            "Writing expired token fixtures",
            "Running auth test suite",
            "Verifying assertion coverage",
          ];
        }
        if (lower.includes("cookie") || lower.includes("doc") || lower.includes("name")) {
          return [
            "Inspecting src/auth/cookies.ts",
            "Preserving legacy cookie alias",
            "Checking middleware headers",
            "Confirming session fallback",
          ];
        }
        return [
          "Inspecting workspace files",
          "Planning scoped code edits",
          "Applying requested changes",
          "Running quick type check",
        ];
      };

      const syncDockButton = () => {
        const hasText = (input?.value.trim().length ?? 0) > 0;
        if (hasText) {
          if (stopIc) stopIc.hidden = true;
          if (playIc) playIc.hidden = true;
          if (sendIc) sendIc.hidden = false;
          if (dockAction) {
            dockAction.setAttribute("aria-label", "Queue message");
            dockAction.className =
              "inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-full border border-transparent bg-primary text-primary-foreground transition-[opacity,scale] duration-150 ease-snappy hover:opacity-90 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-95";
          }
        } else {
          if (stopIc) stopIc.hidden = !working;
          if (playIc) playIc.hidden = working;
          if (sendIc) sendIc.hidden = true;
          if (dockAction) {
            dockAction.setAttribute("aria-label", working ? "Stop agent" : "Resume agent");
            dockAction.className =
              "inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-full border border-frame bg-muted text-foreground transition-colors duration-150 ease-snappy hover:border-frame-strong hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-95";
          }
        }
      };

      const renderAgent = () => {
        const total = Math.max(1, steps.length);
        const currentLabel = steps[Math.min(stepIndex, total - 1)] ?? "Working";
        const pct = Math.min(100, Math.round(((stepIndex + 1) / total) * 100));

        if (stepLabel) stepLabel.textContent = currentLabel;
        if (stepMeta) stepMeta.textContent = `${stepIndex + 1}/${total} · ${elapsedSec}s`;
        if (activePromptEl) activePromptEl.textContent = activePrompt;

        if (agentState) agentState.textContent = working ? "Working" : "Paused";
        if (agentBadge) {
          agentBadge.className = `inline-flex shrink-0 items-center gap-1.5 text-xs/4 font-medium ${
            working ? "text-foreground" : "text-muted-foreground"
          }`;
        }
        if (agentDot) {
          agentDot.className = `size-1.5 rounded-full ${working ? "bg-brand animate-pulse" : "bg-muted-foreground"}`;
        }
        if (stepDot) {
          stepDot.className = `size-1.5 shrink-0 rounded-full ${working ? "bg-foreground/70 animate-pulse" : "bg-muted-foreground/50"}`;
        }

        const progressBar = listEl.querySelector<HTMLElement>("[data-next-progress]");
        if (progressBar) progressBar.style.width = `${pct}%`;

        syncDockButton();
      };

      const runImmediately = (promptText: string, announce: string) => {
        activePrompt = promptText;
        steps = stepsForPrompt(promptText);
        stepIndex = 0;
        elapsedSec = 1;
        working = true;
        renderAgent();
        renderQueue();
        if (statusEl) statusEl.textContent = announce;
      };

      const renderQueue = () => {
        if (countEl) countEl.textContent = String(queue.length);
        if (clearBtn) clearBtn.disabled = queue.length === 0;
        if (queueSection) queueSection.hidden = queue.length === 0;

        const frag = document.createDocumentFragment();
        const total = Math.max(1, steps.length);
        const pct = Math.min(100, Math.round(((stepIndex + 1) / total) * 100));

        queue.forEach((item, idx) => {
          const li = document.createElement("li");
          li.className =
            "group relative flex items-center gap-2 overflow-hidden rounded-xl border border-border bg-card px-3 py-2 text-xs";

          if (editingId === item.id) {
            const editForm = document.createElement("form");
            editForm.className = "flex w-full items-center gap-1.5";

            const editId = `${instanceId}-edit-${item.id}`;
            const label = document.createElement("label");
            label.htmlFor = editId;
            label.className = "sr-only";
            label.textContent = "Edit queued follow-up";

            const editInput = document.createElement("input");
            editInput.id = editId;
            editInput.type = "text";
            editInput.value = item.text;
            editInput.className =
              "-mx-px border border-frame-input h-6 min-w-0 flex-1 rounded-sm bg-transparent text-xs text-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/24 focus-visible:outline-hidden";

            const saveBtn = document.createElement("button");
            saveBtn.type = "submit";
            saveBtn.setAttribute("aria-label", "Save queued message");
            saveBtn.className =
              "inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-md bg-primary text-primary-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring";
            const ck = cloneIcon("[data-q-check]");
            if (ck) saveBtn.append(ck);

            const cancelBtn = document.createElement("button");
            cancelBtn.type = "button";
            cancelBtn.setAttribute("aria-label", "Cancel edit");
            cancelBtn.className =
              "inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring";
            const cl = cloneIcon("[data-q-close]");
            if (cl) cancelBtn.append(cl);
            cancelBtn.addEventListener("click", () => {
              editingId = null;
              renderQueue();
            });

            editForm.addEventListener("submit", (ev) => {
              ev.preventDefault();
              const updated = editInput.value.trim();
              if (!updated) return;
              item.text = updated;
              editingId = null;
              renderQueue();
              if (statusEl) statusEl.textContent = `Updated queued item ${idx + 1}.`;
            });

            editForm.append(label, editInput, saveBtn, cancelBtn);
            li.append(editForm);
            window.requestAnimationFrame(() => editInput.focus());
          } else {
            const grip = cloneIcon("[data-q-grip]");
            if (grip) li.append(grip);

            const num = document.createElement("span");
            num.className = "w-3.5 shrink-0 text-center font-mono text-[0.6875rem] text-muted-foreground tabular-nums";
            num.textContent = String(idx + 1);

            const textSpan = document.createElement("span");
            textSpan.className = "min-w-0 flex-1 truncate text-foreground";
            textSpan.textContent = item.text;

            const actions = document.createElement("div");
            actions.className =
              "flex shrink-0 items-center gap-0.5 opacity-0 transition-opacity duration-150 ease-snappy group-hover:opacity-100 group-focus-within:opacity-100";

            const iconBtnClass =
              "inline-flex size-6 cursor-pointer items-center justify-center rounded-md text-muted-foreground transition-colors duration-150 ease-snappy hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-30 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring";

            const upBtn = document.createElement("button");
            upBtn.type = "button";
            upBtn.disabled = idx === 0;
            upBtn.setAttribute("aria-label", `Move up: ${item.text}`);
            upBtn.className = iconBtnClass;
            const upIc = cloneIcon("[data-q-up]");
            if (upIc) upBtn.append(upIc);
            upBtn.addEventListener("click", () => {
              if (idx === 0) return;
              const prev = queue[idx - 1];
              queue[idx - 1] = item;
              queue[idx] = prev;
              renderQueue();
              if (statusEl) statusEl.textContent = `Moved message up to position ${idx}.`;
            });

            const downBtn = document.createElement("button");
            downBtn.type = "button";
            downBtn.disabled = idx === queue.length - 1;
            downBtn.setAttribute("aria-label", `Move down: ${item.text}`);
            downBtn.className = iconBtnClass;
            const downIc = cloneIcon("[data-q-down]");
            if (downIc) downBtn.append(downIc);
            downBtn.addEventListener("click", () => {
              if (idx >= queue.length - 1) return;
              const next = queue[idx + 1];
              queue[idx + 1] = item;
              queue[idx] = next;
              renderQueue();
              if (statusEl) statusEl.textContent = `Moved message down to position ${idx + 2}.`;
            });

            const editBtn = document.createElement("button");
            editBtn.type = "button";
            editBtn.setAttribute("aria-label", `Edit: ${item.text}`);
            editBtn.className = iconBtnClass;
            const editIc = cloneIcon("[data-q-edit]");
            if (editIc) editBtn.append(editIc);
            editBtn.addEventListener("click", () => {
              editingId = item.id;
              renderQueue();
            });

            const nowBtn = document.createElement("button");
            nowBtn.type = "button";
            nowBtn.setAttribute("aria-label", `Send now: ${item.text}`);
            nowBtn.className =
              "inline-flex size-6 cursor-pointer items-center justify-center rounded-md text-muted-foreground transition-colors duration-150 ease-snappy hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring";
            const zapIc = cloneIcon("[data-q-zap]");
            if (zapIc) nowBtn.append(zapIc);
            nowBtn.addEventListener("click", () => {
              queue.splice(idx, 1);
              runImmediately(item.text, `Interrupted active run and started: "${item.text}".`);
            });

            const delBtn = document.createElement("button");
            delBtn.type = "button";
            delBtn.setAttribute("aria-label", `Remove: ${item.text}`);
            delBtn.className =
              "inline-flex size-6 cursor-pointer items-center justify-center rounded-md text-muted-foreground transition-colors duration-150 ease-snappy hover:bg-destructive/14 hover:text-destructive focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring";
            const trashIc = cloneIcon("[data-q-trash]");
            if (trashIc) delBtn.append(trashIc);
            delBtn.addEventListener("click", () => {
              queue.splice(idx, 1);
              renderQueue();
              if (statusEl) statusEl.textContent = "Removed message from queue.";
            });

            actions.append(upBtn, downBtn, editBtn, nowBtn, delBtn);
            li.append(num, textSpan, actions);

            if (idx === 0) {
              const bar = document.createElement("span");
              bar.setAttribute("data-next-progress", "");
              bar.setAttribute("aria-hidden", "true");
              bar.style.width = `${pct}%`;
              bar.className =
                "pointer-events-none absolute bottom-0 left-0 h-0.5 bg-primary transition-[width] duration-300 ease-smooth";
              li.append(bar);
            }
          }

          frag.append(li);
        });

        listEl.replaceChildren(frag);
      };

      const queueFromComposer = () => {
        const text = input?.value.trim() ?? "";
        if (!text) return;
        queue.push({ id: `q-${counter++}`, text });
        if (input) input.value = "";
        renderQueue();
        syncDockButton();
        if (statusEl) statusEl.textContent = `Queued follow-up (${queue.length} waiting).`;
      };

      const sendNowFromComposer = () => {
        const text = input?.value.trim() ?? "";
        if (!text) return;
        if (input) input.value = "";
        runImmediately(text, `Sent immediately: "${text}".`);
      };

      dockAction?.addEventListener("click", () => {
        if ((input?.value.trim().length ?? 0) > 0) {
          queueFromComposer();
        } else {
          working = !working;
          renderAgent();
          if (statusEl) statusEl.textContent = working ? "Agent resumed." : "Agent paused.";
        }
      });

      clearBtn?.addEventListener("click", () => {
        queue = [];
        editingId = null;
        renderQueue();
        if (statusEl) statusEl.textContent = "Cleared all queued follow-ups.";
      });

      form?.addEventListener("submit", (ev) => {
        ev.preventDefault();
        queueFromComposer();
      });

      input?.addEventListener("input", syncDockButton);

      input?.addEventListener("keydown", (ev) => {
        if (ev.key === "Enter" && (ev.ctrlKey || ev.metaKey)) {
          ev.preventDefault();
          sendNowFromComposer();
        } else if (ev.key === "Enter") {
          ev.preventDefault();
          queueFromComposer();
        }
      });

      window.setInterval(() => {
        if (!working) return;
        elapsedSec += 1;
        if (elapsedSec % 5 === 0) {
          if (stepIndex < steps.length - 1) {
            stepIndex += 1;
          } else if (queue.length > 0) {
            const next = queue.shift();
            if (next) {
              runImmediately(next.text, `Finished previous run and started next queued message: "${next.text}".`);
              return;
            }
          } else {
            stepIndex = 0;
            elapsedSec = 1;
          }
        }
        renderAgent();
      }, 1000);

      renderAgent();
      renderQueue();
    });
  }

  initAiMessageQueue();
  document.addEventListener("astro:page-load", initAiMessageQueue);
</script>
```
