{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "app-assistant-thread",
  "type": "registry:block",
  "title": "App, assistant thread",
  "description": "A conversation with an assistant: drawn as the agent chat kit draws it (the person in a bubble on the right, the reply as plain text, no avatars or visible names), optional code, sources and a note under a turn (a staff correction), and four states. A log region; each turn is named by its speaker for screen readers. The state, height and fixed scroll options are props.",
  "categories": [
    "app"
  ],
  "dependencies": [
    "lucide-react@^1.49.0",
    "zod@^4.6.5"
  ],
  "registryDependencies": [
    "https://ui.klarhimmel.com/r/agent-chat.json",
    "https://ui.klarhimmel.com/r/block-kit.json",
    "https://ui.klarhimmel.com/r/button.json",
    "https://ui.klarhimmel.com/r/editing.json",
    "https://ui.klarhimmel.com/r/utils.json"
  ],
  "files": [
    {
      "path": "src/blocks/app-assistant-thread/spec.ts",
      "type": "registry:file",
      "target": "components/klarhimmel/blocks/app-assistant-thread/spec.ts",
      "content": "import { z } from 'zod';\nimport { defineSpec, link, t, req } from '../_shared/schema';\n\nconst schema = z.object({\n  label: req(60),\n  state: z.enum(['idle', 'streaming', 'error', 'empty']),\n  height: z.enum(['auto', 'fixed']),\n  userName: t(30),\n  assistantName: t(30),\n  /** A reply's `sources`: the pages it was answered from, as small links under it. `note`: one quiet line under the turn, e.g. that staff corrected this answer. */\n  turns: z.array(z.object({ role: z.enum(['user', 'assistant']), text: t(4000), code: t(20000).optional(), sources: z.array(link).max(4).optional(), note: t(160).optional() })).max(50),\n  /** Names the sources list for screen readers; \"Sources\" when empty. */\n  sourcesLabel: t(30).optional(),\n  codeLabel: t(30),\n  typing: t(40),\n  error: z.object({ title: t(60), message: t(160), retry: t(20) }),\n  empty: z.object({ title: t(60), hint: t(160), suggestions: z.array(t(80)).max(3) }),\n});\n\nexport const spec = defineSpec({\n  type: 'app-assistant-thread',\n  aliases: ['app/assistant-thread'],\n  name: 'App, assistant thread',\n  category: 'app',\n  role: 'body',\n  description: 'A conversation with an assistant: drawn as the agent chat kit draws it (the person in a bubble on the right, the reply as plain text, no avatars or visible names), optional code, sources and a note under a turn (a staff correction), and four states. A log region; each turn is named by its speaker for screen readers. The state, height and fixed scroll options are props.',\n  schema,\n  defaults: {\n    \"label\": \"Name who the conversation is with\",\n    \"state\": \"idle\",\n    \"height\": \"auto\",\n    \"codeLabel\": \"Code\",\n    \"userName\": \"You\",\n    \"assistantName\": \"Assistant\",\n    \"turns\": [\n      {\n        \"role\": \"user\",\n        \"text\": \"Write what a person asks the assistant.\"\n      },\n      {\n        \"role\": \"assistant\",\n        \"text\": \"Say what the assistant found, in a sentence or two.\\nAdd a second line with the detail that matters most.\",\n        \"code\": \"First line of the example\\nSecond line of the example\",\n        \"sources\": [\n          {\n            \"label\": \"Name a source\",\n            \"href\": \"#rooms\"\n          }\n        ]\n      },\n      {\n        \"role\": \"user\",\n        \"text\": \"Write the follow-up the person sends.\"\n      }\n    ],\n    \"typing\": \"Writing…\",\n    \"error\": {\n      \"title\": \"Say the answer is missing\",\n      \"message\": \"Say what went wrong and that the message is saved.\",\n      \"retry\": \"Try again\"\n    },\n    \"empty\": {\n      \"title\": \"Say what a person can ask about\",\n      \"hint\": \"Say what the assistant can do for a person, and say when it asks before changing anything.\",\n      \"suggestions\": [\n        \"Suggest a first question\",\n        \"Suggest a second request\",\n        \"Suggest a third thing to do\"\n      ]\n    }\n  },\n});\n"
    },
    {
      "path": "src/blocks/app-assistant-thread/index.tsx",
      "type": "registry:file",
      "target": "components/klarhimmel/blocks/app-assistant-thread/index.tsx",
      "content": "import { useEffect, useId, useRef, type ReactNode } from 'react';\nimport { AlertTriangle, Link2 } from 'lucide-react';\nimport { ChatLoader, ChatStart } from '../../ui/agent-chat';\nimport { Text, withHeadingLevel } from '../../editing';\nimport { cn } from '../../lib/utils';\nimport { Button, safeHref } from '../../ui/button';\nimport { Container, Gate, Named, Section, useEditing } from '../_shared/kit';\nimport { spec } from './spec';\nimport type { BlockProps } from '../types';\nimport type { z } from 'zod';\n\nexport { spec };\ntype Props = z.infer<typeof spec.schema>;\n\n/** A control that has nothing wired to it stays in the tab order but says it does nothing. */\nconst dead = { 'aria-disabled': true, className: 'opacity-60' } as const;\n/** Long unbroken text (a URL, a path) wraps instead of widening the turn. */\nconst WRAP = '[overflow-wrap:anywhere]';\n\nexport interface ThreadActions {\n  onRetry?: () => void;\n  onSuggest?: (text: string) => void;\n}\n\n/**\n * The thread. Only turns live in the `role=log` region, so a screen reader hears each new turn once. The error alert, the\n * `children` (tool calls, approvals: each has its own status) and `tail` (a second log, for turns that follow them) sit\n * outside it. With `height: 'fixed'` the log scrolls inside the thread, is keyboard-focusable, and follows the latest turn.\n */\nexport function Thread({ props, children, tail, onRetry, onSuggest }: { props: Props; children?: ReactNode; tail?: ReactNode } & ThreadActions) {\n  const id = useId();\n  const editing = useEditing();\n  const is = (state: Props['state']) => props.state === state || editing;\n  const fixed = props.height === 'fixed';\n  const showEmpty = is('empty') || (props.turns.length === 0 && props.state === 'idle');\n  const showTurns = props.state !== 'empty' || editing;\n  const names = { user: props.userName, assistant: props.assistantName };\n  const log = useRef<HTMLDivElement>(null);\n  const last = props.turns.length + (props.state === 'streaming' ? 1 : 0);\n  useEffect(() => {\n    if (fixed && log.current) log.current.scrollTop = log.current.scrollHeight;\n  }, [fixed, last]);\n  return (\n    <div className=\"flex min-w-0 flex-col gap-5 rounded-kh-xl border border-kh-line bg-kh-surface p-5 shadow-kh-1 @xl:p-6\">\n      <Named as=\"h2\" id={`${id}-l`} className=\"sr-only\">\n        <Text path={['label']} value={props.label} as=\"span\" />\n      </Named>\n      {showEmpty && (\n        // The kit's empty chat (ChatStart): a centred greeting, the hint where the composer goes, the suggestions as quiet rows.\n        <ChatStart\n          className=\"py-8\"\n          greeting={<Text path={['empty', 'title']} value={props.empty.title} as=\"span\" />}\n          suggestions={props.empty.suggestions.filter((x) => x || editing).map((x) => ({ label: x, onSelect: () => onSuggest?.(x) }))}\n        >\n          <Text path={['empty', 'hint']} value={props.empty.hint} as=\"p\" className=\"mx-auto max-w-kh-narrow text-center text-kh-small text-kh-muted\" />\n          {editing && props.empty.suggestions.map((x, i) => (\n            <Text key={i} path={['empty', 'suggestions', i]} value={x} as=\"p\" className=\"mt-2 text-kh-caption text-kh-muted\" />\n          ))}\n        </ChatStart>\n      )}\n      {showTurns && (\n        <div\n          ref={log}\n          role=\"log\"\n          aria-labelledby={`${id}-l`}\n          aria-live=\"polite\"\n          aria-relevant=\"additions\"\n          aria-busy={props.state === 'streaming'}\n          tabIndex={fixed ? 0 : undefined}\n          className={cn('flex min-w-0 flex-col gap-5 empty:hidden', fixed && 'max-h-[28rem] overflow-y-auto pr-1 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-(--kh-focus)')}\n        >\n          {props.turns.map((m, i) => (\n            <Turn key={i} role={m.role} name={names[m.role]} namePath={m.role === 'user' ? ['userName'] : ['assistantName']}>\n              <Text path={['turns', i, 'text']} value={m.text} as=\"p\" className={cn('whitespace-pre-line', WRAP)} />\n              {m.code !== undefined && m.code !== '' && (\n                <>\n                  {editing && <Text path={['codeLabel']} value={props.codeLabel} as=\"p\" className=\"mt-2 text-kh-caption text-kh-muted\" />}\n                  <CodeBlock label={props.codeLabel}>\n                    <Text path={['turns', i, 'code']} value={m.code} as=\"code\" />\n                  </CodeBlock>\n                </>\n              )}\n              {m.sources && m.sources.length > 0 && (\n                <ul aria-label={props.sourcesLabel || 'Sources'} className=\"mt-3 flex flex-wrap gap-2\">\n                  {m.sources.map((src, j) => (\n                    <Gate key={j} label={src.label}>\n                    <li>\n                      <a href={safeHref(src.href)} className=\"inline-flex min-h-8 items-center gap-1.5 rounded-kh-pill border border-kh-line px-3 text-kh-caption text-kh-muted transition-colors hover:text-kh-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-(--kh-focus)\">\n                        <Link2 aria-hidden strokeWidth={1.75} className=\"size-3.5\" />\n                        <Text path={['turns', i, 'sources', j, 'label']} value={src.label} as=\"span\" />\n                      </a>\n                    </li>\n                    </Gate>\n                  ))}\n                </ul>\n              )}\n              {(m.note || (editing && m.note !== undefined)) && <Text path={['turns', i, 'note']} value={m.note ?? ''} as=\"p\" className={cn('mt-2 text-kh-caption text-kh-muted', WRAP)} />}\n            </Turn>\n          ))}\n          {is('streaming') && (\n            <Turn role=\"assistant\" name={props.assistantName} namePath={['assistantName']}>\n              <ChatLoader label={props.typing} live={false} />\n              {editing && <Text path={['typing']} value={props.typing} as=\"p\" className=\"text-kh-caption text-kh-muted\" />}\n            </Turn>\n          )}\n        </div>\n      )}\n      {children}\n      {tail !== undefined && (\n        <div role=\"log\" aria-labelledby={`${id}-l`} aria-live=\"polite\" aria-relevant=\"additions\" className=\"flex min-w-0 flex-col gap-5 empty:sr-only\">\n          {tail}\n        </div>\n      )}\n      {is('error') && (\n        <div role=\"alert\" className=\"flex items-start gap-3 rounded-kh-lg border border-kh-danger bg-kh-canvas p-4\">\n          <AlertTriangle aria-hidden className=\"mt-0.5 size-5 shrink-0 text-kh-danger\" />\n          <div className=\"min-w-0 flex-1\">\n            <Text path={['error', 'title']} value={props.error.title} as=\"p\" className=\"text-kh-body font-semibold\" />\n            <Text path={['error', 'message']} value={props.error.message} as=\"p\" className={cn('mt-1 text-kh-small text-kh-muted', WRAP)} />\n            <Button variant=\"secondary\" size=\"sm\" className=\"mt-3\" {...(onRetry ? { onClick: onRetry } : dead)}>\n              <Text path={['error', 'retry']} value={props.error.retry} as=\"span\" />\n            </Button>\n          </div>\n        </div>\n      )}\n    </div>\n  );\n}\n\n/** Code in a turn: a labelled, keyboard-focusable scroll region so long lines can be reached without a mouse. */\nexport function CodeBlock({ label, children }: { label: string; children: ReactNode }) {\n  return (\n    <pre\n      tabIndex={0}\n      role=\"region\"\n      aria-label={label}\n      className=\"mt-2 max-h-64 overflow-auto rounded-kh bg-kh-surface-2 px-3 py-2.5 font-kh-mono text-kh-caption leading-relaxed text-kh-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-(--kh-focus)\"\n    >\n      {children}\n    </pre>\n  );\n}\n\n/**\n * One turn, drawn as the agent chat kit draws it (docs/agent-chat.md): the person's words in a bubble on the right, the reply as\n * plain text, no avatar and no visible name. The speaker's name stays the turn's accessible name, so a screen reader hears who talks;\n * the editor shows it so it can be changed.\n */\nexport function Turn({ role, name, namePath, children }: { role: 'user' | 'assistant'; name: string; namePath: (string | number)[]; children: ReactNode }) {\n  const id = useId();\n  const editing = useEditing();\n  const user = role === 'user';\n  return (\n    <article aria-labelledby={id} className={cn('flex min-w-0 flex-col gap-1', user && 'items-end')}>\n      <span id={id} className={editing ? 'text-kh-caption font-medium text-kh-muted' : 'sr-only'}>\n        <Text path={namePath} value={name} as=\"span\" />\n      </span>\n      <div className={cn('min-w-0 text-kh-body text-kh-ink', user ? 'max-w-[min(80%,36rem)] rounded-[1.5rem] bg-(--kh-bubble) px-5 py-3 leading-6' : 'max-w-full leading-7')}>{children}</div>\n    </article>\n  );\n}\n\nfunction AppAssistantThread({ props }: BlockProps<Props>) {\n  return (\n    <Section>\n      <Container width=\"narrow\">\n        <Thread props={props} />\n      </Container>\n    </Section>\n  );\n}\n\nexport default withHeadingLevel(AppAssistantThread);\n"
    }
  ]
}
