import { useRef, useState } from "react"; import { useTranslation } from "react-i18next"; import { FallbackResponseSources } from "@/components/ResponseSourceBadge"; import { AgentActivityCluster } from "@/components/thread/AgentActivityCluster"; import { ComposerUsagePopover, type ComposerRoundUsage } from "@/components/thread/ComposerUsagePopover"; import type { ContextSnapshot } from "@/lib/types"; import { ContextCompactionNotice } from "@/components/thread/ContextCompactionNotice"; import { GoalIsland } from "@/components/thread/GoalIsland"; import { ModelFallbackNotice } from "@/components/thread/ModelFallbackNotice"; import { SandboxNotice, type SandboxIssue } from "@/components/thread/SandboxNotice"; import { ModelPresetBadge, type ModelPresetOption } from "@/components/thread/ModelPresetBadge"; import { PromptNavigator } from "@/components/thread/PromptNavigator"; import { RecoveryNotice } from "@/components/thread/RecoveryNotice"; import { StreamErrorNotice } from "@/components/thread/StreamErrorNotice"; import { ThreadComposer } from "@/components/thread/ThreadComposer"; import { ThreadHeader } from "@/components/thread/ThreadHeader"; import { ThreadHistoryStatus } from "@/components/thread/ThreadHistoryStatus"; import { ThreadMessages } from "@/components/thread/ThreadMessages"; import { ThreadViewport, type ThreadViewportHandle } from "@/components/thread/ThreadViewport"; import { WorkspaceAccessMenu, WorkspaceProjectPicker } from "@/components/thread/WorkspaceControls"; import { WebSearchRun } from "@/components/thread/activity/WebSearchRun"; import { Button } from "@/components/ui/button"; import type { StreamError } from "@/lib/nanobot-client"; import { formatToolCallTrace } from "@/lib/tool-traces"; import type { RecoveryState, SlashCommand, ToolProgressEvent, UIContextCompaction, UIMessage, WorkspaceScopePayload, WorkspacesPayload } from "@/lib/types"; import { Sample, StatePicker, type ComponentExample } from "./example"; import { useGalleryTranslation } from "./i18n"; const createdAt = Date.UTC(2026, 0, 1, 12); const presets: ModelPresetOption[] = [ { name: "日常", provider: "openai", model: "gpt-4.1", contextWindowTokens: 1_047_576 }, { name: "推理", provider: "anthropic", model: "claude-sonnet-4", reasoningEffort: "high", contextWindowTokens: 200_000 }, ]; const rounds: ComposerRoundUsage[] = [ { inputTokens: 8_200, cachedTokens: 6_000, generationMs: 3_100 }, { inputTokens: 12_000, cachedTokens: 8_200, generationMs: 5_400 }, { inputTokens: 18_500, cachedTokens: 12_000, generationMs: 7_200 }, ]; const commands: SlashCommand[] = [ { command: "/status", title: "previews.composer.statusCommand", description: "previews.composer.statusDescription", icon: "activity", lifecycle: "side_channel", acceptsArgs: false }, { command: "/compact", title: "previews.composer.compactCommand", description: "previews.composer.compactDescription", icon: "archive", lifecycle: "finalize_active_turn", acceptsArgs: false }, { command: "/help", title: "previews.composer.helpCommand", description: "previews.composer.helpDescription", icon: "circle-help", lifecycle: "side_channel", acceptsArgs: false }, ]; const projectScope: WorkspaceScopePayload = { project_path: "D:\\Projects\\nanobot", project_name: "nanobot", access_mode: "restricted" }; const workspaceCatalog: WorkspacesPayload = { schema_version: 1, default_access_mode: "default", default_scope: projectScope, recent_projects: [{ name: "nanobot", path: projectScope.project_path }, { name: "design-system", path: "D:\\Projects\\design-system" }], favorite_projects: [{ name: "nanobot", path: projectScope.project_path }], controls: { can_change_project: true }, }; const loadExampleProjects = () => Promise.resolve(workspaceCatalog); const prompts: UIMessage[] = [ { id: "gallery-prompt-1", role: "user", content: "整理组件的输入、状态和回调。", createdAt }, { id: "gallery-answer-1", role: "assistant", content: "先从 **模型选择** 和 **消息输入** 开始。\n\n- 调用方提供数据\n- 组件显示状态\n- 回调更新当前选择", latencyMs: 4_200, createdAt: createdAt + 1_000 }, { id: "gallery-prompt-2", role: "user", content: "给消息列表加入代码和引用示例。", createdAt: createdAt + 60_000 }, { id: "gallery-answer-2", role: "assistant", content: "代码块支持复制:\n\n```tsx\n\n```\n\n选中这段回复中的文字,可以试用引用操作。", latencyMs: 5_200, createdAt: createdAt + 61_000 }, { id: "gallery-prompt-3", role: "user", content: "长会话如何跳转到之前的问题?", createdAt: createdAt + 120_000 }, { id: "gallery-answer-3", role: "assistant", content: "打开问题导航后,可以搜索问题并跳转。\n\n滚动区域左侧的标记也对应每个问题。鼠标停留时会显示问题和回复摘要。", latencyMs: 2_600, createdAt: createdAt + 121_000 }, ]; const longConversation: UIMessage[] = Array.from({ length: 8 }, (_, index) => [ { id: `gallery-long-prompt-${index}`, role: "user" as const, content: `问题 ${index + 1}:${["模型配置", "工作目录", "消息排版", "工具活动"][index % 4]}如何展示?`, createdAt: createdAt + index * 60_000 }, { id: `gallery-long-answer-${index}`, role: "assistant" as const, content: "组件接收已有状态,并把操作交给调用方。\n\n- 可以查看历史问题\n- 可以复制回复内容\n- 可以在回复后创建会话分支\n\n这段示例内容使预览产生真实滚动距离,便于体验问题标记和返回底部按钮。", latencyMs: 3_200, createdAt: createdAt + index * 60_000 + 1_000 }, ]).flat(); function ComposerPreview() { const { t } = useGalleryTranslation(); const [mode, setMode] = useState<"thread" | "hero" | "streaming" | "disabled">("thread"); const [preset, setPreset] = useState(presets[0].name); const [sent, setSent] = useState<{ kind: "sent"; content: string; attachments: number } | { kind: "stopped" } | null>(null); const [quoted, setQuoted] = useState(null); const selected = presets.find((option) => option.name === preset) ?? presets[0]; return
{(renderContextUsage) => ({ ...command, title: t(command.title), description: t(command.description) }))} renderContextUsage={renderContextUsage} workspaceScope={projectScope} workspaceControlsHidden quotedContext={quoted} onQuotedContextChange={setQuoted} onStop={() => { setMode("thread"); setSent({ kind: "stopped" }); }} onSend={(content, attachments) => { setSent({ kind: "sent", content, attachments: attachments?.length ?? 0 }); return true; }} />}

