chore: mini-openclaw 初始版本

Next.js 前端 + FastAPI/LangChain 后端透明 agent平台
- 含 .gitignore, 敏感文件(sessions数据/.env/venv等)已排除
- 待后续添加 trajectory 自进化机制
This commit is contained in:
NathanAlex7
2026-09-01 16:40:10 +08:00
committed by NathanAlex7
parent 73796a6abd
commit 42ce992a0f
76 changed files with 14207 additions and 0 deletions
+180
View File
@@ -0,0 +1,180 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--bg-primary: #f5f5f7;
--text-primary: #1d1d1f;
--text-secondary: #86868b;
--accent: #002fa7;
--accent-light: #e8edff;
--accent-orange: #ff6723;
}
html, body { height: 100%; overflow: hidden; }
body {
color: var(--text-primary);
font-family: -apple-system, BlinkMacSystemFont, "SF Pro Display", "Helvetica Neue", "Segoe UI", Roboto, sans-serif;
-webkit-font-smoothing: antialiased;
}
/* ── Layered background ─────────────────────────────── */
.app-bg {
background:
radial-gradient(ellipse 80% 50% at 50% -10%, rgba(0, 47, 167, 0.05) 0%, transparent 60%),
radial-gradient(ellipse 50% 40% at 100% 100%, rgba(255, 103, 35, 0.03) 0%, transparent 50%),
linear-gradient(180deg, #f8f8fa 0%, #f0f0f3 100%);
}
/* ── Glass variants ─────────────────────────────────── */
.glass-nav {
background: rgba(255,255,255,0.78);
backdrop-filter: blur(40px) saturate(180%);
-webkit-backdrop-filter: blur(40px) saturate(180%);
border-bottom: 1px solid rgba(0,0,0,0.06);
}
.glass-panel {
background: rgba(255,255,255,0.68);
backdrop-filter: blur(28px) saturate(160%);
-webkit-backdrop-filter: blur(28px) saturate(160%);
}
.glass-input {
background: rgba(255,255,255,0.72);
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
border: 1px solid rgba(0,0,0,0.06);
box-shadow: 0 1px 4px rgba(0,0,0,0.04);
}
/* ── Scrollbar ──────────────────────────────────────── */
::-webkit-scrollbar { width: 5px; height: 5px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: rgba(0,0,0,0.10); border-radius: 10px; }
::-webkit-scrollbar-thumb:hover { background: rgba(0,0,0,0.18); }
/* ── Scroll shadow overlay (top/bottom) ─────────────── */
.scroll-shadow {
position: relative;
}
.scroll-shadow::before,
.scroll-shadow::after {
content: '';
position: absolute; left: 0; right: 0; height: 24px;
pointer-events: none; z-index: 2;
}
.scroll-shadow::before {
top: 0;
background: linear-gradient(to bottom, rgba(245,245,247,0.8), transparent);
}
.scroll-shadow::after {
bottom: 0;
background: linear-gradient(to top, rgba(245,245,247,0.8), transparent);
}
/* ── Markdown ───────────────────────────────────────── */
.markdown-content h1 { font-size: 1.35em; font-weight: 700; margin: 0.5em 0 0.3em; }
.markdown-content h2 { font-size: 1.15em; font-weight: 600; margin: 0.4em 0 0.3em; }
.markdown-content h3 { font-size: 1.05em; font-weight: 600; margin: 0.3em 0 0.2em; }
.markdown-content p { margin: 0.35em 0; line-height: 1.65; color: #333; }
.markdown-content ul, .markdown-content ol { padding-left: 1.5em; margin: 0.35em 0; }
.markdown-content li { margin: 0.1em 0; line-height: 1.6; }
.markdown-content code {
background: rgba(0,47,167,0.06); padding: 0.1em 0.35em; border-radius: 4px;
font-size: 0.87em; font-family: "SF Mono","JetBrains Mono","Fira Code",Consolas,monospace;
}
.markdown-content pre {
background: #1a1a2e; color: #d4d4e8; padding: 0.85em 1em; border-radius: 10px;
overflow-x: auto; margin: 0.5em 0; font-size: 0.87em;
box-shadow: 0 2px 8px rgba(0,0,0,0.10);
}
.markdown-content pre code { background: none; padding: 0; color: inherit; font-size: 1em; }
.markdown-content blockquote {
border-left: 3px solid var(--accent); padding-left: 1em; color: var(--text-secondary);
margin: 0.5em 0; font-style: italic;
}
/* ── Animations ─────────────────────────────────────── */
@keyframes fadeIn {
from { opacity: 0; transform: translateY(4px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes fadeInScale {
from { opacity: 0; transform: scale(0.97); }
to { opacity: 1; transform: scale(1); }
}
.animate-fade-in { animation: fadeIn 0.2s ease-out; }
.animate-fade-in-scale { animation: fadeInScale 0.2s ease-out; }
@keyframes pulse-dot {
0%, 100% { opacity: 0.2; transform: scale(0.8); }
50% { opacity: 1; transform: scale(1); }
}
.typing-dot { animation: pulse-dot 1.4s ease-in-out infinite; }
.typing-dot:nth-child(2) { animation-delay: 0.2s; }
.typing-dot:nth-child(3) { animation-delay: 0.4s; }
/* ── Resize Handle ──────────────────────────────────── */
.resize-handle {
width: 5px;
cursor: col-resize;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
position: relative;
z-index: 10;
}
.resize-handle:hover .resize-handle-line,
.resize-handle:active .resize-handle-line {
opacity: 1;
}
.resize-handle-line {
width: 2px;
height: 32px;
border-radius: 1px;
background: rgba(0,0,0,0.12);
opacity: 0;
transition: opacity 0.15s ease;
}
/* ── Panel transitions ──────────────────────────────── */
.panel-transition {
transition: width 0.25s cubic-bezier(0.4, 0, 0.2, 1);
}
/* ── Raw Message Viewer ─────────────────────────────── */
.raw-message-viewer {
font-family: "SF Mono","JetBrains Mono","Fira Code",Consolas,monospace;
font-size: 11px;
line-height: 1.5;
}
.raw-message-viewer .msg-system {
color: #86868b;
}
.raw-message-viewer .msg-user {
color: #002fa7;
}
.raw-message-viewer .msg-assistant {
color: #16a34a;
}
.raw-message-viewer .msg-role {
font-weight: 600;
font-size: 10px;
text-transform: uppercase;
letter-spacing: 0.05em;
margin-bottom: 2px;
}
.raw-message-viewer .msg-content {
white-space: pre-wrap;
word-break: break-word;
padding: 4px 8px;
border-radius: 6px;
background: rgba(0,0,0,0.02);
margin-bottom: 8px;
max-height: 200px;
overflow-y: auto;
}
+19
View File
@@ -0,0 +1,19 @@
import type { Metadata } from "next";
import "./globals.css";
export const metadata: Metadata = {
title: "mini OpenClaw",
description: "A lightweight, transparent AI Agent system",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="zh-CN">
<body className="antialiased">{children}</body>
</html>
);
}
+90
View File
@@ -0,0 +1,90 @@
"use client";
import { useCallback } from "react";
import { AppProvider, useApp } from "@/lib/store";
import Navbar from "@/components/layout/Navbar";
import Sidebar from "@/components/layout/Sidebar";
import ChatPanel from "@/components/chat/ChatPanel";
import InspectorPanel from "@/components/editor/InspectorPanel";
import ResizeHandle from "@/components/layout/ResizeHandle";
const MIN_SIDEBAR = 200;
const MIN_INSPECTOR = 280;
const MIN_CHAT = 360;
function MainLayout() {
const {
sidebarOpen,
inspectorOpen,
sidebarWidth,
setSidebarWidth,
inspectorWidth,
setInspectorWidth,
} = useApp();
const handleSidebarResize = useCallback(
(delta: number) => {
setSidebarWidth((prev: number) => Math.max(MIN_SIDEBAR, prev + delta));
},
[setSidebarWidth]
);
const handleInspectorResize = useCallback(
(delta: number) => {
setInspectorWidth((prev: number) => Math.max(MIN_INSPECTOR, prev + delta));
},
[setInspectorWidth]
);
return (
<div className="h-screen flex flex-col app-bg">
<Navbar />
{/* Content area — flexbox layout with resizable panels */}
<div className="flex-1 flex overflow-hidden">
{/* Left sidebar */}
<div
className="glass-panel border-r border-black/[0.06] shrink-0 panel-transition overflow-hidden"
style={{ width: sidebarOpen ? sidebarWidth : 0 }}
>
<div style={{ width: sidebarWidth, minWidth: MIN_SIDEBAR }} className="h-full">
<Sidebar />
</div>
</div>
{/* Left resize handle */}
{sidebarOpen && (
<ResizeHandle onResize={handleSidebarResize} direction="left" />
)}
{/* Chat — fills remaining space */}
<div className="flex-1 overflow-hidden" style={{ minWidth: MIN_CHAT }}>
<ChatPanel />
</div>
{/* Right resize handle */}
{inspectorOpen && (
<ResizeHandle onResize={handleInspectorResize} direction="right" />
)}
{/* Right inspector */}
<div
className="glass-panel border-l border-black/[0.06] shrink-0 panel-transition overflow-hidden"
style={{ width: inspectorOpen ? inspectorWidth : 0 }}
>
<div style={{ width: inspectorWidth, minWidth: MIN_INSPECTOR }} className="h-full">
<InspectorPanel />
</div>
</div>
</div>
</div>
);
}
export default function Home() {
return (
<AppProvider>
<MainLayout />
</AppProvider>
);
}
+54
View File
@@ -0,0 +1,54 @@
"use client";
import { useState, useRef, useCallback } from "react";
import { ArrowUp, Loader2 } from "lucide-react";
import { useApp } from "@/lib/store";
export default function ChatInput() {
const [text, setText] = useState("");
const { sendMessage, isStreaming, isCompressing } = useApp();
const textareaRef = useRef<HTMLTextAreaElement>(null);
const disabled = isStreaming || isCompressing;
const handleSubmit = useCallback(() => {
if (!text.trim() || disabled) return;
sendMessage(text.trim());
setText("");
if (textareaRef.current) textareaRef.current.style.height = "auto";
}, [text, disabled, sendMessage]);
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); handleSubmit(); }
};
const handleInput = () => {
const el = textareaRef.current;
if (el) { el.style.height = "auto"; el.style.height = Math.min(el.scrollHeight, 160) + "px"; }
};
return (
<div className="p-4 pb-5">
<div className="glass-input rounded-2xl flex items-end gap-2 px-4 py-2.5 max-w-2xl mx-auto hover:shadow-md transition-shadow">
<textarea
ref={textareaRef}
value={text}
onChange={(e) => { setText(e.target.value); handleInput(); }}
onKeyDown={handleKeyDown}
placeholder="输入消息..."
rows={1}
className="flex-1 resize-none bg-transparent text-[14px] outline-none placeholder:text-gray-400 max-h-40 py-1 leading-relaxed"
/>
<button
onClick={handleSubmit}
disabled={!text.trim() || disabled}
className="shrink-0 w-8 h-8 flex items-center justify-center rounded-xl bg-[#002fa7] text-white disabled:opacity-25 hover:bg-[#001f7a] transition-all active:scale-95"
>
{disabled ? <Loader2 className="w-4 h-4 animate-spin" /> : <ArrowUp className="w-4 h-4" />}
</button>
</div>
<p className="text-center text-[10px] text-gray-400/70 mt-2">
Powered by DeepSeek · mini OpenClaw v0.1
</p>
</div>
);
}
+125
View File
@@ -0,0 +1,125 @@
"use client";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { User, AlertTriangle, Key } from "lucide-react";
import type { ChatMessage as ChatMessageType } from "@/lib/store";
import ThoughtChain from "./ThoughtChain";
import RetrievalCard from "./RetrievalCard";
interface Props {
message: ChatMessageType;
}
function formatTime(ts: number): string {
const d = new Date(ts);
return d.toLocaleTimeString("zh-CN", { hour: "2-digit", minute: "2-digit" });
}
/** Detect 401 / API key errors */
function isAuthError(content: string): boolean {
return /401|authentication.?fail|invalid.*api.?key|api.?key.*invalid/i.test(content);
}
export default function ChatMessage({ message }: Props) {
const isUser = message.role === "user";
const hasAuthError = !isUser && isAuthError(message.content);
return (
<div className="animate-fade-in px-4 py-1.5">
<div className="max-w-2xl mx-auto">
{/* User message — right-aligned bubble */}
{isUser ? (
<div className="flex justify-end gap-2">
<div>
<div className="bg-[#002fa7] text-white px-4 py-2.5 rounded-2xl rounded-tr-md text-[14px] leading-relaxed shadow-sm">
{message.content}
</div>
<div className="text-[10px] text-gray-400 mt-1 text-right pr-1">
{formatTime(message.timestamp)}
</div>
</div>
<div className="shrink-0 w-7 h-7 rounded-full bg-gray-200 flex items-center justify-center mt-0.5">
<User className="w-3.5 h-3.5 text-gray-500" />
</div>
</div>
) : (
/* Assistant message — left-aligned */
<div className="flex gap-2.5">
<div className="shrink-0 w-7 h-7 rounded-full bg-gradient-to-br from-[#002fa7] to-[#4070ff] flex items-center justify-center mt-0.5 shadow-sm">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none">
<path d="M12 2L2 7L12 12L22 7L12 2Z" fill="white" fillOpacity="0.9" />
<path d="M2 17L12 22L22 17" stroke="white" strokeOpacity="0.7" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
<path d="M2 12L12 17L22 12" stroke="white" strokeOpacity="0.85" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
</svg>
</div>
<div className="flex-1 min-w-0">
{/* Tool calls */}
{message.toolCalls && message.toolCalls.length > 0 && (
<ThoughtChain toolCalls={message.toolCalls} />
)}
{/* Auth error alert */}
{hasAuthError ? (
<AuthErrorAlert content={message.content} />
) : message.content ? (
<div>
<div className="bg-white/60 px-4 py-2.5 rounded-2xl rounded-tl-md text-[14px] leading-relaxed shadow-[0_1px_3px_rgba(0,0,0,0.04)] border border-black/[0.04]">
<div className="markdown-content">
<ReactMarkdown remarkPlugins={[remarkGfm]}>
{message.content}
</ReactMarkdown>
</div>
</div>
{message.retrievals && message.retrievals.length > 0 && (
<RetrievalCard retrievals={message.retrievals} />
)}
<div className="text-[10px] text-gray-400 mt-1 pl-1">
{formatTime(message.timestamp)}
</div>
</div>
) : (
/* Typing indicator */
<div className="bg-white/60 px-4 py-3 rounded-2xl rounded-tl-md inline-flex items-center gap-1.5 shadow-[0_1px_3px_rgba(0,0,0,0.04)] border border-black/[0.04]">
<span className="typing-dot w-1.5 h-1.5 bg-[#002fa7] rounded-full" />
<span className="typing-dot w-1.5 h-1.5 bg-[#002fa7] rounded-full" />
<span className="typing-dot w-1.5 h-1.5 bg-[#002fa7] rounded-full" />
</div>
)}
</div>
</div>
)}
</div>
</div>
);
}
/** Prominent auth error alert with setup guidance */
function AuthErrorAlert({ content }: { content: string }) {
return (
<div className="animate-fade-in-scale rounded-xl border border-red-200 bg-red-50/80 px-4 py-3 space-y-2">
<div className="flex items-center gap-2">
<AlertTriangle className="w-4 h-4 text-red-500 shrink-0" />
<span className="text-[13px] font-semibold text-red-700">
API Key 认证失败
</span>
</div>
<p className="text-[12px] text-red-600/80 leading-relaxed">
你的 API Key 无效或未配置。请检查 <code className="bg-red-100 px-1 rounded text-red-700">backend/.env</code> 文件中的配置。
</p>
<div className="flex items-center gap-3 pt-1">
<a
href="http://localhost:8002/"
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-[11px] font-medium text-red-600 hover:text-red-800 transition-colors"
>
<Key className="w-3 h-3" />
检查后端状态
</a>
<span className="text-[10px] text-red-400">|</span>
<span className="text-[10px] text-red-500 font-mono">{content.slice(0, 120)}...</span>
</div>
</div>
);
}
+62
View File
@@ -0,0 +1,62 @@
"use client";
import { useEffect, useRef } from "react";
import { useApp } from "@/lib/store";
import ChatMessage from "./ChatMessage";
import ChatInput from "./ChatInput";
import { Sparkles } from "lucide-react";
export default function ChatPanel() {
const { messages } = useApp();
const bottomRef = useRef<HTMLDivElement>(null);
useEffect(() => {
bottomRef.current?.scrollIntoView({ behavior: "smooth" });
}, [messages]);
return (
<div className="flex flex-col h-full">
<div className="flex-1 overflow-y-auto scroll-shadow">
{messages.length === 0 ? (
<div className="flex flex-col items-center justify-center h-full">
<div className="w-14 h-14 rounded-2xl bg-gradient-to-br from-[#002fa7] to-[#4070ff] flex items-center justify-center mb-4 shadow-lg shadow-[#002fa7]/15">
<Sparkles className="w-7 h-7 text-white" />
</div>
<h2 className="text-lg font-semibold text-gray-800 mb-1">
Hi, how can I help?
</h2>
<p className="text-[13px] text-gray-400 max-w-xs text-center leading-relaxed">
Ask me anything, or try{" "}
<span className="text-[#ff6723] font-medium">&quot;查询北京天气&quot;</span>
</p>
<div className="flex flex-wrap gap-2 mt-5 max-w-md justify-center">
{["你好,介绍一下自己", "查询北京天气", "帮我写一段Python代码"].map((hint) => (
<QuickHint key={hint} text={hint} />
))}
</div>
</div>
) : (
<div className="py-4">
{messages.map((msg) => (
<ChatMessage key={msg.id} message={msg} />
))}
<div ref={bottomRef} />
</div>
)}
</div>
<ChatInput />
</div>
);
}
function QuickHint({ text }: { text: string }) {
const { sendMessage, isStreaming } = useApp();
return (
<button
onClick={() => !isStreaming && sendMessage(text)}
className="px-3 py-1.5 rounded-full text-[12px] text-gray-500 bg-white/60 border border-black/[0.04] hover:bg-white hover:shadow-sm hover:text-gray-700 transition-all"
>
{text}
</button>
);
}
+54
View File
@@ -0,0 +1,54 @@
"use client";
import { useState } from "react";
import { ChevronDown, ChevronRight, Database } from "lucide-react";
import type { RetrievalResult } from "@/lib/store";
interface Props {
retrievals: RetrievalResult[];
}
export default function RetrievalCard({ retrievals }: Props) {
const [expanded, setExpanded] = useState(false);
if (retrievals.length === 0) return null;
return (
<div className="mt-1.5 mb-2 rounded-xl border border-violet-200/60 bg-violet-50/40 overflow-hidden animate-fade-in-scale">
<button
onClick={() => setExpanded((v) => !v)}
className="w-full flex items-center gap-2 px-3 py-1.5 text-[12px] hover:bg-violet-50/60 transition-colors"
>
{expanded ? (
<ChevronDown className="w-3 h-3 text-violet-400" />
) : (
<ChevronRight className="w-3 h-3 text-violet-400" />
)}
<div className="w-5 h-5 rounded flex items-center justify-center bg-violet-100">
<Database className="w-3 h-3 text-violet-600" />
</div>
<span className="font-medium text-violet-700">Memory Retrieval</span>
<span className="text-[10px] text-violet-400 ml-1">
{retrievals.length} snippet{retrievals.length > 1 ? "s" : ""}
</span>
</button>
{expanded && (
<div className="px-3 pb-2.5 space-y-2 border-t border-violet-100/60 pt-2">
{retrievals.map((r, idx) => (
<div key={idx} className="space-y-0.5">
<div className="flex items-center gap-2 text-[10px]">
<span className="font-semibold text-violet-500 uppercase tracking-wider">
{r.source}
</span>
<span className="text-violet-400">score: {r.score}</span>
</div>
<pre className="p-2 bg-white/70 rounded-lg text-[11px] text-gray-600 font-mono whitespace-pre-wrap leading-relaxed max-h-32 overflow-y-auto border border-violet-100/40">
{r.text}
</pre>
</div>
))}
</div>
)}
</div>
);
}
+80
View File
@@ -0,0 +1,80 @@
"use client";
import { useState } from "react";
import {
ChevronDown, ChevronRight, Terminal, Code, Globe,
FileText, Search, Loader2, CheckCircle2,
} from "lucide-react";
import type { ToolCall } from "@/lib/store";
const TOOL_META: Record<string, { icon: React.ElementType; color: string; bg: string }> = {
terminal: { icon: Terminal, color: "#6b7280", bg: "#f3f4f6" },
python_repl: { icon: Code, color: "#2563eb", bg: "#eff6ff" },
fetch_url: { icon: Globe, color: "#059669", bg: "#ecfdf5" },
read_file: { icon: FileText, color: "#d97706", bg: "#fffbeb" },
search_knowledge_base: { icon: Search, color: "#7c3aed", bg: "#f5f3ff" },
};
interface Props { toolCalls: ToolCall[] }
export default function ThoughtChain({ toolCalls }: Props) {
const [expanded, setExpanded] = useState<Record<number, boolean>>({});
if (toolCalls.length === 0) return null;
return (
<div className="mb-2 space-y-1">
{toolCalls.map((tc, idx) => {
const meta = TOOL_META[tc.tool] || TOOL_META.terminal;
const Icon = meta.icon;
const isOpen = expanded[idx] ?? false;
return (
<div key={idx} className="rounded-xl border border-black/[0.04] bg-white/50 overflow-hidden animate-fade-in-scale">
<button
onClick={() => setExpanded((p) => ({ ...p, [idx]: !p[idx] }))}
className="w-full flex items-center gap-2 px-3 py-1.5 text-[12px] hover:bg-black/[0.02] transition-colors"
>
{isOpen
? <ChevronDown className="w-3 h-3 text-gray-400" />
: <ChevronRight className="w-3 h-3 text-gray-400" />
}
<div
className="w-5 h-5 rounded flex items-center justify-center"
style={{ background: meta.bg }}
>
<Icon className="w-3 h-3" style={{ color: meta.color }} />
</div>
<span className="font-medium text-gray-600">{tc.tool}</span>
<span className="ml-auto">
{tc.status === "running"
? <Loader2 className="w-3.5 h-3.5 text-amber-500 animate-spin" />
: <CheckCircle2 className="w-3.5 h-3.5 text-emerald-500" />
}
</span>
</button>
{isOpen && (
<div className="px-3 pb-2 text-[11px] space-y-1.5 border-t border-black/[0.03] pt-1.5">
{tc.input && (
<div>
<span className="text-[10px] font-semibold text-gray-400 uppercase tracking-wider">Input</span>
<pre className="mt-0.5 p-2 bg-gray-50/80 rounded-lg overflow-x-auto whitespace-pre-wrap text-gray-600 font-mono leading-relaxed">
{tc.input}
</pre>
</div>
)}
{tc.output && (
<div>
<span className="text-[10px] font-semibold text-gray-400 uppercase tracking-wider">Output</span>
<pre className="mt-0.5 p-2 bg-gray-50/80 rounded-lg overflow-x-auto whitespace-pre-wrap text-gray-600 font-mono max-h-36 overflow-y-auto leading-relaxed">
{tc.output}
</pre>
</div>
)}
</div>
)}
</div>
);
})}
</div>
);
}
+354
View File
@@ -0,0 +1,354 @@
"use client";
import { useEffect, useState, useCallback, useRef } from "react";
import { useApp } from "@/lib/store";
import { readFile, saveFile, listSkills, getFileTokenCounts } from "@/lib/api";
import {
Save,
FileText,
Loader2,
CheckCircle2,
AlertCircle,
Brain,
Zap,
Sparkles,
Maximize2,
Minimize2,
} from "lucide-react";
import dynamic from "next/dynamic";
const MonacoEditor = dynamic(() => import("@monaco-editor/react"), {
ssr: false,
loading: () => (
<div className="flex items-center justify-center h-full text-gray-400 text-sm">
<Loader2 className="w-4 h-4 animate-spin mr-2" />Loading editor...
</div>
),
});
// ── Memory files config ─────────────────────────────────
const MEMORY_FILES = [
{ label: "MEMORY.md", path: "memory/MEMORY.md", icon: Brain, color: "#7c3aed" },
{ label: "SOUL.md", path: "workspace/SOUL.md", icon: Sparkles, color: "#f59e0b" },
{ label: "IDENTITY.md", path: "workspace/IDENTITY.md", icon: FileText, color: "#6b7280" },
{ label: "USER.md", path: "workspace/USER.md", icon: FileText, color: "#6b7280" },
{ label: "AGENTS.md", path: "workspace/AGENTS.md", icon: FileText, color: "#10b981" },
{ label: "SKILLS_SNAPSHOT.md", path: "SKILLS_SNAPSHOT.md", icon: Zap, color: "#f59e0b" },
];
export default function InspectorPanel() {
const {
inspectorFile,
setInspectorFile,
rightTab,
setRightTab,
expandedFile,
setExpandedFile,
} = useApp();
const [content, setContent] = useState("");
const [originalContent, setOriginalContent] = useState("");
const [loading, setLoading] = useState(false);
const [saving, setSaving] = useState(false);
const [saveStatus, setSaveStatus] = useState<"idle" | "saved" | "error">("idle");
const [skills, setSkills] = useState<Array<{ name: string; path: string; description: string }>>([]);
const [tokenCounts, setTokenCounts] = useState<Record<string, number>>({});
const editorRef = useRef<unknown>(null);
// Load skills on mount
useEffect(() => {
listSkills()
.then(setSkills)
.catch(() => setSkills([]));
}, []);
// Load token counts for memory files
useEffect(() => {
if (rightTab === "memory") {
const paths = MEMORY_FILES.map((f) => f.path);
getFileTokenCounts(paths)
.then((data) => {
const counts: Record<string, number> = {};
for (const f of data.files) {
counts[f.path] = f.tokens;
}
setTokenCounts(counts);
})
.catch(() => {});
}
}, [rightTab]);
// Load file content when selected
useEffect(() => {
if (!inspectorFile) {
setContent("");
setOriginalContent("");
return;
}
setLoading(true);
setSaveStatus("idle");
readFile(inspectorFile)
.then((t) => {
setContent(t);
setOriginalContent(t);
})
.catch(() => {
setContent("# Error loading file");
setOriginalContent("");
})
.finally(() => setLoading(false));
}, [inspectorFile]);
const handleSave = useCallback(async () => {
if (!inspectorFile || saving) return;
setSaving(true);
setSaveStatus("idle");
try {
await saveFile(inspectorFile, content);
setOriginalContent(content);
setSaveStatus("saved");
setTimeout(() => setSaveStatus("idle"), 2000);
} catch {
setSaveStatus("error");
} finally {
setSaving(false);
}
}, [inspectorFile, content, saving]);
// Ctrl+S shortcut
useEffect(() => {
const h = (e: KeyboardEvent) => {
if ((e.ctrlKey || e.metaKey) && e.key === "s") {
e.preventDefault();
handleSave();
}
};
window.addEventListener("keydown", h);
return () => window.removeEventListener("keydown", h);
}, [handleSave]);
const isDirty = content !== originalContent;
const fileExt = inspectorFile?.split(".").pop() || "md";
const language = fileExt === "md" ? "markdown" : fileExt === "json" ? "json" : "markdown";
const fileName = inspectorFile?.split("/").pop() || "";
return (
<div className="flex flex-col h-full">
{/* Tab bar */}
<div className="flex gap-0.5 p-2 pb-0 shrink-0">
{(["memory", "skills"] as const).map((tab) => {
const active = rightTab === tab;
const Icon = tab === "memory" ? Brain : Zap;
const color = tab === "memory" ? "#7c3aed" : "#f59e0b";
return (
<button
key={tab}
onClick={() => setRightTab(tab)}
className={`flex-1 flex items-center justify-center gap-1.5 py-2 rounded-lg text-[11px] font-medium transition-all ${
active
? "bg-white/70 shadow-sm text-gray-800"
: "text-gray-400 hover:text-gray-600 hover:bg-white/30"
}`}
>
<Icon className="w-3.5 h-3.5" style={active ? { color } : {}} />
{tab === "memory" ? "Memory" : "Skills"}
</button>
);
})}
</div>
<div className="mx-3 my-1.5 h-px bg-black/[0.04]" />
{/* File list (hidden when expanded) */}
{!expandedFile && (
<div className="shrink-0 overflow-y-auto px-1.5 max-h-[35%]">
{rightTab === "memory" ? (
<FileList files={MEMORY_FILES} onSelect={setInspectorFile} selectedPath={inspectorFile} tokenCounts={tokenCounts} />
) : (
<SkillsFileList skills={skills} onSelect={setInspectorFile} selectedPath={inspectorFile} />
)}
</div>
)}
{/* Editor area */}
<div className="flex-1 flex flex-col overflow-hidden">
{inspectorFile ? (
<>
{/* Editor toolbar */}
<div className="shrink-0 flex items-center justify-between px-3 py-1.5 border-t border-b border-black/[0.04] bg-white/60 backdrop-blur-sm">
<div className="flex items-center gap-2 min-w-0">
<FileText className="w-3.5 h-3.5 text-[#ff6723] shrink-0" />
<div className="min-w-0">
<div className="text-[11px] font-semibold text-gray-700 truncate flex items-center gap-1.5">
{fileName}
{isDirty && <span className="w-1.5 h-1.5 bg-amber-400 rounded-full shrink-0" />}
</div>
</div>
</div>
<div className="flex items-center gap-1">
{saveStatus === "saved" && <CheckCircle2 className="w-3.5 h-3.5 text-emerald-500" />}
{saveStatus === "error" && <AlertCircle className="w-3.5 h-3.5 text-red-500" />}
<button
onClick={handleSave}
disabled={saving || !isDirty}
className="flex items-center gap-1 px-2 py-1 rounded-md text-[11px] font-medium text-white bg-[#ff6723] disabled:opacity-25 hover:bg-[#e55a1b] transition-all active:scale-95"
title="Save (Ctrl+S)"
>
{saving ? <Loader2 className="w-3 h-3 animate-spin" /> : <Save className="w-3 h-3" />}
Save
</button>
<button
onClick={() => setExpandedFile(!expandedFile)}
className="p-1 rounded-md text-gray-400 hover:text-gray-600 hover:bg-black/[0.04] transition-colors"
title={expandedFile ? "Collapse" : "Expand"}
>
{expandedFile ? <Minimize2 className="w-3.5 h-3.5" /> : <Maximize2 className="w-3.5 h-3.5" />}
</button>
</div>
</div>
{/* Monaco editor */}
<div className="flex-1">
{loading ? (
<div className="flex items-center justify-center h-full">
<Loader2 className="w-5 h-5 animate-spin text-gray-400" />
</div>
) : (
<MonacoEditor
height="100%"
language={language}
value={content}
theme="vs"
onChange={(val) => setContent(val || "")}
onMount={(editor) => {
editorRef.current = editor;
}}
options={{
minimap: { enabled: false },
fontSize: 13,
lineNumbers: "on",
wordWrap: "on",
scrollBeyondLastLine: false,
padding: { top: 10, bottom: 10 },
renderLineHighlight: "none",
overviewRulerBorder: false,
hideCursorInOverviewRuler: true,
automaticLayout: true,
fontFamily: "'SF Mono','JetBrains Mono','Fira Code',Consolas,monospace",
lineHeight: 20,
cursorBlinking: "smooth",
smoothScrolling: true,
}}
/>
)}
</div>
</>
) : (
<div className="flex flex-col items-center justify-center flex-1 text-gray-400">
<FileText className="w-10 h-10 mb-2 text-gray-300" />
<p className="text-sm font-medium text-gray-500">No file selected</p>
<p className="text-[11px] mt-1 text-gray-400">Choose from the list above</p>
</div>
)}
</div>
</div>
);
}
// ── File List Component ─────────────────────────────────
function FileList({
files,
onSelect,
selectedPath,
tokenCounts,
}: {
files: Array<{ label: string; path: string; icon: React.ElementType; color: string }>;
onSelect: (path: string) => void;
selectedPath: string | null;
tokenCounts?: Record<string, number>;
}) {
return (
<div className="space-y-0.5">
<p className="px-3 pt-1 pb-1 text-[10px] font-semibold text-gray-400 uppercase tracking-widest">
Workspace
</p>
{files.map((f) => {
const Icon = f.icon;
const active = selectedPath === f.path;
const count = tokenCounts?.[f.path];
return (
<button
key={f.path}
onClick={() => onSelect(f.path)}
className={`w-full flex items-center gap-2 px-3 py-1.5 text-[12px] rounded-lg transition-all text-left relative ${
active
? "bg-white/70 text-gray-800 font-medium shadow-sm"
: "text-gray-500 hover:bg-white/40"
}`}
>
{active && (
<div
className="absolute left-0 top-1/2 -translate-y-1/2 w-[3px] h-4 rounded-r-full"
style={{ background: f.color }}
/>
)}
<Icon className="w-3.5 h-3.5 shrink-0" style={{ color: f.color }} />
<span className="truncate flex-1">{f.label}</span>
{count !== undefined && count > 0 && (
<span className="text-[10px] text-gray-400 shrink-0">{count}t</span>
)}
</button>
);
})}
</div>
);
}
// ── Skills File List ────────────────────────────────────
function SkillsFileList({
skills,
onSelect,
selectedPath,
}: {
skills: Array<{ name: string; path: string; description: string }>;
onSelect: (path: string) => void;
selectedPath: string | null;
}) {
return (
<div className="space-y-0.5">
<p className="px-3 pt-1 pb-1 text-[10px] font-semibold text-gray-400 uppercase tracking-widest">
Available Skills
</p>
{skills.length === 0 && (
<p className="px-3 py-2 text-[11px] text-gray-400">No skills found</p>
)}
{skills.map((s) => {
const active = selectedPath === s.path;
return (
<button
key={s.name}
onClick={() => onSelect(s.path)}
className={`w-full flex items-center gap-2 px-3 py-1.5 text-[12px] rounded-lg transition-all text-left relative ${
active
? "bg-white/70 text-gray-800 font-medium shadow-sm"
: "text-gray-500 hover:bg-white/40"
}`}
>
{active && (
<div className="absolute left-0 top-1/2 -translate-y-1/2 w-[3px] h-4 bg-[#f59e0b] rounded-r-full" />
)}
<Zap className="w-3.5 h-3.5 shrink-0 text-[#f59e0b]" />
<div className="min-w-0">
<span className="truncate block">{s.name}</span>
{s.description && (
<span className="text-[10px] text-gray-400 truncate block">{s.description}</span>
)}
</div>
</button>
);
})}
</div>
);
}
+55
View File
@@ -0,0 +1,55 @@
"use client";
import { PanelLeft, PanelRight } from "lucide-react";
import { useApp } from "@/lib/store";
export default function Navbar() {
const { sidebarOpen, toggleSidebar, inspectorOpen, toggleInspector } =
useApp();
return (
<nav className="glass-nav sticky top-0 z-50 h-11 flex items-center justify-between px-3">
{/* Left — Sidebar toggle */}
<div className="w-[120px]">
<button
onClick={toggleSidebar}
className={`w-8 h-8 flex items-center justify-center rounded-lg transition-all ${
sidebarOpen
? "bg-[#002fa7] text-white shadow-sm"
: "text-gray-400 hover:text-gray-600 hover:bg-black/[0.04]"
}`}
>
<PanelLeft className="w-[16px] h-[16px]" />
</button>
</div>
{/* Center — Brand */}
<div className="flex items-center gap-2">
<div className="w-6 h-6 rounded-md bg-gradient-to-br from-[#002fa7] to-[#4070ff] flex items-center justify-center">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none">
<path d="M12 2L2 7L12 12L22 7L12 2Z" fill="white" fillOpacity="0.9" />
<path d="M2 17L12 22L22 17" stroke="white" strokeOpacity="0.7" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
<path d="M2 12L12 17L22 12" stroke="white" strokeOpacity="0.85" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
</svg>
</div>
<span className="font-semibold text-[14px] tracking-tight text-gray-800">
mini OpenClaw
</span>
</div>
{/* Right — Inspector toggle */}
<div className="w-[120px] flex justify-end">
<button
onClick={toggleInspector}
className={`w-8 h-8 flex items-center justify-center rounded-lg transition-all ${
inspectorOpen
? "bg-[#ff6723] text-white shadow-sm"
: "text-gray-400 hover:text-gray-600 hover:bg-black/[0.04]"
}`}
>
<PanelRight className="w-[16px] h-[16px]" />
</button>
</div>
</nav>
);
}
+61
View File
@@ -0,0 +1,61 @@
"use client";
import { useCallback, useRef, useEffect } from "react";
interface ResizeHandleProps {
onResize: (delta: number) => void;
direction: "left" | "right";
}
export default function ResizeHandle({ onResize, direction }: ResizeHandleProps) {
const dragging = useRef(false);
const startX = useRef(0);
// Keep a ref to the latest onResize to avoid stale closure during drag
const onResizeRef = useRef(onResize);
const directionRef = useRef(direction);
useEffect(() => {
onResizeRef.current = onResize;
}, [onResize]);
useEffect(() => {
directionRef.current = direction;
}, [direction]);
const handleMouseDown = useCallback((e: React.MouseEvent) => {
e.preventDefault();
dragging.current = true;
startX.current = e.clientX;
const handleMouseMove = (ev: MouseEvent) => {
if (!dragging.current) return;
const delta = ev.clientX - startX.current;
startX.current = ev.clientX;
// For left panel: dragging right = positive delta = wider
// For right panel: dragging left = negative delta = wider
onResizeRef.current(directionRef.current === "left" ? delta : -delta);
};
const handleMouseUp = () => {
dragging.current = false;
document.removeEventListener("mousemove", handleMouseMove);
document.removeEventListener("mouseup", handleMouseUp);
document.body.style.cursor = "";
document.body.style.userSelect = "";
};
document.addEventListener("mousemove", handleMouseMove);
document.addEventListener("mouseup", handleMouseUp);
document.body.style.cursor = "col-resize";
document.body.style.userSelect = "none";
}, []);
return (
<div
className="resize-handle"
onMouseDown={handleMouseDown}
>
<div className="resize-handle-line" />
</div>
);
}
+425
View File
@@ -0,0 +1,425 @@
"use client";
import { useEffect, useState, useRef, useCallback } from "react";
import {
MessageSquare,
Plus,
MoreHorizontal,
Pencil,
Trash2,
ChevronDown,
ChevronRight,
FileCode,
Check,
X,
Maximize2,
Minimize2,
RefreshCw,
Wrench,
Loader2,
Database,
} from "lucide-react";
import { useApp } from "@/lib/store";
import { getSessionTokenCount } from "@/lib/api";
export default function Sidebar() {
const {
sessionId,
setSessionId,
sessions,
createSession,
renameSession,
deleteSession,
rawMessages,
loadRawMessages,
isCompressing,
compressCurrentSession,
ragMode,
toggleRagMode,
} = useApp();
const [rawOpen, setRawOpen] = useState(false);
const [rawExpanded, setRawExpanded] = useState(false);
const [sessionTokens, setSessionTokens] = useState<number | null>(null);
const [showCompressModal, setShowCompressModal] = useState(false);
// Load raw messages when section is opened or session changes
useEffect(() => {
if (rawOpen) {
loadRawMessages();
getSessionTokenCount(sessionId)
.then((data) => setSessionTokens(data.total_tokens))
.catch(() => setSessionTokens(null));
}
}, [rawOpen, sessionId, loadRawMessages]);
return (
<aside className="flex flex-col h-full relative">
{/* New Chat button */}
<div className="p-2 pb-0">
<button
onClick={createSession}
className="w-full flex items-center gap-2 px-3 py-2 text-[13px] font-medium text-[#002fa7] hover:bg-[#002fa7]/[0.05] rounded-lg transition-all"
>
<Plus className="w-4 h-4" />
New Chat
</button>
</div>
<div className="mx-3 my-1.5 h-px bg-black/[0.04]" />
{/* Session list */}
<div className="flex-1 overflow-y-auto px-1.5">
{sessions.length > 0 && (
<div className="space-y-0.5">
<p className="px-3 pt-1 pb-1 text-[10px] font-semibold text-gray-400 uppercase tracking-widest">
Recent
</p>
{sessions.map((s) => (
<SessionItem
key={s.id}
id={s.id}
title={s.title}
isActive={sessionId === s.id}
onSelect={() => setSessionId(s.id)}
onRename={(title) => renameSession(s.id, title)}
onDelete={() => deleteSession(s.id)}
/>
))}
</div>
)}
</div>
{/* Divider */}
<div className="mx-3 h-px bg-black/[0.04]" />
{/* Raw Messages section */}
<div className="shrink-0">
<div className="flex items-center">
<button
onClick={() => setRawOpen((v) => !v)}
className="flex-1 flex items-center gap-2 px-4 py-2 text-[11px] font-semibold text-gray-500 hover:text-gray-700 transition-colors"
>
{rawOpen ? (
<ChevronDown className="w-3 h-3" />
) : (
<ChevronRight className="w-3 h-3" />
)}
<FileCode className="w-3.5 h-3.5" />
Raw Messages
{rawOpen && sessionTokens !== null && (
<span className="text-[10px] text-gray-400 font-normal ml-1">
~{sessionTokens.toLocaleString()} tokens
</span>
)}
</button>
{rawOpen && (
<div className="flex items-center mr-2 gap-0.5">
<button
onClick={() => toggleRagMode()}
className={`p-1 rounded-md transition-colors ${
ragMode
? "text-white bg-[#002fa7] hover:bg-[#001f7a]"
: "text-gray-400 hover:text-gray-600 hover:bg-black/[0.04]"
}`}
title={ragMode ? "RAG Mode ON" : "RAG Mode OFF"}
>
<Database className="w-3.5 h-3.5" />
</button>
<button
onClick={() => setShowCompressModal(true)}
disabled={isCompressing}
className="p-1 rounded-md text-gray-400 hover:text-gray-600 hover:bg-black/[0.04] transition-colors disabled:opacity-40"
title="Compress history"
>
{isCompressing ? (
<Loader2 className="w-3.5 h-3.5 animate-spin" />
) : (
<Wrench className="w-3.5 h-3.5" />
)}
</button>
<button
onClick={loadRawMessages}
className="p-1 rounded-md text-gray-400 hover:text-gray-600 hover:bg-black/[0.04] transition-colors"
title="Refresh"
>
<RefreshCw className="w-3.5 h-3.5" />
</button>
<button
onClick={() => setRawExpanded(true)}
className="p-1 rounded-md text-gray-400 hover:text-gray-600 hover:bg-black/[0.04] transition-colors"
title="Expand"
>
<Maximize2 className="w-3.5 h-3.5" />
</button>
</div>
)}
</div>
{rawOpen && !rawExpanded && (
<div className="px-2 pb-2 max-h-[40vh] overflow-y-auto">
<RawMessageViewer messages={rawMessages} truncate />
</div>
)}
</div>
{/* Full-screen Raw Messages overlay */}
{rawExpanded && (
<div className="fixed inset-0 z-[100] bg-black/50 flex items-center justify-center p-6 animate-fade-in">
<div className="bg-white rounded-2xl shadow-2xl w-full max-w-4xl h-[85vh] flex flex-col overflow-hidden">
{/* Header */}
<div className="flex items-center justify-between px-5 py-3 border-b border-black/[0.06]">
<div className="flex items-center gap-2">
<FileCode className="w-4 h-4 text-gray-500" />
<span className="text-[14px] font-semibold text-gray-800">Raw Messages</span>
<span className="text-[11px] text-gray-400 ml-1">
{rawMessages ? `${rawMessages.length} messages` : ""}
</span>
</div>
<div className="flex items-center gap-1">
<button
onClick={loadRawMessages}
className="p-1.5 rounded-md text-gray-400 hover:text-gray-600 hover:bg-black/[0.04] transition-colors"
title="Refresh"
>
<RefreshCw className="w-4 h-4" />
</button>
<button
onClick={() => setRawExpanded(false)}
className="p-1.5 rounded-md text-gray-400 hover:text-gray-600 hover:bg-black/[0.04] transition-colors"
title="Close"
>
<Minimize2 className="w-4 h-4" />
</button>
</div>
</div>
{/* Body */}
<div className="flex-1 overflow-y-auto p-5">
<RawMessageViewer messages={rawMessages} truncate={false} />
</div>
</div>
</div>
)}
{/* Compress confirmation modal */}
{showCompressModal && (
<div className="fixed inset-0 z-[110] bg-black/50 flex items-center justify-center p-6 animate-fade-in">
<div className="bg-white rounded-xl shadow-2xl w-full max-w-sm p-5 space-y-4">
<h3 className="text-[14px] font-semibold text-gray-800">Compress History</h3>
<p className="text-[13px] text-gray-600 leading-relaxed">
Are you sure you want to compress 50% of conversation history? The compressed messages will be archived and replaced with a summary.
</p>
<div className="flex items-center justify-end gap-2">
<button
onClick={() => setShowCompressModal(false)}
className="px-3 py-1.5 text-[12px] font-medium text-gray-600 hover:bg-gray-100 rounded-lg transition-colors"
>
Cancel
</button>
<button
onClick={async () => {
setShowCompressModal(false);
await compressCurrentSession();
// Refresh token count
getSessionTokenCount(sessionId)
.then((data) => setSessionTokens(data.total_tokens))
.catch(() => {});
}}
className="px-3 py-1.5 text-[12px] font-medium text-white bg-[#002fa7] hover:bg-[#001f7a] rounded-lg transition-colors"
>
Confirm
</button>
</div>
</div>
</div>
)}
</aside>
);
}
// ── Session Item ────────────────────────────────────────
function SessionItem({
id,
title,
isActive,
onSelect,
onRename,
onDelete,
}: {
id: string;
title: string;
isActive: boolean;
onSelect: () => void;
onRename: (title: string) => void;
onDelete: () => void;
}) {
const [menuOpen, setMenuOpen] = useState(false);
const [renaming, setRenaming] = useState(false);
const [renameValue, setRenameValue] = useState(title);
const inputRef = useRef<HTMLInputElement>(null);
const menuRef = useRef<HTMLDivElement>(null);
// Close menu on outside click
useEffect(() => {
if (!menuOpen) return;
const handler = (e: MouseEvent) => {
if (menuRef.current && !menuRef.current.contains(e.target as Node)) {
setMenuOpen(false);
}
};
document.addEventListener("mousedown", handler);
return () => document.removeEventListener("mousedown", handler);
}, [menuOpen]);
// Focus input when renaming
useEffect(() => {
if (renaming && inputRef.current) {
inputRef.current.focus();
inputRef.current.select();
}
}, [renaming]);
const handleRenameSubmit = useCallback(() => {
const trimmed = renameValue.trim();
if (trimmed && trimmed !== title) {
onRename(trimmed);
}
setRenaming(false);
}, [renameValue, title, onRename]);
const handleDelete = useCallback(() => {
setMenuOpen(false);
if (confirm("Delete this session?")) {
onDelete();
}
}, [onDelete]);
if (renaming) {
return (
<div className="flex items-center gap-1 px-2 py-1">
<input
ref={inputRef}
className="flex-1 px-2 py-1 text-[13px] rounded-md border border-[#002fa7]/30 bg-white outline-none focus:border-[#002fa7]"
value={renameValue}
onChange={(e) => setRenameValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") handleRenameSubmit();
if (e.key === "Escape") setRenaming(false);
}}
onBlur={handleRenameSubmit}
/>
<button
onClick={handleRenameSubmit}
className="p-1 text-green-600 hover:bg-green-50 rounded"
>
<Check className="w-3.5 h-3.5" />
</button>
<button
onClick={() => setRenaming(false)}
className="p-1 text-gray-400 hover:bg-gray-100 rounded"
>
<X className="w-3.5 h-3.5" />
</button>
</div>
);
}
return (
<div className="relative group">
<button
onClick={onSelect}
className={`w-full flex items-center gap-2 px-3 py-2 text-[13px] rounded-lg transition-all text-left relative pr-8 ${
isActive
? "bg-white/70 text-gray-800 font-medium shadow-sm"
: "text-gray-500 hover:bg-white/40"
}`}
>
{isActive && (
<div className="absolute left-0 top-1/2 -translate-y-1/2 w-[3px] h-5 bg-[#002fa7] rounded-r-full" />
)}
<MessageSquare className="w-3.5 h-3.5 shrink-0 text-gray-400" />
<span className="truncate">{title}</span>
</button>
{/* More button */}
<div className="absolute right-1 top-1/2 -translate-y-1/2" ref={menuRef}>
<button
onClick={(e) => {
e.stopPropagation();
setMenuOpen((v) => !v);
}}
className="p-1 rounded-md text-gray-300 opacity-0 group-hover:opacity-100 hover:text-gray-600 hover:bg-black/[0.04] transition-all"
>
<MoreHorizontal className="w-3.5 h-3.5" />
</button>
{menuOpen && (
<div className="absolute right-0 top-full mt-1 w-32 bg-white rounded-lg shadow-lg border border-black/[0.06] py-1 z-50 animate-fade-in-scale">
<button
onClick={() => {
setMenuOpen(false);
setRenameValue(title);
setRenaming(true);
}}
className="w-full flex items-center gap-2 px-3 py-1.5 text-[12px] text-gray-600 hover:bg-gray-50 transition-colors"
>
<Pencil className="w-3 h-3" />
Rename
</button>
<button
onClick={handleDelete}
className="w-full flex items-center gap-2 px-3 py-1.5 text-[12px] text-red-500 hover:bg-red-50 transition-colors"
>
<Trash2 className="w-3 h-3" />
Delete
</button>
</div>
)}
</div>
</div>
);
}
// ── Raw Message Viewer ──────────────────────────────────
function RawMessageViewer({
messages,
truncate = true,
}: {
messages: Array<{ role: string; content: string }> | null;
truncate?: boolean;
}) {
if (!messages) {
return (
<div className="text-[11px] text-gray-400 text-center py-4">
No messages yet
</div>
);
}
return (
<div className="raw-message-viewer space-y-1">
{messages.map((msg, i) => {
const roleClass =
msg.role === "system"
? "msg-system"
: msg.role === "user"
? "msg-user"
: "msg-assistant";
const displayContent =
truncate && msg.content.length > 500
? msg.content.slice(0, 500) + "..."
: msg.content;
return (
<div key={i} className={roleClass}>
<div className="msg-role">{msg.role}</div>
<div className={`msg-content ${truncate ? "" : "!max-h-none"}`}>
{displayContent}
</div>
</div>
);
})}
</div>
);
}
+256
View File
@@ -0,0 +1,256 @@
/**
* API client for mini OpenClaw backend.
* Custom SSE parser for POST requests (native EventSource only supports GET).
*/
const API_BASE =
typeof window !== "undefined"
? `http://${window.location.hostname}:8002/api`
: "http://localhost:8002/api";
export interface SSEEvent {
event: string;
data: Record<string, unknown>;
}
/**
* Stream chat messages via POST SSE.
* Yields parsed SSE events as they arrive.
*/
export async function* streamChat(
message: string,
sessionId: string
): AsyncGenerator<SSEEvent> {
const response = await fetch(`${API_BASE}/chat`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message, session_id: sessionId, stream: true }),
});
if (!response.ok) {
throw new Error(`Chat API error: ${response.status}`);
}
const reader = response.body?.getReader();
if (!reader) throw new Error("No response body");
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop() || "";
let currentEvent = "message";
for (const line of lines) {
if (line.startsWith("event:")) {
currentEvent = line.slice(6).trim();
} else if (line.startsWith("data:")) {
const dataStr = line.slice(5).trim();
if (dataStr) {
try {
const data = JSON.parse(dataStr);
yield { event: currentEvent, data };
} catch {
// Skip malformed JSON
}
}
}
// Empty line resets event type
if (line === "") {
currentEvent = "message";
}
}
}
}
/**
* Read a file from the backend.
*/
export async function readFile(path: string): Promise<string> {
const resp = await fetch(`${API_BASE}/files?path=${encodeURIComponent(path)}`);
if (!resp.ok) throw new Error(`Failed to read file: ${resp.status}`);
const data = await resp.json();
return data.content;
}
/**
* Save a file to the backend.
*/
export async function saveFile(path: string, content: string): Promise<void> {
const resp = await fetch(`${API_BASE}/files`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ path, content }),
});
if (!resp.ok) throw new Error(`Failed to save file: ${resp.status}`);
}
/**
* List all sessions.
*/
export async function listSessions(): Promise<
Array<{ id: string; title: string; updated_at: number }>
> {
const resp = await fetch(`${API_BASE}/sessions`);
if (!resp.ok) throw new Error(`Failed to list sessions: ${resp.status}`);
const data = await resp.json();
return data.sessions;
}
/**
* Create a new session.
*/
export async function createSession(): Promise<{ id: string; title: string }> {
const resp = await fetch(`${API_BASE}/sessions`, { method: "POST" });
if (!resp.ok) throw new Error(`Failed to create session: ${resp.status}`);
return resp.json();
}
/**
* Rename a session.
*/
export async function renameSession(id: string, title: string): Promise<void> {
const resp = await fetch(`${API_BASE}/sessions/${encodeURIComponent(id)}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title }),
});
if (!resp.ok) throw new Error(`Failed to rename session: ${resp.status}`);
}
/**
* Delete a session.
*/
export async function deleteSession(id: string): Promise<void> {
const resp = await fetch(`${API_BASE}/sessions/${encodeURIComponent(id)}`, {
method: "DELETE",
});
if (!resp.ok) throw new Error(`Failed to delete session: ${resp.status}`);
}
/**
* Get raw messages for a session (including system prompt).
*/
export async function getRawMessages(
sessionId: string
): Promise<{ session_id: string; title: string; messages: Array<{ role: string; content: string }> }> {
const resp = await fetch(
`${API_BASE}/sessions/${encodeURIComponent(sessionId)}/messages`
);
if (!resp.ok) throw new Error(`Failed to get raw messages: ${resp.status}`);
return resp.json();
}
/**
* Get session conversation history (no system prompt, includes tool_calls).
*/
export async function getSessionHistory(
sessionId: string
): Promise<{
session_id: string;
messages: Array<{ role: string; content: string; tool_calls?: Array<{ tool: string; input?: string; output?: string }> }>;
}> {
const resp = await fetch(
`${API_BASE}/sessions/${encodeURIComponent(sessionId)}/history`
);
if (!resp.ok) throw new Error(`Failed to get session history: ${resp.status}`);
return resp.json();
}
/**
* List available skills.
*/
export async function listSkills(): Promise<
Array<{ name: string; path: string; description: string }>
> {
const resp = await fetch(`${API_BASE}/skills`);
if (!resp.ok) throw new Error(`Failed to list skills: ${resp.status}`);
const data = await resp.json();
return data.skills;
}
/**
* Generate a title for a session using AI.
*/
export async function generateTitle(
sessionId: string
): Promise<{ title: string }> {
const resp = await fetch(
`${API_BASE}/sessions/${encodeURIComponent(sessionId)}/generate-title`,
{ method: "POST" }
);
if (!resp.ok) throw new Error(`Failed to generate title: ${resp.status}`);
return resp.json();
}
/**
* Get token count for a session (system + messages).
*/
export async function getSessionTokenCount(
sessionId: string
): Promise<{ system_tokens: number; message_tokens: number; total_tokens: number }> {
const resp = await fetch(
`${API_BASE}/tokens/session/${encodeURIComponent(sessionId)}`
);
if (!resp.ok) throw new Error(`Failed to get token count: ${resp.status}`);
return resp.json();
}
/**
* Get token counts for a list of files.
*/
export async function getFileTokenCounts(
paths: string[]
): Promise<{ files: Array<{ path: string; tokens: number }> }> {
const resp = await fetch(`${API_BASE}/tokens/files`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ paths }),
});
if (!resp.ok) throw new Error(`Failed to get file token counts: ${resp.status}`);
return resp.json();
}
/**
* Compress a session's conversation history.
*/
export async function compressSession(
sessionId: string
): Promise<{ archived_count: number; remaining_count: number }> {
const resp = await fetch(
`${API_BASE}/sessions/${encodeURIComponent(sessionId)}/compress`,
{ method: "POST" }
);
if (!resp.ok) throw new Error(`Failed to compress session: ${resp.status}`);
return resp.json();
}
/**
* Get current RAG mode status.
*/
export async function getRagMode(): Promise<{ rag_mode: boolean }> {
const resp = await fetch(`${API_BASE}/config/rag-mode`);
if (!resp.ok) throw new Error(`Failed to get RAG mode: ${resp.status}`);
return resp.json();
}
/**
* Set RAG mode enabled/disabled.
*/
export async function setRagMode(
enabled: boolean
): Promise<{ rag_mode: boolean }> {
const resp = await fetch(`${API_BASE}/config/rag-mode`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ enabled }),
});
if (!resp.ok) throw new Error(`Failed to set RAG mode: ${resp.status}`);
return resp.json();
}
+523
View File
@@ -0,0 +1,523 @@
"use client";
import React, {
createContext,
useContext,
useState,
useCallback,
useRef,
useEffect,
} from "react";
import {
streamChat,
listSessions as apiListSessions,
createSession as apiCreateSession,
renameSession as apiRenameSession,
deleteSession as apiDeleteSession,
getRawMessages as apiGetRawMessages,
getSessionHistory as apiGetSessionHistory,
compressSession as apiCompressSession,
getRagMode as apiGetRagMode,
setRagMode as apiSetRagMode,
} from "./api";
// ── Types ──────────────────────────────────────────────────
export interface ToolCall {
tool: string;
input?: string;
output?: string;
status: "running" | "done";
}
export interface RetrievalResult {
text: string;
score: string;
source: string;
}
export interface ChatMessage {
id: string;
role: "user" | "assistant";
content: string;
toolCalls?: ToolCall[];
retrievals?: RetrievalResult[];
timestamp: number;
}
export interface SessionMeta {
id: string;
title: string;
updated_at: number;
}
export interface RawMessage {
role: string;
content: string;
}
interface AppState {
// Chat
messages: ChatMessage[];
isStreaming: boolean;
sendMessage: (text: string) => Promise<void>;
// Sessions
sessionId: string;
setSessionId: (id: string) => void;
sessions: SessionMeta[];
loadSessions: () => void;
createSession: () => Promise<void>;
renameSession: (id: string, title: string) => Promise<void>;
deleteSession: (id: string) => Promise<void>;
// Sidebar
sidebarOpen: boolean;
setSidebarOpen: (open: boolean) => void;
toggleSidebar: () => void;
// Inspector (Monaco editor)
inspectorFile: string | null;
setInspectorFile: (path: string | null) => void;
inspectorOpen: boolean;
setInspectorOpen: (open: boolean) => void;
toggleInspector: () => void;
// Right panel tab
rightTab: "memory" | "skills";
setRightTab: (tab: "memory" | "skills") => void;
// Raw messages
rawMessages: RawMessage[] | null;
loadRawMessages: () => void;
// Expanded file (editor full-panel mode)
expandedFile: boolean;
setExpandedFile: (v: boolean) => void;
// Panel widths
sidebarWidth: number;
setSidebarWidth: (w: number | ((prev: number) => number)) => void;
inspectorWidth: number;
setInspectorWidth: (w: number | ((prev: number) => number)) => void;
// Compression
isCompressing: boolean;
compressCurrentSession: () => Promise<void>;
// RAG mode
ragMode: boolean;
toggleRagMode: () => void;
}
const AppContext = createContext<AppState | null>(null);
export function AppProvider({ children }: { children: React.ReactNode }) {
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [isStreaming, setIsStreaming] = useState(false);
const [sessionId, setSessionIdRaw] = useState("default");
const [sessions, setSessions] = useState<SessionMeta[]>([]);
const [sidebarOpen, setSidebarOpen] = useState(true);
const [inspectorFile, setInspectorFileRaw] = useState<string | null>(null);
const [inspectorOpen, setInspectorOpen] = useState(false);
const [rightTab, setRightTab] = useState<"memory" | "skills">("memory");
const [rawMessages, setRawMessages] = useState<RawMessage[] | null>(null);
const [expandedFile, setExpandedFile] = useState(false);
const [sidebarWidth, setSidebarWidth] = useState(260);
const [inspectorWidth, setInspectorWidth] = useState(360);
const [isCompressing, setIsCompressing] = useState(false);
const [ragMode, setRagMode] = useState(false);
const abortRef = useRef(false);
// Load RAG mode on mount
useEffect(() => {
apiGetRagMode()
.then((data) => setRagMode(data.rag_mode))
.catch(() => {});
}, []);
const toggleSidebar = useCallback(() => setSidebarOpen((v) => !v), []);
const toggleInspector = useCallback(() => setInspectorOpen((v) => !v), []);
// When a file is selected, auto-open the inspector
const setInspectorFile = useCallback((path: string | null) => {
setInspectorFileRaw(path);
if (path) setInspectorOpen(true);
}, []);
// ── Session management ─────────────────────────────
const loadSessions = useCallback(() => {
apiListSessions()
.then((list) => setSessions(list))
.catch(() => {});
}, []);
// Load sessions on mount
useEffect(() => {
loadSessions();
}, [loadSessions]);
const setSessionId = useCallback(
(id: string) => {
setSessionIdRaw(id);
setMessages([]);
setRawMessages(null);
// Load existing conversation history from backend
apiGetSessionHistory(id)
.then((data) => {
if (data.messages && data.messages.length > 0) {
const loaded: ChatMessage[] = [];
let msgIndex = 0;
for (const msg of data.messages) {
if (msg.role === "user") {
loaded.push({
id: `hist-user-${msgIndex++}`,
role: "user",
content: msg.content,
timestamp: Date.now() - (data.messages.length - msgIndex) * 1000,
});
} else if (msg.role === "assistant") {
const toolCalls: ToolCall[] = (msg.tool_calls || []).map(
(tc: { tool: string; input?: string; output?: string }) => ({
tool: tc.tool,
input: tc.input || "",
output: tc.output || "",
status: "done" as const,
})
);
loaded.push({
id: `hist-asst-${msgIndex++}`,
role: "assistant",
content: msg.content,
toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
timestamp: Date.now() - (data.messages.length - msgIndex) * 1000,
});
}
}
setMessages(loaded);
}
})
.catch(() => {
// Session might not exist yet, that's OK
});
},
[]
);
const createSession = useCallback(async () => {
try {
const meta = await apiCreateSession();
setSessions((prev) => [{ id: meta.id, title: meta.title, updated_at: Date.now() / 1000 }, ...prev]);
setSessionId(meta.id);
} catch {
// ignore
}
}, [setSessionId]);
const renameSessionFn = useCallback(async (id: string, title: string) => {
try {
await apiRenameSession(id, title);
setSessions((prev) =>
prev.map((s) => (s.id === id ? { ...s, title } : s))
);
} catch {
// ignore
}
}, []);
const deleteSessionFn = useCallback(
async (id: string) => {
try {
await apiDeleteSession(id);
setSessions((prev) => prev.filter((s) => s.id !== id));
if (sessionId === id) {
setSessionId("default");
}
} catch {
// ignore
}
},
[sessionId, setSessionId]
);
const loadRawMessages = useCallback(() => {
if (!sessionId) return;
apiGetRawMessages(sessionId)
.then((data) => setRawMessages(data.messages))
.catch(() => setRawMessages(null));
}, [sessionId]);
// ── Compression ──────────────────────────────────────
const compressCurrentSession = useCallback(async () => {
if (isCompressing) return;
setIsCompressing(true);
try {
await apiCompressSession(sessionId);
// Refresh raw messages and chat history
loadRawMessages();
apiGetSessionHistory(sessionId)
.then((data) => {
if (data.messages && data.messages.length > 0) {
const loaded: ChatMessage[] = [];
let msgIndex = 0;
for (const msg of data.messages) {
if (msg.role === "user") {
loaded.push({
id: `hist-user-${msgIndex++}`,
role: "user",
content: msg.content,
timestamp: Date.now() - (data.messages.length - msgIndex) * 1000,
});
} else if (msg.role === "assistant") {
const toolCalls: ToolCall[] = (msg.tool_calls || []).map(
(tc: { tool: string; input?: string; output?: string }) => ({
tool: tc.tool,
input: tc.input || "",
output: tc.output || "",
status: "done" as const,
})
);
loaded.push({
id: `hist-asst-${msgIndex++}`,
role: "assistant",
content: msg.content,
toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
timestamp: Date.now() - (data.messages.length - msgIndex) * 1000,
});
}
}
setMessages(loaded);
} else {
setMessages([]);
}
})
.catch(() => {});
} catch {
// ignore
} finally {
setIsCompressing(false);
}
}, [isCompressing, sessionId, loadRawMessages]);
// ── RAG mode ────────────────────────────────────────
const toggleRagMode = useCallback(() => {
const newMode = !ragMode;
setRagMode(newMode);
apiSetRagMode(newMode).catch(() => setRagMode(ragMode));
}, [ragMode]);
// ── Send message ───────────────────────────────────
// Ref to track the current assistant message ID during streaming
const currentAssistantIdRef = useRef("");
const sendMessage = useCallback(
async (text: string) => {
if (!text.trim() || isStreaming || isCompressing) return;
const userMsg: ChatMessage = {
id: `user-${Date.now()}`,
role: "user",
content: text,
timestamp: Date.now(),
};
const firstAssistantId = `assistant-${Date.now()}`;
const assistantMsg: ChatMessage = {
id: firstAssistantId,
role: "assistant",
content: "",
toolCalls: [],
timestamp: Date.now(),
};
currentAssistantIdRef.current = firstAssistantId;
setMessages((prev) => [...prev, userMsg, assistantMsg]);
setIsStreaming(true);
abortRef.current = false;
try {
for await (const event of streamChat(text, sessionId)) {
if (abortRef.current) break;
// Handle retrieval event (RAG mode)
if (event.event === "retrieval") {
const targetId = currentAssistantIdRef.current;
const retrievalData = event.data as {
query: string;
results: Array<{ text: string; score: string; source: string }>;
};
setMessages((prev) => {
const updated = [...prev];
const idx = updated.findIndex((m) => m.id === targetId);
if (idx === -1) return prev;
updated[idx] = {
...updated[idx],
retrievals: retrievalData.results,
};
return updated;
});
continue;
}
// Handle title event (auto-generated after first message)
if (event.event === "title") {
const titleData = event.data as { session_id: string; title: string };
setSessions((prev) =>
prev.map((s) =>
s.id === titleData.session_id
? { ...s, title: titleData.title }
: s
)
);
continue;
}
// Handle new_response — create a new assistant bubble
if (event.event === "new_response") {
const newId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
currentAssistantIdRef.current = newId;
setMessages((prev) => [
...prev,
{
id: newId,
role: "assistant",
content: "",
toolCalls: [],
timestamp: Date.now(),
},
]);
continue;
}
const targetId = currentAssistantIdRef.current;
setMessages((prev) => {
const updated = [...prev];
const idx = updated.findIndex((m) => m.id === targetId);
if (idx === -1) return prev;
const msg = { ...updated[idx] };
switch (event.event) {
case "token":
msg.content += (event.data.content as string) || "";
break;
case "tool_start":
msg.toolCalls = [
...(msg.toolCalls || []),
{
tool: event.data.tool as string,
input: event.data.input as string,
status: "running",
},
];
break;
case "tool_end": {
const calls = [...(msg.toolCalls || [])];
for (let i = calls.length - 1; i >= 0; i--) {
if (
calls[i].tool === event.data.tool &&
calls[i].status === "running"
) {
calls[i] = {
...calls[i],
output: event.data.output as string,
status: "done",
};
break;
}
}
msg.toolCalls = calls;
break;
}
case "done":
break;
case "error":
msg.content +=
`\n\n**Error:** ${event.data.error || "Unknown error"}`;
break;
}
updated[idx] = msg;
return updated;
});
}
} catch (err) {
const targetId = currentAssistantIdRef.current;
setMessages((prev) => {
const updated = [...prev];
const idx = updated.findIndex((m) => m.id === targetId);
if (idx !== -1) {
updated[idx] = {
...updated[idx],
content:
updated[idx].content +
`\n\n**Connection error:** ${err instanceof Error ? err.message : "Unknown"}`,
};
}
return updated;
});
} finally {
setIsStreaming(false);
// Refresh sessions list to pick up any updates
loadSessions();
}
},
[isStreaming, isCompressing, sessionId, loadSessions]
);
return (
<AppContext.Provider
value={{
messages,
isStreaming,
sendMessage,
sessionId,
setSessionId,
sessions,
loadSessions,
createSession,
renameSession: renameSessionFn,
deleteSession: deleteSessionFn,
sidebarOpen,
setSidebarOpen,
toggleSidebar,
inspectorFile,
setInspectorFile,
inspectorOpen,
setInspectorOpen,
toggleInspector,
rightTab,
setRightTab,
rawMessages,
loadRawMessages,
expandedFile,
setExpandedFile,
sidebarWidth,
setSidebarWidth,
inspectorWidth,
setInspectorWidth,
isCompressing,
compressCurrentSession,
ragMode,
toggleRagMode,
}}
>
{children}
</AppContext.Provider>
);
}
export function useApp(): AppState {
const ctx = useContext(AppContext);
if (!ctx) throw new Error("useApp must be used within AppProvider");
return ctx;
}