{sent?.kind === "stopped" ? t("previews.composer.stopped") : sent ? t("previews.composer.sent", { content: sent.content, attachments: sent.attachments ? t("previews.composer.attachments", { amount: sent.attachments }) : "" }) : t("previews.composer.hint")}

; } function GoalPreview() { const { t } = useGalleryTranslation(); const [status, setStatus] = useState<"active" | "blocked">("active"); return
; } function ModelPresetPreview() { const { t } = useTranslation(); const { t: g } = useGalleryTranslation(); const [preset, setPreset] = useState(presets[0].name); const [mode, setMode] = useState<"ready" | "setup" | "hero">("ready"); const [action, setAction] = useState(""); const selected = presets.find((option) => option.name === preset) ?? presets[0]; return
setAction("previews.modelPreset.manage")} onClick={() => setAction("previews.modelPreset.settings")} />

{action ? g(action) : g("previews.modelPreset.hint", { preset })}

; } const contextSnapshots: ContextSnapshot[] = [0, 1, 2].map((round) => ({ id: `context-example-${round}`, contextWindowTokens: 128000, usage: { prompt_tokens: 28000 + round * 7300, context_tokens: 28000 + round * 7300, cached_tokens: 20000 + round * 7000, generation_ms: 8200 }, graph: { nodes: [ { path: "/workspace/MEMORY.md", name: "MEMORY.md", state: "loaded", tokens: 2100 }, { path: "/workspace/SOUL.md", name: "SOUL.md", state: "loaded", tokens: 380 }, { path: "/workspace/AGENTS.md", name: "AGENTS.md", state: "loaded", tokens: 1400 }, { path: "/workspace/skills/nanobot-document/SKILL.md", name: "nanobot-document", state: "loaded", tokens: 550 }, { path: "/workspace/skills/nanobot-document/references/architecture.md", name: "architecture.md", state: round ? "loaded" : "discovered", tokens: round * 1600 }, { path: "/workspace/skills/nanobot-document/references/configuration.md", name: "configuration.md", state: "discovered", tokens: 0 }, ], edges: ["architecture.md", "configuration.md"].map((name) => ({ source: "/workspace/skills/nanobot-document/SKILL.md", target: `/workspace/skills/nanobot-document/references/${name}` })), }, })); function UsagePreview() { const { t } = useGalleryTranslation(); const [mode, setMode] = useState<"normal" | "caution" | "critical" | "rounds_only">("normal"); const tokens = mode === "critical" ? 192_000 : mode === "caution" ? 162_000 : 18_500; return

{t("previews.usage.hint")}

; } function WorkspacePreview() { const { t } = useTranslation(); const { t: g } = useGalleryTranslation(); const [scope, setScope] = useState(projectScope); const [mode, setMode] = useState<"ready" | "disabled">("ready"); const hintBoundaryRef = useRef(null); return

{scope.project_path} · {t("thread.composer.workspace.full")}: {t(scope.access_mode === "full" ? "settings.values.on" : "settings.values.off")}

; } function NavigatorPreview() { const { t } = useGalleryTranslation(); const [selected, setSelected] = useState(""); return
{t("previews.navigator.hint")}

{prompts.find((message) => message.id === selected)?.content ?? t("previews.navigator.empty")}

; } function HeaderPreview() { const { t } = useTranslation(); const { t: g } = useGalleryTranslation(); const [theme, setTheme] = useState<"light" | "dark">("light"); const [temporary, setTemporary] = useState(false); const [action, setAction] = useState<{ kind: "sidebar" } | { kind: "jump"; id: string } | null>(null); return
setTheme((value) => value === "light" ? "dark" : "light")} onToggleSidebar={() => setAction({ kind: "sidebar" })} temporaryChatEnabled={temporary} onTemporaryChatEnabledChange={setTemporary} promptNavigatorAction={ setAction({ kind: "jump", id })} />} />

{action?.kind === "jump" ? g("previews.header.jump", { id: action.id }) : g(action ? "previews.header.sidebar" : "previews.header.hint")} · {t(`settings.values.${theme}`)} · {g(temporary ? "previews.header.temporary" : "previews.header.regular")}

; } function MessagesPreview() { const { t } = useGalleryTranslation(); const [quoted, setQuoted] = useState(""); const [fork, setFork] = useState(null); return

{quoted ? t("previews.messages.quoted", { text: quoted }) : fork !== null ? t("previews.messages.forked", { index: fork + 1 }) : t("previews.messages.hint")}

; } function ViewportPreview() { const { t } = useGalleryTranslation(); const viewport = useRef(null); const [mode, setMode] = useState<"history" | "empty">("history"); const [fork, setFork] = useState(null); return
viewport.current?.jumpToUserPrompt(id)} />
{t("previews.viewport.empty")}

} />

{fork !== null ? t("previews.messages.forked", { index: fork + 1 }) : t("previews.viewport.hint")}

; } function HistoryPreview() { const { t } = useGalleryTranslation(); const [mode, setMode] = useState<"loading" | "error" | "exhausted">("loading"); const [retries, setRetries] = useState(0); return
{ setRetries((value) => value + 1); setMode("loading"); }} />

{t("previews.history.retries", { amount: retries })}

; } function RecoveryPreview() { const { t } = useGalleryTranslation(); const [mode, setMode] = useState<"awaiting_user" | "resuming" | "failed" | "unavailable">("awaiting_user"); const [action, setAction] = useState(""); const [visible, setVisible] = useState(true); const state: RecoveryState = { recovery_id: `gallery-recovery-${mode}`, status: mode === "unavailable" ? "failed" : mode, can_continue: mode !== "unavailable" }; return
{ setMode(value); setVisible(true); setAction(""); }} /> {visible ? { setVisible(false); setAction("previews.recovery.continued"); return Promise.resolve(); }} onDismiss={() => { setVisible(false); setAction("previews.recovery.dismissed"); return Promise.resolve(); }} /> : null}

{t(action || "previews.recovery.hint")}

; } function SandboxPreview() { const { t } = useGalleryTranslation(); const [backend, setBackend] = useState<"bwrap" | "seatbelt" | null>("bwrap"); const gateway = backend === "bwrap" ? "Linux / fnOS" : backend === "seatbelt" ? "macOS" : t("previews.sandbox.unknownGateway"); const [issue, setIssue] = useState("missing"); const [dismissed, setDismissed] = useState(false); const [opened, setOpened] = useState(false); return
setBackend(value === "Linux / fnOS" ? "bwrap" : value === "macOS" ? "seatbelt" : null)} />
{(["missing", "permissions", "startup"] as const).map((value) => )}
{!dismissed ? setDismissed(true)} onOpenSettings={() => setOpened(true)} /> : null} false} onStop={() => {}} />

{t(`previews.sandbox.${opened ? "settingsAction" : "hint"}`)}

; } function FallbackPreview() { const { t } = useGalleryTranslation(); const [mode, setMode] = useState<"fallback" | "reauth">("fallback"); const [dismissed, setDismissed] = useState(false); const [action, setAction] = useState(""); return
{ setMode(value); setDismissed(false); }} /> {!dismissed ? setDismissed(true)} onOpenSettings={() => setAction("previews.modelPreset.settings")} /> : null}

{t(action || "previews.fallback.hint")}

; } function CompactionPreview() { const { t } = useGalleryTranslation(); const [phase, setPhase] = useState("started"); return <> ; } const errors: Record = { message_too_big: { kind: "message_too_big" }, workspace_scope_rejected: { kind: "workspace_scope_rejected" }, turn_rejected: { kind: "turn_rejected", chatId: "gallery", turnId: "gallery-turn" }, model_request_failed: { kind: "model_request_failed", chatId: "gallery", errorKind: "rate_limit", attempts: 3 }, }; function ErrorPreview() { const { t } = useGalleryTranslation(); const [kind, setKind] = useState("model_request_failed"); const [dismissed, setDismissed] = useState(false); return
{ setKind(value); setDismissed(false); }} /> {!dismissed ? setDismissed(true)} /> : null}
; } function ClusterPreview() { const { t } = useGalleryTranslation(); const [status, setStatus] = useState<"running" | "done" | "error">("done"); const [expanded, setExpanded] = useState(true); const [startedAt] = useState(Date.now); const event: ToolProgressEvent = { call_id: "gallery-read", name: "read_file", arguments: { path: "webui/src/components/thread/ThreadComposer.tsx" }, phase: status === "running" ? "start" : status === "error" ? "error" : "end", error: status === "error" ? t("previews.cluster.error") : undefined }; const trace = formatToolCallTrace(event) ?? "read_file()"; const messages: UIMessage[] = [ { id: "gallery-reasoning", role: "assistant", content: "", reasoning: "先核对组件接口,再查看消息和模型控件的组合方式。", reasoningStreaming: status === "running", isStreaming: status === "running", createdAt: startedAt }, { id: "gallery-tool", role: "tool", kind: "trace", content: trace, traces: [trace], toolEvents: [event], createdAt: startedAt + 1_000 }, ]; return <> ; } function SearchActivityPreview() { const { t } = useGalleryTranslation(); const [status, setStatus] = useState<"running" | "done" | "error">("done"); const [target, setTarget] = useState<"web" | "x">("web"); return <> ; } function ResponseSourcesPreview() { const { t } = useGalleryTranslation(); return ; } const components = "webui/src/components/"; export const conversationExamples: ComponentExample[] = [ { title: "previews.goal.title", files: ["thread/GoalIsland"], Preview: GoalPreview, description: "previews.goal.description", options: "previews.goal.options", code: '' }, { title: "previews.composer.title", files: ["thread/ThreadComposer"], Preview: ComposerPreview, description: "previews.composer.description", options: "previews.composer.options", code: '' }, { title: "previews.modelPreset.title", files: ["thread/ModelPresetBadge"], Preview: ModelPresetPreview, description: "previews.modelPreset.description", options: "previews.modelPreset.options", code: '' }, { title: "previews.usage.title", files: ["thread/ComposerUsagePopover"], Preview: UsagePreview, description: "previews.usage.description", options: "previews.usage.options", code: '' }, { title: "previews.workspace.title", files: ["thread/WorkspaceControls"], Preview: WorkspacePreview, description: "previews.workspace.description", options: "previews.workspace.options", code: '\n' }, { title: "previews.navigator.title", files: ["thread/PromptNavigator"], Preview: NavigatorPreview, description: "previews.navigator.description", options: "previews.navigator.options", code: '' }, { title: "previews.header.title", files: ["thread/ThreadHeader"], Preview: HeaderPreview, description: "previews.header.description", options: "previews.header.options", code: '' }, { title: "previews.messages.title", files: ["thread/ThreadMessages", "thread/AssistantSelectionAction"], Preview: MessagesPreview, description: "previews.messages.description", options: "previews.messages.options", code: '' }, { title: "previews.viewport.title", files: ["thread/ThreadViewport", "thread/PromptRail"], Preview: ViewportPreview, description: "previews.viewport.description", options: "previews.viewport.options", code: '
' }, { title: "previews.history.title", files: ["thread/ThreadHistoryStatus"], Preview: HistoryPreview, description: "previews.history.description", options: "previews.history.options", code: '' }, { title: "previews.recovery.title", files: ["thread/RecoveryNotice"], Preview: RecoveryPreview, description: "previews.recovery.description", options: "previews.recovery.options", code: '' }, { title: "previews.fallback.title", files: ["thread/ModelFallbackNotice"], Preview: FallbackPreview, description: "previews.fallback.description", options: "previews.fallback.options", code: '' }, { title: "previews.sandbox.title", files: ["thread/SandboxNotice"], Preview: SandboxPreview, description: "previews.sandbox.description", options: "previews.sandbox.options", code: '' }, { title: "previews.compaction.title", files: ["thread/ContextCompactionNotice"], Preview: CompactionPreview, description: "previews.compaction.description", options: "previews.compaction.options", code: '' }, { title: "previews.streamError.title", files: ["thread/StreamErrorNotice"], Preview: ErrorPreview, description: "previews.streamError.description", options: "previews.streamError.options", code: '' }, { title: "previews.cluster.title", files: ["thread/AgentActivityCluster"], Preview: ClusterPreview, description: "previews.cluster.description", options: "previews.cluster.options", code: '' }, { title: "previews.search.title", files: ["thread/activity/WebSearchRun", "thread/activity/WebActivityRow"], Preview: SearchActivityPreview, description: "previews.search.description", options: "previews.search.options", code: '' }, { title: "previews.responseSources.title", files: ["ResponseSourceBadge"], Preview: ResponseSourcesPreview, description: "previews.responseSources.description", options: "previews.responseSources.options", code: '' }, ].map((example) => ({ ...example, files: example.files.map((file) => `${components}${file}.tsx`) }));