Initial commit: NexusOS - local AI assistant platform

This commit is contained in:
Jon Wingender
2026-07-21 22:48:38 -05:00
commit 714b9fc890
850 changed files with 28278 additions and 0 deletions
+24
View File
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+1
View File
@@ -0,0 +1 @@
20
+16
View File
@@ -0,0 +1,16 @@
# React + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend using TypeScript with type-aware lint rules enabled. Check out the [TS template](https://github.com/vitejs/vite/tree/main/packages/create-vite/template-react-ts) for information on how to integrate TypeScript and [`typescript-eslint`](https://typescript-eslint.io) in your project.
+29
View File
@@ -0,0 +1,29 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{js,jsx}'],
extends: [
js.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
parserOptions: {
ecmaVersion: 'latest',
ecmaFeatures: { jsx: true },
sourceType: 'module',
},
},
rules: {
'no-unused-vars': ['error', { varsIgnorePattern: '^[A-Z_]' }],
},
},
])
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/n small.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>NexusOS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
+2623
View File
File diff suppressed because it is too large Load Diff
+27
View File
@@ -0,0 +1,27 @@
{
"name": "web",
"private": true,
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"react": "^19.2.4",
"react-dom": "^19.2.4"
},
"devDependencies": {
"@eslint/js": "^9.39.4",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"eslint": "^9.39.4",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.5.2",
"globals": "^17.4.0",
"vite": "^8.0.4"
}
}
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 9.3 KiB

+24
View File
@@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="bluesky-icon" viewBox="0 0 16 17">
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
</symbol>
<symbol id="discord-icon" viewBox="0 0 20 19">
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
</symbol>
<symbol id="documentation-icon" viewBox="0 0 21 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
</symbol>
<symbol id="github-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
</symbol>
<symbol id="social-icon" viewBox="0 0 20 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
</symbol>
<symbol id="x-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
</symbol>
</svg>

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 185 KiB

+184
View File
@@ -0,0 +1,184 @@
.counter {
font-size: 16px;
padding: 5px 10px;
border-radius: 5px;
color: var(--accent);
background: var(--accent-bg);
border: 2px solid transparent;
transition: border-color 0.3s;
margin-bottom: 24px;
&:hover {
border-color: var(--accent-border);
}
&:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
}
.hero {
position: relative;
.base,
.framework,
.vite {
inset-inline: 0;
margin: 0 auto;
}
.base {
width: 170px;
position: relative;
z-index: 0;
}
.framework,
.vite {
position: absolute;
}
.framework {
z-index: 1;
top: 34px;
height: 28px;
transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg)
scale(1.4);
}
.vite {
z-index: 0;
top: 107px;
height: 26px;
width: auto;
transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg)
scale(0.8);
}
}
#center {
display: flex;
flex-direction: column;
gap: 25px;
place-content: center;
place-items: center;
flex-grow: 1;
@media (max-width: 1024px) {
padding: 32px 20px 24px;
gap: 18px;
}
}
#next-steps {
display: flex;
border-top: 1px solid var(--border);
text-align: left;
& > div {
flex: 1 1 0;
padding: 32px;
@media (max-width: 1024px) {
padding: 24px 20px;
}
}
.icon {
margin-bottom: 16px;
width: 22px;
height: 22px;
}
@media (max-width: 1024px) {
flex-direction: column;
text-align: center;
}
}
#docs {
border-right: 1px solid var(--border);
@media (max-width: 1024px) {
border-right: none;
border-bottom: 1px solid var(--border);
}
}
#next-steps ul {
list-style: none;
padding: 0;
display: flex;
gap: 8px;
margin: 32px 0 0;
.logo {
height: 18px;
}
a {
color: var(--text-h);
font-size: 16px;
border-radius: 6px;
background: var(--social-bg);
display: flex;
padding: 6px 12px;
align-items: center;
gap: 8px;
text-decoration: none;
transition: box-shadow 0.3s;
&:hover {
box-shadow: var(--shadow);
}
.button-icon {
height: 18px;
width: 18px;
}
}
@media (max-width: 1024px) {
margin-top: 20px;
flex-wrap: wrap;
justify-content: center;
li {
flex: 1 1 calc(50% - 8px);
}
a {
width: 100%;
justify-content: center;
box-sizing: border-box;
}
}
}
#spacer {
height: 88px;
border-top: 1px solid var(--border);
@media (max-width: 1024px) {
height: 48px;
}
}
.ticks {
position: relative;
width: 100%;
&::before,
&::after {
content: '';
position: absolute;
top: -4.5px;
border: 5px solid transparent;
}
&::before {
left: 0;
border-left-color: var(--border);
}
&::after {
right: 0;
border-right-color: var(--border);
}
}
+444
View File
@@ -0,0 +1,444 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { Chatbot } from "./Chatbot";
import { Playbook } from "./Playbook";
import { Models } from "./Models";
import { Settings } from "./Settings";
import { Memory } from "./Memory";
import { Logs } from "./Logs";
import { API_BASE } from "./config";
function timeAgo(epochSeconds) {
const diff = Math.floor(Date.now() / 1000) - epochSeconds;
if (diff < 60) return "just now";
if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
if (diff < 604800) return `${Math.floor(diff / 86400)}d ago`;
return new Date(epochSeconds * 1000).toLocaleDateString();
}
function App() {
const [currentPage, setCurrentPage] = useState("chatbot");
const [status, setStatus] = useState("Checking Synapse...");
const [version, setVersion] = useState("");
const [ollamaStatus, setOllamaStatus] = useState("checking");
const [ollamaBusy, setOllamaBusy] = useState(false);
const [showStatusTooltip, setShowStatusTooltip] = useState(false);
const [activeConversationId, setActiveConversationId] = useState(() => crypto.randomUUID());
const [isModelPulling, setIsModelPulling] = useState(false);
const [conversations, setConversations] = useState([]);
const [search, setSearch] = useState("");
const [hoveredConvId, setHoveredConvId] = useState(null);
const searchDebounce = useRef(null);
const loadStatus = () => {
fetch(`${API_BASE}/status`)
.then(r => r.json())
.then(d => {
setStatus(d.status ?? "Unknown");
setVersion(d.version ?? "");
setOllamaStatus(d.ollama ?? "unavailable");
})
.catch(() => {
setStatus("Offline");
setOllamaStatus("unavailable");
});
};
// Manual AI control — Ollama does not auto-start with the app.
const toggleOllama = async () => {
const action = ollamaStatus === "running" ? "stop" : "start";
setOllamaBusy(true);
try {
await fetch(`${API_BASE}/ollama/${action}`, { method: "POST" });
} catch (e) {
console.error("Ollama toggle failed:", e);
}
setOllamaBusy(false);
loadStatus();
};
const loadConversations = useCallback(async (q = "") => {
try {
const url = q.trim()
? `${API_BASE}/conversations?q=${encodeURIComponent(q.trim())}`
: `${API_BASE}/conversations`;
const response = await fetch(url);
if (response.ok) {
const data = await response.json();
setConversations(data.conversations || []);
}
} catch (error) {
console.error("Failed to load conversations:", error);
}
}, []);
useEffect(() => {
loadStatus();
const interval = setInterval(loadStatus, 5000);
return () => clearInterval(interval);
}, []);
useEffect(() => {
let cancelled = false;
fetch(`${API_BASE}/conversations`)
.then(r => r.ok ? r.json() : null)
.then(data => {
if (cancelled || !data) return;
setConversations(data.conversations || []);
})
.catch(err => console.error("Failed to load conversations:", err));
return () => { cancelled = true; };
}, []);
const handleSearch = (e) => {
const q = e.target.value;
setSearch(q);
clearTimeout(searchDebounce.current);
searchDebounce.current = setTimeout(() => loadConversations(q), 300);
};
const selectConversation = (id) => {
setActiveConversationId(id);
setCurrentPage("chatbot");
};
const startNewChat = () => {
setActiveConversationId(crypto.randomUUID());
setCurrentPage("chatbot");
};
const renameConversation = async (e, conv) => {
e.stopPropagation();
const current = conv.title || conv.preview || "";
const next = window.prompt("Rename conversation:", current);
if (next == null) return;
const title = next.trim();
if (!title || title === current) return;
try {
const response = await fetch(`${API_BASE}/conversations/${conv.id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title }),
});
if (response.ok) loadConversations(search);
} catch (error) {
console.error("Failed to rename conversation:", error);
}
};
const deleteConversation = async (e, conversationId) => {
e.stopPropagation();
if (!window.confirm("Delete this conversation?")) return;
try {
const response = await fetch(`${API_BASE}/conversations/${conversationId}`, { method: "DELETE" });
if (response.ok) {
if (activeConversationId === conversationId) {
setActiveConversationId(crypto.randomUUID());
}
loadConversations(search);
}
} catch (error) {
console.error("Failed to delete conversation:", error);
}
};
const navItems = [
{ key: "chatbot", label: "💬 Chat" },
{ key: "playbook", label: "📖 Playbooks" },
{ key: "models", label: "🤖 Models", badge: isModelPulling },
{ key: "memory", label: "🧠 Memory" },
{ key: "logs", label: "📜 Logs" },
{ key: "settings", label: "⚙️ Settings" },
];
return (
<div style={{ background: "#111", color: "#eee", height: "100vh", overflow: "hidden", fontFamily: "system-ui", display: "flex" }}>
{/* Sidebar */}
<aside style={{
width: "260px",
flexShrink: 0,
background: "#0a0a0a",
borderRight: "1px solid #333",
display: "flex",
flexDirection: "column",
minHeight: 0,
}}>
{/* Top cell: brand + nav */}
<div style={{
padding: "1.25rem 1rem 1rem",
borderBottom: "1px solid #1f1f1f",
display: "flex",
flexDirection: "column",
alignItems: "center",
gap: "0.75rem",
flexShrink: 0,
}}>
<img src="/n small.png" alt="Logo" style={{ width: "48px", height: "48px", objectFit: "contain", borderRadius: "8px" }} />
<h1 style={{ fontSize: "1rem", margin: 0, color: "#007acc", textAlign: "center" }}>NexusOS</h1>
{version && (
<span style={{ fontSize: "0.7rem", color: "#666", marginTop: "-0.5rem", letterSpacing: "0.02em" }}>v{version}</span>
)}
{/* Status Indicator */}
<div style={{ position: "relative" }}>
<div
style={{
width: "8px",
height: "8px",
borderRadius: "50%",
background: status === "Offline" || ollamaStatus === "unavailable" ? "#f44336"
: ollamaStatus === "running" ? "#4caf50" : "#ff9800",
cursor: "pointer",
transition: "all 0.3s"
}}
onMouseEnter={() => {
loadStatus();
setShowStatusTooltip(true);
}}
onMouseLeave={() => setShowStatusTooltip(false)}
title="Hover to refresh"
/>
{showStatusTooltip && (
<div style={{
position: "absolute",
top: "16px",
left: "50%",
transform: "translateX(-50%)",
background: "#1a1a1a",
border: "1px solid #333",
borderRadius: "6px",
padding: "0.6rem 0.8rem",
fontSize: "0.8rem",
whiteSpace: "nowrap",
zIndex: 1000,
boxShadow: "0 4px 12px rgba(0,0,0,0.5)"
}}>
<div style={{ marginBottom: "0.3rem", color: status === "Offline" ? "#f44336" : "#4caf50" }}>
Synapse: <strong>{status}</strong>
</div>
<div style={{ color: ollamaStatus === "unavailable" ? "#f44336" : ollamaStatus === "running" ? "#4caf50" : "#aaa" }}>
Ollama: <strong>{ollamaStatus}</strong>
</div>
</div>
)}
</div>
{/* Manual AI start/stop — Ollama is off until the user turns it on */}
<button
onClick={toggleOllama}
disabled={ollamaBusy || ollamaStatus === "unavailable" || status === "Offline"}
title={ollamaStatus === "unavailable" ? "Ollama binary not found" : "Start or stop the AI"}
style={{
width: "100%",
padding: "0.5rem 0.75rem",
background: ollamaStatus === "running" ? "#2a1a1a" : "#152a15",
color: ollamaStatus === "running" ? "#ff8a80" : "#8aff8a",
border: "1px solid " + (ollamaStatus === "running" ? "#5a2a2a" : "#2a5a2a"),
borderRadius: "8px",
cursor: (ollamaBusy || ollamaStatus === "unavailable" || status === "Offline") ? "not-allowed" : "pointer",
fontSize: "0.8rem",
opacity: (ollamaStatus === "unavailable" || status === "Offline") ? 0.5 : 1,
}}
>
{/* Naming the phase matters: nearly all of the wait is the model
being read off disk (GBs), not the server booting. "…" for a
minute reads as hung. */}
{ollamaBusy ? (ollamaStatus === "running" ? "Stopping…" : "Loading model…")
: ollamaStatus === "running" ? "⏹ Stop AI" : "▶ Start AI"}
</button>
<nav style={{ display: "flex", flexDirection: "column", gap: "0.4rem", width: "100%", marginTop: "0.25rem" }}>
{navItems.map(item => (
<button
key={item.key}
onClick={() => setCurrentPage(item.key)}
style={{
padding: "0.65rem 0.85rem",
background: currentPage === item.key ? "#007acc" : "#161616",
color: "#fff",
border: "1px solid " + (currentPage === item.key ? "#0099ff" : "#2a2a2a"),
borderRadius: "8px",
cursor: "pointer",
fontSize: "0.85rem",
textAlign: "left",
transition: "all 0.15s",
display: "flex",
alignItems: "center",
justifyContent: "space-between",
}}
>
{item.label}
{item.badge && (
<span style={{
width: "8px",
height: "8px",
borderRadius: "50%",
background: "#28a745",
flexShrink: 0,
animation: "pulse 1.2s ease-in-out infinite",
}} />
)}
</button>
))}
</nav>
</div>
{/* Bottom cell: conversation list */}
<div style={{
flexGrow: 1,
minHeight: 0,
display: "flex",
flexDirection: "column",
padding: "0.75rem 0.75rem 0.75rem",
}}>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "0.5rem", flexShrink: 0 }}>
<span style={{ fontSize: "0.75rem", color: "#888", textTransform: "uppercase", letterSpacing: "0.05em" }}>Chats</span>
<button
onClick={startNewChat}
title="New chat"
style={{
padding: "0.2rem 0.55rem",
background: "#161616",
color: "#bbb",
border: "1px solid #2a2a2a",
borderRadius: "6px",
cursor: "pointer",
fontSize: "0.75rem",
}}
>
+ New
</button>
</div>
<input
type="text"
placeholder="Search..."
value={search}
onChange={handleSearch}
style={{
width: "100%",
padding: "0.45rem 0.6rem",
background: "#161616",
color: "#eee",
border: "1px solid #2a2a2a",
borderRadius: "6px",
marginBottom: "0.5rem",
boxSizing: "border-box",
fontSize: "0.8rem",
flexShrink: 0,
}}
/>
<div style={{ flexGrow: 1, overflowY: "auto", minHeight: 0 }}>
{conversations.length === 0 ? (
<p style={{ color: "#555", fontSize: "0.8rem", textAlign: "center", marginTop: "0.5rem" }}>
{search ? "No matches." : "No conversations yet."}
</p>
) : (
conversations.map((conv) => {
const isActive = activeConversationId === conv.id;
const isHover = hoveredConvId === conv.id;
return (
<div
key={conv.id}
onClick={() => selectConversation(conv.id)}
onMouseEnter={() => setHoveredConvId(conv.id)}
onMouseLeave={() => setHoveredConvId(null)}
style={{
padding: "0.55rem 0.65rem",
marginBottom: "0.3rem",
borderRadius: "6px",
cursor: "pointer",
background: isActive ? "#1c2a3a" : (isHover ? "#161616" : "transparent"),
border: `1px solid ${isActive ? "#2a4a6a" : "transparent"}`,
display: "flex",
alignItems: "center",
gap: "0.4rem",
}}
>
<div style={{ flexGrow: 1, minWidth: 0 }}>
<div style={{
fontSize: "0.82rem",
color: isActive ? "#eee" : "#ccc",
whiteSpace: "nowrap",
overflow: "hidden",
textOverflow: "ellipsis",
}}>
{conv.title || conv.preview || "Conversation"}
</div>
<div style={{ fontSize: "0.7rem", color: "#666", marginTop: "0.1rem" }}>
{timeAgo(conv.timestamp)}
</div>
</div>
{isHover && (
<>
<button
onClick={(e) => renameConversation(e, conv)}
title="Rename"
style={{
padding: "0.15rem 0.4rem",
background: "transparent",
color: "#888",
border: "1px solid #333",
borderRadius: "4px",
cursor: "pointer",
fontSize: "0.7rem",
flexShrink: 0,
}}
>
</button>
<button
onClick={(e) => deleteConversation(e, conv.id)}
title="Delete"
style={{
padding: "0.15rem 0.4rem",
background: "transparent",
color: "#888",
border: "1px solid #333",
borderRadius: "4px",
cursor: "pointer",
fontSize: "0.7rem",
flexShrink: 0,
}}
>
</button>
</>
)}
</div>
);
})
)}
</div>
</div>
</aside>
{/* Main Content */}
<main style={{ flexGrow: 1, padding: "1.5rem", display: "flex", flexDirection: "column", overflowY: "auto", minHeight: 0, minWidth: 0 }}>
{/* Models stays mounted so active downloads survive page navigation */}
<div style={{
display: currentPage === "models" ? "flex" : "none",
flexDirection: "column",
flexGrow: 1,
minHeight: 0,
}}>
<Models onPullStateChange={setIsModelPulling} />
</div>
{currentPage === "chatbot" && (
<Chatbot
conversationId={activeConversationId}
setConversationId={setActiveConversationId}
onConversationChanged={() => loadConversations(search)}
/>
)}
{currentPage === "playbook" && <Playbook />}
{currentPage === "memory" && <Memory />}
{currentPage === "logs" && <Logs />}
{currentPage === "settings" && <Settings />}
</main>
</div>
);
}
export default App;
+481
View File
@@ -0,0 +1,481 @@
import { useState, useRef, useEffect } from "react";
import { API_BASE } from "./config";
import { Markdown } from "./Markdown";
export function Chatbot({ conversationId, setConversationId, onConversationChanged }) {
const [messages, setMessages] = useState([]);
const [input, setInput] = useState("");
const [loading, setLoading] = useState(false);
const [modelList, setModelList] = useState([]);
const [selectedModel, setSelectedModel] = useState(""); // "" = auto
const [autoModel, setAutoModel] = useState(null);
const [showPicker, setShowPicker] = useState(false);
const [copiedIdx, setCopiedIdx] = useState(null);
const [lastStats, setLastStats] = useState(null);
const [memoryToast, setMemoryToast] = useState(null);
const abortRef = useRef(null);
const messagesEndRef = useRef(null);
const pickerRef = useRef(null);
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
}, [messages]);
useEffect(() => {
if (!conversationId) return;
if (abortRef.current) abortRef.current.abort();
let cancelled = false;
setLastStats(null);
fetch(`${API_BASE}/conversations/${conversationId}`)
.then(r => r.ok ? r.json() : null)
.then(data => {
if (cancelled) return;
setMessages(data?.messages?.map(m => ({ role: m.role, content: m.content })) || []);
})
.catch(() => { if (!cancelled) setMessages([]); });
return () => { cancelled = true; };
}, [conversationId]);
useEffect(() => {
Promise.all([
fetch(`${API_BASE}/models`).then(r => r.ok ? r.json() : null),
fetch(`${API_BASE}/settings`).then(r => r.ok ? r.json() : null),
]).then(([models, settings]) => {
if (models?.models) setModelList(models.models);
if (models?.selected) setAutoModel(models.selected);
if (settings) setSelectedModel(settings.model || "");
}).catch(() => {});
}, []);
useEffect(() => {
if (!showPicker) return;
const handle = (e) => {
if (pickerRef.current && !pickerRef.current.contains(e.target)) setShowPicker(false);
};
document.addEventListener("mousedown", handle);
return () => document.removeEventListener("mousedown", handle);
}, [showPicker]);
const setModelChoice = async (model) => {
setSelectedModel(model);
setShowPicker(false);
try {
await fetch(`${API_BASE}/settings`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ model }),
});
} catch { /* persisting the model choice is best-effort */ }
};
const startNewChat = () => {
if (abortRef.current) abortRef.current.abort();
setInput("");
setLoading(false);
setLastStats(null);
setConversationId(crypto.randomUUID());
};
const sendMessage = async () => {
if (!input.trim() || loading) return;
const userMessage = input.trim();
setInput("");
// Add user message
setMessages(prev => [...prev, { role: "user", content: userMessage }]);
// Prepare assistant placeholder
const assistantIndex = messages.length + 1;
setMessages(prev => [...prev, { role: "assistant", content: "" }]);
setLoading(true);
// Abort previous stream if still open
if (abortRef.current) abortRef.current.abort();
const controller = new AbortController();
abortRef.current = controller;
try {
// Exclude the empty assistant placeholder that was just appended
const historySnapshot = messages.filter(m => m.content.trim() !== "");
const response = await fetch(`${API_BASE}/chat/stream`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
message: userMessage,
conversation_id: conversationId,
history: historySnapshot.map(m => ({ role: m.role, content: m.content })),
}),
signal: controller.signal,
});
if (!response.ok) {
const text = await response.text();
updateAssistant(assistantIndex, `Error: ${text}`);
setLoading(false);
return;
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
let pendingEventType = null;
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop();
for (const line of lines) {
if (line.startsWith("event: ")) {
pendingEventType = line.slice(7).trim();
continue;
}
if (line.startsWith("data: ")) {
const payload = line.slice(6);
if (!payload.trim()) { pendingEventType = null; continue; }
if (pendingEventType === "meta") {
try {
const stats = JSON.parse(payload);
setLastStats(stats);
// Tag this message with the model that answered
if (stats.model) {
setMessages(prev => {
const updated = [...prev];
updated[assistantIndex] = { ...updated[assistantIndex], model: stats.model };
return updated;
});
}
} catch { /* ignore */ }
pendingEventType = null;
continue;
}
if (pendingEventType === "memory") {
try {
const mem = JSON.parse(payload);
setMemoryToast(mem);
setTimeout(() => setMemoryToast(null), 5000);
} catch { /* ignore */ }
pendingEventType = null;
continue;
}
if (pendingEventType === "done") {
// Answer is complete; re-enable input while the backend finishes
// slow post-processing (title, memory) on the still-open stream.
setLoading(false);
pendingEventType = null;
continue;
}
if (pendingEventType === "title") {
if (onConversationChanged) onConversationChanged();
pendingEventType = null;
continue;
}
if (pendingEventType === "error") {
try {
const err = JSON.parse(payload);
updateAssistant(assistantIndex, `Error: ${err.detail || payload}`);
} catch {
updateAssistant(assistantIndex, `Error: ${payload}`);
}
pendingEventType = null;
setLoading(false);
return;
}
pendingEventType = null;
let token = payload;
try { token = JSON.parse(payload); } catch { /* plain text fallback */ }
setMessages(prev => {
const updated = [...prev];
updated[assistantIndex] = {
...updated[assistantIndex],
content: (updated[assistantIndex].content || "") + token,
};
return updated;
});
}
}
}
} catch (err) {
if (err.name !== "AbortError") {
updateAssistant(assistantIndex, `Connection error: ${err.message}`);
}
} finally {
setLoading(false);
if (onConversationChanged) onConversationChanged();
}
};
const updateAssistant = (index, text) => {
setMessages(prev => {
const updated = [...prev];
updated[index] = { ...updated[index], content: text };
return updated;
});
};
const handleKeyDown = (e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
sendMessage();
}
};
return (
<div style={{ display: "flex", flexDirection: "column", height: "100%", flexGrow: 1 }}>
{memoryToast && (
<div style={{
position: "fixed", bottom: "1.5rem", right: "1.5rem",
background: "#1a1a2e", border: "1px solid #7c3aed",
borderRadius: "8px", padding: "0.6rem 1rem",
fontSize: "0.85rem", color: "#c4b5fd",
boxShadow: "0 4px 12px rgba(0,0,0,0.5)", zIndex: 9999,
maxWidth: "320px"
}}>
🧠 <strong>Memory saved</strong> [{memoryToast.section}]<br />
<span style={{ color: "#aaa", fontSize: "0.8rem" }}>{memoryToast.text}</span>
</div>
)}
<div style={{
flexGrow: 1,
background: "#161616",
border: "1px solid #333",
borderRadius: "12px",
padding: "1rem",
display: "flex",
flexDirection: "column",
overflow: "hidden"
}}>
{/* Header */}
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "0.75rem" }}>
<div style={{ display: "flex", alignItems: "center", gap: "0.75rem" }}>
<span style={{ fontSize: "0.85rem", color: "#555" }}>
{messages.length === 0 ? "New conversation" : `${Math.ceil(messages.length / 2)} exchange${messages.length > 2 ? "s" : ""}`}
</span>
<div ref={pickerRef} style={{ position: "relative" }}>
<button
onClick={() => setShowPicker(p => !p)}
style={{
fontSize: "0.7rem",
color: "#7aa",
background: showPicker ? "#1e2e2e" : "#1a2a2a",
border: "1px solid #2a4a4a",
borderRadius: "4px",
padding: "0.15rem 0.5rem",
cursor: "pointer",
letterSpacing: "0.03em",
display: "flex",
alignItems: "center",
gap: "0.3rem",
}}
>
{!selectedModel && <span style={{ color: "#4a6a6a" }}>auto ·</span>}
{selectedModel || autoModel || "no model"}
<span style={{ color: "#4a7a7a", fontSize: "0.6rem" }}></span>
</button>
{showPicker && (
<div style={{
position: "absolute",
top: "calc(100% + 4px)",
left: 0,
background: "#1a1a1a",
border: "1px solid #333",
borderRadius: "8px",
zIndex: 100,
minWidth: "200px",
maxHeight: "240px",
overflowY: "auto",
boxShadow: "0 4px 16px rgba(0,0,0,0.6)",
}}>
<div
onClick={() => setModelChoice("")}
style={{
padding: "0.55rem 0.85rem",
cursor: "pointer",
fontSize: "0.8rem",
color: !selectedModel ? "#7aa" : "#888",
background: !selectedModel ? "#1a2a2a" : "transparent",
borderBottom: "1px solid #262626",
display: "flex",
justifyContent: "space-between",
alignItems: "center",
}}
>
<span>Auto <span style={{ color: "#445", fontSize: "0.7rem" }}>{autoModel ? `(${autoModel})` : ""}</span></span>
{!selectedModel && <span></span>}
</div>
{modelList.map(m => (
<div
key={m}
onClick={() => setModelChoice(m)}
style={{
padding: "0.55rem 0.85rem",
cursor: "pointer",
fontSize: "0.8rem",
color: selectedModel === m ? "#7aa" : "#ccc",
background: selectedModel === m ? "#1a2a2a" : "transparent",
display: "flex",
justifyContent: "space-between",
alignItems: "center",
}}
>
<span>{m}</span>
{selectedModel === m && <span></span>}
</div>
))}
</div>
)}
</div>
{lastStats && (
<span style={{
fontSize: "0.7rem",
color: "#888",
background: "#1a1a1a",
border: "1px solid #2a2a2a",
borderRadius: "4px",
padding: "0.15rem 0.45rem",
}}>
{lastStats.tokens} tok · {lastStats.elapsed_s}s
{lastStats.tokens_per_s > 0 ? ` · ${lastStats.tokens_per_s} t/s` : ""}
</span>
)}
</div>
<button
onClick={startNewChat}
disabled={loading}
style={{
padding: "0.4rem 0.85rem",
background: "#222",
color: "#aaa",
border: "1px solid #444",
borderRadius: "6px",
cursor: loading ? "default" : "pointer",
fontSize: "0.8rem",
opacity: loading ? 0.5 : 1,
}}
>
New Chat
</button>
</div>
<div style={{
flexGrow: 1,
overflowY: "auto",
marginBottom: "1rem",
paddingRight: "0.5rem"
}}>
{messages.length === 0 ? (
<div style={{ color: "#666", textAlign: "center", paddingTop: "2rem" }}>
<p>Start a conversation with the chatbot...</p>
</div>
) : (
messages.map((msg, idx) => (
<div
key={idx}
style={{
marginBottom: "1rem",
display: "flex",
flexDirection: "column",
alignItems: msg.role === "user" ? "flex-end" : "flex-start",
}}
>
<div
style={{
maxWidth: msg.role === "user" ? "70%" : "90%",
width: msg.role === "assistant" ? "100%" : undefined,
padding: "0.9rem",
borderRadius: "10px",
background: msg.role === "user" ? "#007acc" : "#262626",
color: "#eee",
wordWrap: "break-word",
boxSizing: "border-box",
}}
>
{msg.role === "user"
? <span style={{ whiteSpace: "pre-wrap" }}>{msg.content}</span>
: msg.content
? <Markdown content={msg.content} />
: <span style={{ color: "#aaa" }}>Thinking...</span>
}
</div>
{msg.content && (
<button
onClick={() => {
navigator.clipboard.writeText(msg.content).then(() => {
setCopiedIdx(idx);
setTimeout(() => setCopiedIdx(null), 1500);
});
}}
style={{
marginTop: "0.25rem",
padding: "0.15rem 0.5rem",
fontSize: "0.7rem",
color: copiedIdx === idx ? "#4caf50" : "#555",
background: "transparent",
border: "none",
cursor: "pointer",
}}
>
{copiedIdx === idx ? "Copied!" : "Copy"}
</button>
)}
</div>
))
)}
<div ref={messagesEndRef} />
</div>
<div style={{ display: "flex", gap: "0.75rem", alignItems: "flex-end" }}>
<textarea
value={input}
onChange={e => setInput(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Type your message... (Shift+Enter for new line)"
disabled={loading}
rows={3}
style={{
flexGrow: 1,
padding: "0.9rem",
background: "#222",
color: "#eee",
border: "1px solid #333",
borderRadius: "10px",
fontFamily: "system-ui",
resize: "none",
opacity: loading ? 0.6 : 1
}}
/>
<button
onClick={sendMessage}
disabled={loading || !input.trim()}
style={{
padding: "0.9rem 1.5rem",
background: loading || !input.trim() ? "#555" : "#007acc",
color: "#fff",
border: "none",
borderRadius: "8px",
cursor: loading || !input.trim() ? "default" : "pointer",
opacity: loading || !input.trim() ? 0.6 : 1,
}}
>
Send
</button>
</div>
</div>
</div>
);
}
+93
View File
@@ -0,0 +1,93 @@
import { useEffect, useRef, useState } from "react";
import { API_BASE } from "./config";
export function Logs() {
const [tabs, setTabs] = useState([]);
const [active, setActive] = useState(null);
const [content, setContent] = useState("");
const [follow, setFollow] = useState(true);
const preRef = useRef(null);
// Load the available log names once.
useEffect(() => {
fetch(`${API_BASE}/logs`)
.then(r => r.json())
.then(d => {
setTabs(d.logs || []);
setActive(prev => prev ?? (d.logs || [])[0] ?? null);
})
.catch(() => setTabs([]));
}, []);
// Poll the active log every 2s.
useEffect(() => {
if (!active) return;
let cancelled = false;
const load = () => {
fetch(`${API_BASE}/logs/${active}`)
.then(r => r.json())
.then(d => { if (!cancelled) setContent(d.content || (d.missing ? "(no log file yet)" : "")); })
.catch(() => { if (!cancelled) setContent("(failed to load log)"); });
};
load();
const id = setInterval(load, 2000);
return () => { cancelled = true; clearInterval(id); };
}, [active]);
// Auto-scroll to bottom when following.
useEffect(() => {
if (follow && preRef.current) preRef.current.scrollTop = preRef.current.scrollHeight;
}, [content, follow]);
return (
<div style={{ display: "flex", flexDirection: "column", flexGrow: 1, minHeight: 0 }}>
<div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: "0.75rem" }}>
<div style={{ display: "flex", gap: "0.4rem", flexWrap: "wrap" }}>
{tabs.map(name => (
<button
key={name}
onClick={() => setActive(name)}
style={{
padding: "0.4rem 0.8rem",
background: active === name ? "#007acc" : "#161616",
color: "#fff",
border: "1px solid " + (active === name ? "#0099ff" : "#2a2a2a"),
borderRadius: "6px",
cursor: "pointer",
fontSize: "0.8rem",
textTransform: "capitalize",
}}
>
{name}
</button>
))}
</div>
<label style={{ fontSize: "0.75rem", color: "#888", display: "flex", alignItems: "center", gap: "0.35rem", cursor: "pointer" }}>
<input type="checkbox" checked={follow} onChange={e => setFollow(e.target.checked)} />
Follow
</label>
</div>
<pre
ref={preRef}
style={{
flexGrow: 1,
minHeight: 0,
overflow: "auto",
background: "#0a0a0a",
border: "1px solid #2a2a2a",
borderRadius: "8px",
padding: "0.9rem",
margin: 0,
fontSize: "0.78rem",
lineHeight: 1.45,
color: "#cfcfcf",
fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace",
whiteSpace: "pre-wrap",
wordBreak: "break-word",
}}
>
{content || "(empty)"}
</pre>
</div>
);
}
+208
View File
@@ -0,0 +1,208 @@
import { useState } from "react";
// Parse content into an array of {type, value, lang, streaming} blocks.
// Handles:
// - ```lang\ncode``` (well-formed)
// - ```code``` (no language, no newline — model formatting bug)
// - ```lang\ncode (unclosed — streaming in progress)
function parseBlocks(content) {
const blocks = [];
let i = 0;
while (i < content.length) {
const fenceStart = content.indexOf("```", i);
if (fenceStart === -1) {
if (i < content.length) blocks.push({ type: "text", value: content.slice(i) });
break;
}
if (fenceStart > i) blocks.push({ type: "text", value: content.slice(i, fenceStart) });
let j = fenceStart + 3;
let lang = "";
// Language specifier is valid only when word-chars are followed by a newline.
// If there's no newline (e.g. ```pythonprint(...)) treat everything as code.
const langMatch = content.slice(j).match(/^(\w+)(\r?\n)/);
if (langMatch) {
lang = langMatch[1];
j += langMatch[0].length;
} else if (/^\r?\n/.test(content.slice(j))) {
j += content[j] === "\r" ? 2 : 1;
}
// else: no newline — leave j as-is, lang stays ""
const closeIdx = content.indexOf("```", j);
if (closeIdx === -1) {
blocks.push({ type: "code", lang, value: content.slice(j), streaming: true });
i = content.length;
} else {
blocks.push({ type: "code", lang, value: content.slice(j, closeIdx).replace(/\n$/, ""), streaming: false });
i = closeIdx + 3;
}
}
return blocks;
}
export function Markdown({ content }) {
if (!content) return null;
const blocks = parseBlocks(content);
return (
<div style={{ lineHeight: "1.6" }}>
{blocks.map((block, i) =>
block.type === "code"
? <CodeBlock key={i} lang={block.lang} value={block.value} streaming={block.streaming} />
: <TextBlock key={i} text={block.value} />
)}
</div>
);
}
function CodeBlock({ lang, value, streaming }) {
const [copied, setCopied] = useState(false);
const copy = () => {
navigator.clipboard.writeText(value.trimEnd()).then(() => {
setCopied(true);
setTimeout(() => setCopied(false), 1500);
});
};
return (
<div style={{
background: "#0d0d0d",
border: "1px solid #2a2a2a",
borderRadius: "6px",
margin: "0.5rem 0",
overflow: "hidden",
}}>
<div style={{
display: "flex",
justifyContent: "space-between",
alignItems: "center",
padding: "0.3rem 0.75rem",
background: "#161616",
borderBottom: "1px solid #2a2a2a",
}}>
<span style={{ fontSize: "0.75rem", color: "#666", fontFamily: "monospace" }}>
{lang || "code"}
{streaming && <span style={{ color: "#444", marginLeft: "0.5rem" }}></span>}
</span>
{!streaming && (
<button onClick={copy} style={{
background: "transparent",
border: "none",
color: copied ? "#4caf50" : "#555",
cursor: "pointer",
fontSize: "0.75rem",
padding: "0.1rem 0.3rem",
}}>
{copied ? "Copied!" : "Copy"}
</button>
)}
</div>
<pre style={{
padding: "0.75rem 1rem",
overflowX: "auto",
fontSize: "0.85rem",
lineHeight: "1.5",
margin: 0,
fontFamily: "monospace",
}}>
<code>{value.trimEnd()}</code>
</pre>
</div>
);
}
function TextBlock({ text }) {
const lines = text.split("\n");
const elements = [];
let i = 0;
while (i < lines.length) {
const line = lines[i];
const hMatch = line.match(/^(#{1,3})\s+(.+)/);
if (hMatch) {
const level = hMatch[1].length;
const sizes = { 1: "1.2rem", 2: "1.05rem", 3: "0.95rem" };
elements.push(
<div key={i} style={{ fontWeight: "700", fontSize: sizes[level], margin: "0.6rem 0 0.2rem", color: "#fff" }}>
{inlineMarkdown(hMatch[2])}
</div>
);
i++; continue;
}
if (/^[-*]\s+/.test(line)) {
const items = [];
while (i < lines.length && /^[-*]\s+/.test(lines[i])) {
items.push(<li key={i}>{inlineMarkdown(lines[i].replace(/^[-*]\s+/, ""))}</li>);
i++;
}
elements.push(<ul key={`ul-${i}`} style={{ paddingLeft: "1.25rem", margin: "0.25rem 0" }}>{items}</ul>);
continue;
}
if (/^\d+\.\s+/.test(line)) {
const items = [];
while (i < lines.length && /^\d+\.\s+/.test(lines[i])) {
items.push(<li key={i}>{inlineMarkdown(lines[i].replace(/^\d+\.\s+/, ""))}</li>);
i++;
}
elements.push(<ol key={`ol-${i}`} style={{ paddingLeft: "1.25rem", margin: "0.25rem 0" }}>{items}</ol>);
continue;
}
if (/^---+$/.test(line.trim())) {
elements.push(<hr key={i} style={{ border: "none", borderTop: "1px solid #333", margin: "0.5rem 0" }} />);
i++; continue;
}
if (line.trim() === "") {
elements.push(<div key={i} style={{ height: "0.4rem" }} />);
i++; continue;
}
elements.push(<div key={i}>{inlineMarkdown(line)}</div>);
i++;
}
return <>{elements}</>;
}
function inlineMarkdown(text) {
const parts = [];
const re = /(\*\*(.+?)\*\*|\*(.+?)\*|`([^`]+)`)/g;
let last = 0;
let m;
while ((m = re.exec(text)) !== null) {
if (m.index > last) parts.push(text.slice(last, m.index));
if (m[2] !== undefined) {
parts.push(<strong key={m.index}>{m[2]}</strong>);
} else if (m[3] !== undefined) {
parts.push(<em key={m.index}>{m[3]}</em>);
} else if (m[4] !== undefined) {
parts.push(
<code key={m.index} style={{
background: "#1e1e1e",
border: "1px solid #333",
borderRadius: "3px",
padding: "0.1rem 0.35rem",
fontSize: "0.85em",
fontFamily: "monospace",
}}>
{m[4]}
</code>
);
}
last = m.index + m[0].length;
}
if (last < text.length) parts.push(text.slice(last));
return parts.length === 1 && typeof parts[0] === "string" ? parts[0] : parts;
}
+497
View File
@@ -0,0 +1,497 @@
import { useEffect, useState, useCallback } from "react";
import { API_BASE } from "./config";
const DEFAULT_SECTIONS = ["Instructions", "Identity", "Career", "Projects", "Preferences"];
function groupBySection(items) {
const map = {};
for (const item of items) {
const sec = item.section || "General";
if (!map[sec]) map[sec] = [];
map[sec].push(item);
}
return map;
}
function indentLevelOf(text) {
const m = text.match(/^( *)/);
return Math.floor((m ? m[0].length : 0) / 2);
}
// Collapse a section's items into top-level "groups": each group is a parent
// (indent 0) plus its consecutive indented children.
function computeGroups(sectionItems) {
const groups = [];
const groupIndexById = {};
for (const item of sectionItems) {
const lvl = indentLevelOf(item.text);
if (lvl === 0 || groups.length === 0) {
groups.push([item]);
} else {
groups[groups.length - 1].push(item);
}
groupIndexById[item.id] = groups.length - 1;
}
return { groups, groupIndexById };
}
export function Memory() {
const [items, setItems] = useState([]);
const [editing, setEditing] = useState(null); // { id, section, text } or null
const [adding, setAdding] = useState(null); // { section } for inline new-item form
const [newSection, setNewSection] = useState("");
const [showNewSection, setShowNewSection] = useState(false);
const [message, setMessage] = useState("");
const [draggingId, setDraggingId] = useState(null);
const [dragOver, setDragOver] = useState(null); // { id, position: "before"|"after" }
const loadItems = useCallback(async () => {
try {
const res = await fetch(`${API_BASE}/memory`);
const data = res.ok ? await res.json() : { items: [] };
setItems(data.items || []);
} catch {
setItems([]);
}
}, []);
useEffect(() => { loadItems(); }, [loadItems]);
const flash = (msg) => { setMessage(msg); setTimeout(() => setMessage(""), 3000); };
const saveNew = async (section, text) => {
// Split on newlines so a pasted list becomes one memory per line (leading
// spaces kept for nesting). Direct write — no LLM curator, saves every line.
const lines = text.split("\n").map(l => l.replace(/\s+$/, "")).filter(l => l.trim());
if (!lines.length) return;
let ok = 0;
for (const line of lines) {
const res = await fetch(`${API_BASE}/memory`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ section, text: line }),
});
if (res.ok) ok++;
}
if (ok) { loadItems(); setAdding(null); flash(ok === 1 ? "Saved." : `Saved ${ok} items.`); }
else flash("Save failed.");
};
const saveEdit = async (id, section, text) => {
const cleaned = text.replace(/\s+$/, "");
if (!cleaned.trim()) return;
const res = await fetch(`${API_BASE}/memory/${id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ section, text: cleaned }),
});
if (res.ok) { loadItems(); setEditing(null); flash("Updated."); }
else flash("Update failed.");
};
const deleteItem = async (id) => {
if (!window.confirm("Delete this item?")) return;
const res = await fetch(`${API_BASE}/memory/${id}`, { method: "DELETE" });
if (res.ok) { loadItems(); flash("Deleted."); }
else flash("Delete failed.");
};
const reorderSection = async (section, ids) => {
try {
const res = await fetch(`${API_BASE}/memory/reorder`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ section, ids }),
});
const result = await res.json();
if (!res.ok || result.ok === false) {
throw new Error("Memory reorder failed");
}
loadItems();
} catch (err) {
setMessage(err.message);
}
};
const moveItem = (id, direction) => {
const item = items.find(i => i.id === id);
if (!item) return;
const section = item.section || "General";
const sectionItems = items.filter(i => (i.section || "General") === section);
const { groups, groupIndexById } = computeGroups(sectionItems);
const lvl = indentLevelOf(item.text);
if (lvl === 0) {
// Swap whole group with previous/next group
const gIdx = groupIndexById[id];
const tIdx = direction === "up" ? gIdx - 1 : gIdx + 1;
if (tIdx < 0 || tIdx >= groups.length) return;
const newGroups = [...groups];
[newGroups[gIdx], newGroups[tIdx]] = [newGroups[tIdx], newGroups[gIdx]];
reorderSection(section, newGroups.flat().map(i => i.id));
} else {
// Swap child with previous/next sibling within same group; never past the parent
const gIdx = groupIndexById[id];
const group = groups[gIdx];
const localIdx = group.findIndex(i => i.id === id);
const tLocal = direction === "up" ? localIdx - 1 : localIdx + 1;
if (tLocal <= 0 || tLocal >= group.length) return; // tLocal === 0 is the parent
const newGroup = [...group];
[newGroup[localIdx], newGroup[tLocal]] = [newGroup[tLocal], newGroup[localIdx]];
const newGroups = [...groups];
newGroups[gIdx] = newGroup;
reorderSection(section, newGroups.flat().map(i => i.id));
}
};
const onItemDragStart = (e, item) => {
setDraggingId(item.id);
e.dataTransfer.effectAllowed = "move";
try { e.dataTransfer.setData("text/plain", item.id); } catch { /* some browsers restrict */ }
};
const onItemDragOver = (e, targetItem, section) => {
if (!draggingId || draggingId === targetItem.id) return;
const dragged = items.find(i => i.id === draggingId);
if (!dragged || (dragged.section || "General") !== section) return;
const sectionItems = items.filter(i => (i.section || "General") === section);
const { groups, groupIndexById } = computeGroups(sectionItems);
const draggedLevel = indentLevelOf(dragged.text);
const targetGroupIdx = groupIndexById[targetItem.id];
const draggedGroupIdx = groupIndexById[dragged.id];
const rect = e.currentTarget.getBoundingClientRect();
const inUpperHalf = e.clientY < rect.top + rect.height / 2;
if (draggedLevel === 0) {
// Top-level drag: snap to group boundaries; ignore hover over own group
if (targetGroupIdx === draggedGroupIdx) {
if (dragOver) setDragOver(null);
return;
}
e.preventDefault();
e.dataTransfer.dropEffect = "move";
const targetGroup = groups[targetGroupIdx];
const isTargetParent = targetItem.id === targetGroup[0].id;
const position = (isTargetParent && inUpperHalf) ? "before" : "after";
if (dragOver?.kind !== "group" || dragOver?.section !== section || dragOver?.groupIdx !== targetGroupIdx || dragOver?.position !== position) {
setDragOver({ kind: "group", section, groupIdx: targetGroupIdx, position });
}
} else {
// Child drag: confined to its own parent group
if (targetGroupIdx !== draggedGroupIdx) {
if (dragOver) setDragOver(null);
return;
}
e.preventDefault();
e.dataTransfer.dropEffect = "move";
const targetGroup = groups[targetGroupIdx];
const isTargetParent = targetItem.id === targetGroup[0].id;
let position = inUpperHalf ? "before" : "after";
if (isTargetParent) position = "after"; // child can't go before its parent
if (dragOver?.kind !== "item" || dragOver?.section !== section || dragOver?.id !== targetItem.id || dragOver?.position !== position) {
setDragOver({ kind: "item", section, id: targetItem.id, position });
}
}
};
const onItemDrop = (e, targetItem, section) => {
e.preventDefault();
const dragged = items.find(i => i.id === draggingId);
if (!dragged || dragged.id === targetItem.id || (dragged.section || "General") !== section || !dragOver) {
setDraggingId(null);
setDragOver(null);
return;
}
const sectionItems = items.filter(i => (i.section || "General") === section);
const { groups, groupIndexById } = computeGroups(sectionItems);
const draggedLevel = indentLevelOf(dragged.text);
let block, anchorId, after;
if (draggedLevel === 0 && dragOver.kind === "group") {
block = groups[groupIndexById[dragged.id]];
const targetGroup = groups[dragOver.groupIdx];
anchorId = dragOver.position === "before" ? targetGroup[0].id : targetGroup[targetGroup.length - 1].id;
after = dragOver.position === "after";
} else if (draggedLevel > 0 && dragOver.kind === "item") {
block = [dragged];
anchorId = dragOver.id;
after = dragOver.position === "after";
} else {
setDraggingId(null);
setDragOver(null);
return;
}
const blockIds = new Set(block.map(b => b.id));
const remainder = sectionItems.filter(i => !blockIds.has(i.id));
let insertIdx = remainder.findIndex(i => i.id === anchorId);
if (insertIdx < 0) {
setDraggingId(null);
setDragOver(null);
return;
}
if (after) insertIdx += 1;
const newOrder = [...remainder.slice(0, insertIdx), ...block, ...remainder.slice(insertIdx)];
setDraggingId(null);
setDragOver(null);
reorderSection(section, newOrder.map(i => i.id));
};
const onItemDragEnd = () => {
setDraggingId(null);
setDragOver(null);
};
const addSection = () => {
const sec = newSection.trim();
if (!sec) return;
// Create a placeholder item to establish the section, then let user fill it
setAdding({ section: sec });
setNewSection("");
setShowNewSection(false);
};
const grouped = groupBySection(items);
const sections = Object.keys(grouped);
const inputStyle = {
background: "#1a1a1a",
color: "#eee",
border: "1px solid #444",
borderRadius: "6px",
padding: "0.4rem 0.6rem",
fontSize: "0.9rem",
width: "100%",
boxSizing: "border-box",
};
const btnStyle = (color = "#007acc") => ({
padding: "0.3rem 0.7rem",
background: color,
color: "#fff",
border: "none",
borderRadius: "6px",
cursor: "pointer",
fontSize: "0.8rem",
});
return (
<div style={{ flexGrow: 1 }}>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "1.25rem" }}>
<div>
<h2 style={{ margin: 0, fontSize: "1.1rem" }}>Memory</h2>
<p style={{ margin: "0.25rem 0 0", color: "#888", fontSize: "0.85rem" }}>
Facts injected into every conversation. Format mirrors your claude.md.
</p>
</div>
<button onClick={() => setShowNewSection(s => !s)} style={btnStyle()}>
+ New Section
</button>
</div>
{showNewSection && (
<div style={{ display: "flex", gap: "0.5rem", marginBottom: "1.25rem" }}>
<input
autoFocus
type="text"
placeholder="Section name (e.g. Health, Finance)"
value={newSection}
onChange={e => setNewSection(e.target.value)}
onKeyDown={e => { if (e.key === "Enter") addSection(); if (e.key === "Escape") setShowNewSection(false); }}
style={{ ...inputStyle, maxWidth: "320px" }}
/>
<button onClick={addSection} style={btnStyle()}>Add</button>
<button onClick={() => setShowNewSection(false)} style={btnStyle("#444")}>Cancel</button>
</div>
)}
{sections.length === 0 && !adding && (
<div style={{ color: "#666", fontSize: "0.9rem", marginTop: "2rem" }}>
No memory yet. Add a section to get started.
</div>
)}
{/* Render sections in claude.md style */}
{[...sections, ...(adding && !sections.includes(adding.section) ? [adding.section] : [])].map(section => (
<div key={section} style={{ marginBottom: "2rem" }}>
{/* ## Section Header */}
<div style={{ display: "flex", alignItems: "center", gap: "0.75rem", marginBottom: "0.5rem" }}>
<h3 style={{ margin: 0, fontSize: "1rem", color: "#4db8ff" }}>## {section}</h3>
<button
onClick={() => setAdding({ section })}
style={{ ...btnStyle("#2a3a2a"), border: "1px solid #3a5a3a", color: "#7dcc7d", fontSize: "0.75rem" }}
>
+ Add item
</button>
</div>
{/* Bullet items */}
{(() => {
const sectionItems = grouped[section] || [];
const { groups, groupIndexById } = computeGroups(sectionItems);
return (
<div style={{ paddingLeft: "1rem", borderLeft: "2px solid #222" }}>
{sectionItems.map((item) => {
const indentMatch = item.text.match(/^( *)(.*)$/s);
const indentLevel = indentMatch ? Math.floor(indentMatch[1].length / 2) : 0;
const displayText = indentMatch ? indentMatch[2] : item.text;
const gIdx = groupIndexById[item.id];
const group = groups[gIdx];
const localIdx = group.findIndex(i => i.id === item.id);
const isParentRow = localIdx === 0;
const isLastInGroup = localIdx === group.length - 1;
const arrowUpDisabled = indentLevel === 0 ? gIdx === 0 : localIdx <= 1;
const arrowDownDisabled = indentLevel === 0 ? gIdx === groups.length - 1 : isLastInGroup;
const isDragging = draggingId === item.id;
let showLineBefore = false, showLineAfter = false;
if (dragOver && dragOver.section === section) {
if (dragOver.kind === "group" && dragOver.groupIdx === gIdx) {
if (dragOver.position === "before" && isParentRow) showLineBefore = true;
if (dragOver.position === "after" && isLastInGroup) showLineAfter = true;
} else if (dragOver.kind === "item" && dragOver.id === item.id) {
if (dragOver.position === "before") showLineBefore = true;
else showLineAfter = true;
}
}
return (
<div
key={item.id}
draggable={!editing}
onDragStart={(e) => onItemDragStart(e, item)}
onDragOver={(e) => onItemDragOver(e, item, section)}
onDrop={(e) => onItemDrop(e, item, section)}
onDragEnd={onItemDragEnd}
style={{
marginBottom: "0.4rem",
paddingLeft: `${indentLevel * 1.5}rem`,
borderTop: showLineBefore ? "2px solid #4db8ff" : "2px solid transparent",
borderBottom: showLineAfter ? "2px solid #4db8ff" : "2px solid transparent",
opacity: isDragging ? 0.4 : 1,
}}
>
{editing?.id === item.id ? (
<EditRow
initial={editing.text}
onSave={text => saveEdit(item.id, section, text)}
onCancel={() => setEditing(null)}
inputStyle={inputStyle}
btnStyle={btnStyle}
/>
) : (
<div
onDoubleClick={() => setEditing({ id: item.id, section, text: item.text })}
title="Drag to reorder · double-click to edit"
style={{ display: "flex", alignItems: "flex-start", gap: "0.5rem", cursor: "grab" }}
>
<span style={{ color: "#aaa", marginTop: "0.1rem", flexShrink: 0 }}>-</span>
<span style={{ color: "#ddd", fontSize: "0.9rem", flexGrow: 1 }}>{displayText}</span>
<div style={{ display: "flex", gap: "0.3rem", flexShrink: 0, opacity: 0.4 }}
onMouseEnter={e => e.currentTarget.style.opacity = 1}
onMouseLeave={e => e.currentTarget.style.opacity = 0.4}
>
<button
onClick={() => moveItem(item.id, "up")}
disabled={arrowUpDisabled}
title="Move up"
style={{ ...btnStyle("#333"), fontSize: "0.72rem", padding: "0.2rem 0.4rem", opacity: arrowUpDisabled ? 0.3 : 1, cursor: arrowUpDisabled ? "default" : "pointer" }}
></button>
<button
onClick={() => moveItem(item.id, "down")}
disabled={arrowDownDisabled}
title="Move down"
style={{ ...btnStyle("#333"), fontSize: "0.72rem", padding: "0.2rem 0.4rem", opacity: arrowDownDisabled ? 0.3 : 1, cursor: arrowDownDisabled ? "default" : "pointer" }}
></button>
<button
onClick={() => deleteItem(item.id)}
style={{ ...btnStyle("#5a1a1a"), fontSize: "0.72rem", padding: "0.2rem 0.5rem" }}
>del</button>
</div>
</div>
)}
</div>
);
})}
{/* Inline add form */}
{adding?.section === section && (
<AddRow
onSave={text => saveNew(section, text)}
onCancel={() => setAdding(null)}
inputStyle={inputStyle}
btnStyle={btnStyle}
/>
)}
</div>
);
})()}
</div>
))}
{message && (
<div style={{ position: "fixed", bottom: "1.5rem", right: "1.5rem", background: "#1a2e1a", border: "1px solid #3a5a3a", color: "#7dcc7d", padding: "0.6rem 1rem", borderRadius: "8px", fontSize: "0.85rem" }}>
{message}
</div>
)}
</div>
);
}
function handleIndentKey(e, setText) {
if (e.key !== "Tab") return false;
e.preventDefault();
if (e.shiftKey) {
setText(t => t.startsWith(" ") ? t.slice(2) : t);
} else {
setText(t => " " + t);
}
return true;
}
function AddRow({ onSave, onCancel, inputStyle, btnStyle }) {
const [text, setText] = useState("");
return (
<div style={{ display: "flex", gap: "0.5rem", alignItems: "center", marginTop: "0.4rem" }}>
<span style={{ color: "#555", flexShrink: 0 }}>-</span>
<textarea
autoFocus
rows={1}
placeholder="New item… (paste multiple lines to add several at once)"
value={text}
onChange={e => setText(e.target.value)}
onKeyDown={e => {
if (handleIndentKey(e, setText)) return;
if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); onSave(text); }
if (e.key === "Escape") onCancel();
}}
style={{ ...inputStyle, resize: "vertical", fontFamily: "inherit", minHeight: "2.1rem" }}
/>
<button onClick={() => onSave(text)} style={btnStyle()}>Save</button>
<button onClick={onCancel} style={btnStyle("#444")}></button>
</div>
);
}
function EditRow({ initial, onSave, onCancel, inputStyle, btnStyle }) {
const [text, setText] = useState(initial);
return (
<div style={{ display: "flex", gap: "0.5rem", alignItems: "center" }}>
<span style={{ color: "#555", flexShrink: 0 }}>-</span>
<input
autoFocus
type="text"
value={text}
onChange={e => setText(e.target.value)}
onKeyDown={e => {
if (handleIndentKey(e, setText)) return;
if (e.key === "Enter") onSave(text);
if (e.key === "Escape") onCancel();
}}
style={{ ...inputStyle }}
/>
<button onClick={() => onSave(text)} style={btnStyle()}>Save</button>
<button onClick={onCancel} style={btnStyle("#444")}></button>
</div>
);
}
+278
View File
@@ -0,0 +1,278 @@
import { useCallback, useEffect, useState } from "react";
import { API_BASE } from "./config";
export function Models({ onPullStateChange }) {
const [models, setModels] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const [pulling, setPulling] = useState(false);
const [modelName, setModelName] = useState("");
const [pullProgress, setPullProgress] = useState("");
const checkOllamaStatus = useCallback(async () => {
try {
const response = await fetch(`${API_BASE}/ollama/status`);
const data = await response.json();
return data.status === "running";
} catch {
return false;
}
}, []);
const loadModels = useCallback(async () => {
setLoading(true);
setError("");
try {
const isRunning = await checkOllamaStatus();
if (!isRunning) {
setError("Ollama service is not running");
setModels([]);
return;
}
const response = await fetch(`${API_BASE}/models/details`);
if (!response.ok) throw new Error("Failed to fetch models");
const data = await response.json();
// Embedding models (nomic-embed-text) are infrastructure — hide them.
setModels((data.models || []).filter((m) => !m.name.toLowerCase().includes("embed")));
} catch (err) {
setError(`Error loading models: ${err.message}`);
setModels([]);
} finally {
setLoading(false);
}
}, [checkOllamaStatus]);
const pullModel = async () => {
if (!modelName.trim()) {
setError("Please enter a model name");
return;
}
setPulling(true);
onPullStateChange?.(true);
setError("");
setPullProgress("");
try {
const response = await fetch(`${API_BASE}/models/pull`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: modelName.trim() }),
});
if (!response.ok) throw new Error("Failed to pull model");
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split("\n");
for (const line of lines) {
if (line.trim()) {
try {
const json = JSON.parse(line);
if (json.error) {
setError(`Pull error: ${json.error}`);
} else if (json.status) {
setPullProgress(json.completed && json.total
? `${json.status}${Math.round((json.completed / json.total) * 100)}%`
: json.status
);
}
} catch {
// ignore incomplete JSON lines
}
}
}
}
setModelName("");
setPullProgress("");
await loadModels();
} catch (err) {
setError(`Error pulling model: ${err.message}`);
} finally {
setPulling(false);
onPullStateChange?.(false);
}
};
const deleteModel = async (modelId) => {
if (!confirm(`Are you sure you want to delete ${modelId}?`)) return;
setError("");
try {
const response = await fetch(`${API_BASE}/models/${encodeURIComponent(modelId)}`, {
method: "DELETE",
});
if (!response.ok) {
const text = await response.text().catch(() => "");
throw new Error(text || response.statusText);
}
await loadModels();
} catch (err) {
setError(`Error deleting model: ${err.message}`);
}
};
useEffect(() => {
loadModels();
const interval = setInterval(loadModels, 30000);
return () => clearInterval(interval);
}, [loadModels]);
return (
<div style={{ display: "flex", flexDirection: "column", height: "100%", flexGrow: 1 }}>
{error && (
<div style={{
padding: "0.75rem 1rem",
background: "#3d2d2d",
border: "1px solid #ff6b6b",
borderRadius: "8px",
color: "#ff8888",
marginBottom: "1rem",
fontSize: "0.9rem"
}}>
{error}
</div>
)}
<div style={{
flexGrow: 1,
background: "#161616",
border: "1px solid #333",
borderRadius: "12px",
padding: "1rem",
display: "flex",
flexDirection: "column",
overflow: "hidden"
}}>
{/* Pull Model Section */}
<div style={{ marginBottom: "1.5rem", paddingBottom: "1rem", borderBottom: "1px solid #333" }}>
<h3 style={{ margin: "0 0 0.75rem 0", fontSize: "0.95rem", color: "#bbb" }}>Pull Model from Registry</h3>
<div style={{ display: "flex", gap: "0.5rem" }}>
<input
type="text"
placeholder="e.g., llama3, mistral, gemma"
value={modelName}
onChange={(e) => setModelName(e.target.value)}
onKeyPress={(e) => e.key === "Enter" && !pulling && pullModel()}
disabled={pulling}
style={{
flex: 1,
padding: "0.6rem 0.75rem",
background: "#0a0a0a",
color: "#eee",
border: "1px solid #333",
borderRadius: "6px",
fontSize: "0.9rem"
}}
/>
<button
onClick={pullModel}
disabled={pulling}
style={{
padding: "0.6rem 1.25rem",
background: pulling ? "#666" : "#28a745",
color: "#fff",
border: "none",
borderRadius: "6px",
cursor: pulling ? "not-allowed" : "pointer",
fontSize: "0.9rem",
whiteSpace: "nowrap"
}}
>
{pulling ? "Pulling..." : "Pull"}
</button>
<button
onClick={loadModels}
disabled={loading}
style={{
padding: "0.6rem 1.25rem",
background: "#007acc",
color: "#fff",
border: "none",
borderRadius: "6px",
cursor: loading ? "not-allowed" : "pointer",
opacity: loading ? 0.6 : 1,
fontSize: "0.9rem",
whiteSpace: "nowrap"
}}
>
{loading ? "Refreshing..." : "Refresh"}
</button>
</div>
{pullProgress && (
<div style={{ marginTop: "0.75rem", fontSize: "0.85rem", color: "#999" }}>
{pullProgress}
</div>
)}
</div>
{/* Local Models List */}
<div style={{ flexGrow: 1, overflowY: "auto", paddingRight: "0.5rem" }}>
<h3 style={{ margin: "0 0 1rem 0", fontSize: "0.95rem", color: "#bbb" }}>
Available Models ({models.length})
</h3>
{models.length === 0 ? (
<div style={{ padding: "2rem", textAlign: "center", color: "#666" }}>
{loading ? "Loading models..." : "No models available. Pull a model to get started."}
</div>
) : (
<div style={{ display: "grid", gap: "0.75rem" }}>
{models.map((model) => (
<div
key={model.name}
style={{
padding: "0.9rem",
background: "#1b1b1b",
borderRadius: "8px",
border: "1px solid #2a2a2a",
display: "flex",
justifyContent: "space-between",
alignItems: "center"
}}
>
<div>
<div style={{ fontWeight: "500", marginBottom: "0.3rem", color: "#ddd" }}>
{model.name}
</div>
<div style={{ fontSize: "0.85rem", color: "#aaa" }}>
{(model.size / (1024 * 1024 * 1024)).toFixed(2)} GB
</div>
{model.modified_at && (
<div style={{ fontSize: "0.85rem", color: "#888" }}>
Modified: {new Date(model.modified_at).toLocaleDateString()}
</div>
)}
</div>
<button
onClick={() => deleteModel(model.name)}
style={{
padding: "0.5rem 1rem",
background: "#d63031",
color: "#fff",
border: "none",
borderRadius: "6px",
cursor: "pointer",
fontSize: "0.85rem",
whiteSpace: "nowrap"
}}
>
Delete
</button>
</div>
))}
</div>
)}
</div>
</div>
</div>
);
}
+406
View File
@@ -0,0 +1,406 @@
import { useEffect, useState, useCallback, useRef } from "react";
import { API_BASE } from "./config";
export function Playbook() {
const [playbooks, setPlaybooks] = useState([]);
const [selectedId, setSelectedId] = useState(null);
const [form, setForm] = useState({ title: "", goal: "", instructions: "", tags: "" });
const [search, setSearch] = useState("");
const [message, setMessage] = useState("");
const dragItem = useRef(null);
const dragOverItem = useRef(null);
const normalizePlaybooks = (data) => {
if (!data) return [];
if (Array.isArray(data)) return data;
if (Array.isArray(data.playbooks)) return data.playbooks;
if (typeof data === "object") return Object.values(data);
return [];
};
const loadPlaybooks = useCallback(async () => {
try {
const res = await fetch(`${API_BASE}/playbooks`);
if (!res.ok) { setPlaybooks([]); return; }
const data = await res.json().catch(() => null);
setPlaybooks(normalizePlaybooks(data));
} catch {
setPlaybooks([]);
}
}, []);
// eslint-disable-next-line react-hooks/set-state-in-effect -- async fetch on mount; setPlaybooks runs after await, not a synchronous cascading render
useEffect(() => { loadPlaybooks(); }, [loadPlaybooks]);
const safeString = (v) => (v == null ? "" : String(v));
const filteredPlaybooks = Array.isArray(playbooks)
? playbooks.filter(p => {
if (!search.trim()) return true;
const q = search.toLowerCase();
return (
safeString(p.title).toLowerCase().includes(q) ||
safeString(p.goal).toLowerCase().includes(q) ||
(Array.isArray(p.tags) ? p.tags : []).some(t => safeString(t).toLowerCase().includes(q))
);
})
: [];
const tryFetchWithTrailingSlash = async (url, opts) => {
let res = await fetch(url, opts);
if (res.status === 404 && !url.endsWith("/")) res = await fetch(url + "/", opts);
return res;
};
const selectPlaybook = async (playbookSummary) => {
const id = encodeURIComponent(String(playbookSummary.id));
setMessage("");
setSelectedId(playbookSummary.id);
try {
const res = await tryFetchWithTrailingSlash(`${API_BASE}/playbooks/${id}`, { method: "GET" });
const full = res.ok ? await res.json() : playbookSummary;
setForm({
title: full.title || "",
goal: full.goal || "",
instructions: full.instructions || "",
tags: (full.tags || []).join(", "),
});
} catch {
setForm({
title: playbookSummary.title || "",
goal: playbookSummary.goal || "",
instructions: playbookSummary.instructions || "",
tags: (playbookSummary.tags || []).join(", "),
});
}
};
const resetForm = () => {
setSelectedId(null);
setForm({ title: "", goal: "", instructions: "", tags: "" });
setMessage("");
};
const savePlaybook = async () => {
if (!form.title || !form.goal || !form.instructions) {
setMessage("Please fill in title, goal, and instructions.");
return;
}
const payload = {
title: form.title,
goal: form.goal,
instructions: form.instructions,
tags: form.tags.split(",").map(t => t.trim()).filter(Boolean),
};
const isUpdate = Boolean(selectedId);
const safeId = isUpdate ? encodeURIComponent(String(selectedId)) : null;
const baseUrl = isUpdate ? `${API_BASE}/playbooks/${safeId}` : `${API_BASE}/playbooks`;
const commonOpts = { headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) };
try {
let res;
if (isUpdate) {
res = await tryFetchWithTrailingSlash(baseUrl, { ...commonOpts, method: "PATCH" });
if (res.status === 404 || res.status === 405) {
const getRes = await tryFetchWithTrailingSlash(baseUrl, { method: "GET" });
const existing = getRes.ok ? await getRes.json().catch(() => ({})) : {};
res = await tryFetchWithTrailingSlash(baseUrl, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ...existing, ...payload }),
});
}
} else {
res = await tryFetchWithTrailingSlash(baseUrl, { ...commonOpts, method: "POST" });
}
if (!res.ok) {
const text = await res.text().catch(() => "");
setMessage(`Save failed: ${text || res.statusText}`);
return;
}
setMessage(isUpdate ? "Playbook updated." : "Playbook created.");
resetForm();
loadPlaybooks();
} catch (err) {
setMessage(`Save error: ${err.message || err}`);
}
};
const deletePlaybook = async (id) => {
if (!window.confirm("Delete this playbook?")) return;
const safeId = encodeURIComponent(String(id));
try {
const res = await tryFetchWithTrailingSlash(`${API_BASE}/playbooks/${safeId}`, { method: "DELETE" });
if (!res.ok) {
const text = await res.text().catch(() => "");
setMessage(`Delete failed: ${text || res.statusText}`);
return;
}
setMessage("Playbook deleted.");
if (selectedId === id) resetForm();
loadPlaybooks();
} catch (err) {
setMessage(`Delete error: ${err.message || err}`);
}
};
const onDragStart = (e, id) => {
dragItem.current = String(id);
e.dataTransfer.effectAllowed = "move";
};
const onDragEnter = (e, id) => {
dragOverItem.current = String(id);
e.preventDefault();
};
const onDragOver = (e) => {
e.preventDefault();
e.dataTransfer.dropEffect = "move";
};
const onDrop = async () => {
if (!dragItem.current || dragItem.current === dragOverItem.current) return;
const currentOrder = filteredPlaybooks.map(p => String(p.id));
const fromIdx = currentOrder.indexOf(dragItem.current);
const toIdx = currentOrder.indexOf(dragOverItem.current);
if (fromIdx === -1 || toIdx === -1) return;
// Guard: only a playbook with "main" in its title can occupy the first slot
if (toIdx === 0 && fromIdx !== 0) {
const dragged = filteredPlaybooks.find(p => String(p.id) === dragItem.current);
if (!dragged || !dragged.title.toLowerCase().includes("main")) {
setMessage("Only a playbook with 'main' in its title can be placed first.");
dragItem.current = null;
dragOverItem.current = null;
return;
}
}
const newFilteredOrder = [...currentOrder];
newFilteredOrder.splice(fromIdx, 1);
newFilteredOrder.splice(toIdx, 0, dragItem.current);
// Optimistic UI update — reorder within filtered set, keep unfiltered playbooks intact
setPlaybooks(prev => {
const filteredSet = new Set(currentOrder);
const filteredMap = Object.fromEntries(prev.filter(p => filteredSet.has(String(p.id))).map(p => [String(p.id), p]));
const reorderedFiltered = newFilteredOrder.map(id => filteredMap[id]).filter(Boolean);
// Merge: place unfiltered items back in their original relative positions
const result = [];
let fi = 0;
for (const p of prev) {
if (filteredSet.has(String(p.id))) {
if (fi < reorderedFiltered.length) result.push(reorderedFiltered[fi++]);
} else {
result.push(p);
}
}
return result;
});
dragItem.current = null;
dragOverItem.current = null;
// Send the full playbook order to the backend (filtered reorder merged with all IDs)
try {
await fetch(`${API_BASE}/playbooks/reorder`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ids: newFilteredOrder }),
});
} catch (err) {
console.error("Failed to persist order:", err);
loadPlaybooks();
}
};
return (
<div style={{ flexGrow: 1 }}>
<div style={{ display: "flex", gap: "1rem", alignItems: "stretch" }}>
{/* Sidebar */}
<aside style={{
width: "35%",
minWidth: "280px",
background: "#161616",
border: "1px solid #333",
borderRadius: "12px",
padding: "1rem"
}}>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "1rem" }}>
<h3 style={{ margin: 0, fontSize: "1rem" }}>Playbooks</h3>
<button
onClick={resetForm}
style={{ padding: "0.35rem 0.75rem", background: "#007acc", color: "#fff", border: "none", borderRadius: "6px", cursor: "pointer" }}
>
New
</button>
</div>
<input
type="text"
placeholder="Search playbooks..."
value={search}
onChange={e => setSearch(e.target.value)}
style={{
width: "100%",
padding: "0.75rem",
background: "#222",
color: "#eee",
border: "1px solid #333",
borderRadius: "8px",
marginBottom: "1rem",
boxSizing: "border-box"
}}
/>
<div style={{ maxHeight: "calc(100vh - 240px)", overflowY: "auto" }}>
{filteredPlaybooks.length === 0 ? (
<p style={{ color: "#aaa" }}>No playbooks found.</p>
) : (
filteredPlaybooks.map((p, idx) => {
const isMain = idx === 0 && !search.trim();
return (
<div
key={safeString(p.id)}
draggable
onDragStart={e => onDragStart(e, p.id)}
onDragEnter={e => onDragEnter(e, p.id)}
onDragOver={onDragOver}
onDrop={onDrop}
onClick={() => selectPlaybook(p)}
style={{
padding: "0.75rem 1rem",
marginBottom: "0.5rem",
borderRadius: "10px",
cursor: "grab",
background: selectedId === p.id ? "#262626" : "#1b1b1b",
border: selectedId === p.id
? "1px solid #007acc"
: isMain
? "1px solid #2a4a2a"
: "1px solid #2a2a2a",
display: "flex",
alignItems: "center",
gap: "0.75rem",
userSelect: "none",
}}
>
<span style={{ color: "#555", fontSize: "1rem", flexShrink: 0 }}></span>
<span style={{ color: "#eee", fontSize: "0.95rem", textAlign: "left", flexGrow: 1 }}>{p.title}</span>
{isMain && (
<span style={{
fontSize: "0.65rem",
fontWeight: "600",
color: "#4caf50",
background: "#1a2e1a",
border: "1px solid #2a4a2a",
borderRadius: "4px",
padding: "0.15rem 0.4rem",
flexShrink: 0,
letterSpacing: "0.05em",
}}>
MAIN
</span>
)}
</div>
);
})
)}
</div>
</aside>
{/* Editor */}
<main style={{
flexGrow: 1,
background: "#161616",
border: "1px solid #333",
borderRadius: "12px",
padding: "1rem"
}}>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: "1rem", marginBottom: "1rem" }}>
<div>
<h3 style={{ margin: 0, fontSize: "1rem" }}>{selectedId ? "Edit Playbook" : "Create Playbook"}</h3>
<p style={{ margin: "0.35rem 0 0", color: "#aaa", fontSize: "0.9rem" }}>
Select a playbook on the left, then edit here.
</p>
</div>
{selectedId && (
<button
onClick={() => deletePlaybook(selectedId)}
style={{ padding: "0.5rem 0.9rem", background: "#b32f2f", color: "#fff", border: "none", borderRadius: "8px", cursor: "pointer" }}
>
Delete
</button>
)}
</div>
<div style={{ display: "grid", gap: "0.9rem" }}>
<input
type="text"
placeholder="Title"
value={form.title}
onChange={e => setForm(prev => ({ ...prev, title: e.target.value }))}
style={{ padding: "0.9rem", background: "#222", color: "#eee", border: "1px solid #333", borderRadius: "10px" }}
/>
<input
type="text"
placeholder="Tags (comma separated)"
value={form.tags}
onChange={e => setForm(prev => ({ ...prev, tags: e.target.value }))}
style={{ padding: "0.9rem", background: "#222", color: "#eee", border: "1px solid #333", borderRadius: "10px" }}
/>
<textarea
rows={4}
placeholder="Goal"
value={form.goal}
onChange={e => setForm(prev => ({ ...prev, goal: e.target.value }))}
style={{ padding: "0.9rem", background: "#222", color: "#eee", border: "1px solid #333", borderRadius: "10px" }}
/>
<textarea
rows={10}
placeholder="Instructions"
value={form.instructions}
onChange={e => setForm(prev => ({ ...prev, instructions: e.target.value }))}
onKeyDown={e => {
if (e.key === "Tab") {
e.preventDefault();
const ta = e.currentTarget;
const start = ta.selectionStart;
const end = ta.selectionEnd;
setForm(prev => {
const newVal = prev.instructions.slice(0, start) + "\t" + prev.instructions.slice(end);
setTimeout(() => { ta.selectionStart = ta.selectionEnd = start + 1; }, 0);
return { ...prev, instructions: newVal };
});
}
}}
style={{ padding: "0.9rem", background: "#222", color: "#eee", border: "1px solid #333", borderRadius: "10px" }}
/>
</div>
<div style={{ marginTop: "1rem", display: "flex", gap: "0.75rem", flexWrap: "wrap" }}>
<button
onClick={savePlaybook}
style={{ padding: "0.85rem 1.2rem", background: "#007acc", color: "#fff", border: "none", borderRadius: "8px", cursor: "pointer" }}
>
{selectedId ? "Update Playbook" : "Create Playbook"}
</button>
<button
onClick={resetForm}
style={{ padding: "0.85rem 1.2rem", background: "#444", color: "#fff", border: "none", borderRadius: "8px", cursor: "pointer" }}
>
Clear
</button>
</div>
{message && (
<div style={{ marginTop: "1rem", color: "#aaffaa" }}>{message}</div>
)}
</main>
</div>
</div>
);
}
+577
View File
@@ -0,0 +1,577 @@
import { useEffect, useState } from "react";
import { API_BASE } from "./config";
const DEFAULTS = {
model: "",
think: false, // Qwen3-style reasoning; off = much faster chat/memory
temperature: 0.7,
system_prompt: "",
timeout: 120,
gpu_offload: -1, // -1 = Auto; 0100 = percent of layers forced onto the GPU
memory_model: "mistral:latest", // curator model for memory extraction
memory_gpu_offload: 0, // curator offload; 0 = all CPU/RAM (safe on small GPUs)
memory_merge_threshold: 0.80, // 0 = off; else update near-duplicate facts in place
};
export function Settings() {
const [form, setForm] = useState(DEFAULTS);
const [saved, setSaved] = useState(false);
const [error, setError] = useState("");
// Icon branding state
const [iconApps, setIconApps] = useState([]);
const [iconFilter, setIconFilter] = useState("");
const [iconFrac, setIconFrac] = useState(0.60);
const [iconRing, setIconRing] = useState(false);
const [selectedApps, setSelectedApps] = useState([]);
const [brandQueue, setBrandQueue] = useState([]);
const [isBranding, setIsBranding] = useState(false);
useEffect(() => {
fetch(`${API_BASE}/settings`)
.then(r => r.ok ? r.json() : null)
.then(d => { if (d) setForm(f => ({ ...f, ...d })); })
.catch(() => {});
fetch(`${API_BASE}/icons/apps`)
.then(r => r.ok ? r.json() : null)
.then(d => { if (d) setIconApps(d.apps || []); })
.catch(() => {});
}, []);
const update = (key, value) => setForm(f => ({ ...f, [key]: value }));
const save = async () => {
setError("");
setSaved(false);
try {
const r = await fetch(`${API_BASE}/settings`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(form),
});
if (!r.ok) throw new Error(await r.text());
setSaved(true);
setTimeout(() => setSaved(false), 2500);
} catch (e) {
setError(e.message || "Failed to save");
}
};
const reset = () => setForm(DEFAULTS);
// Icon branding logic
const toggleAppSelect = (app) => {
setSelectedApps(prev => {
const exists = prev.find(a => a.icon_name === app.icon_name);
if (exists) return prev.filter(a => a.icon_name !== app.icon_name);
return [...prev, app];
});
};
const removeFromQueue = (icon_name) => {
setSelectedApps(prev => prev.filter(a => a.icon_name !== icon_name));
};
const brandAll = async () => {
if (!selectedApps.length || isBranding) return;
setIsBranding(true);
const queue = selectedApps.map(a => ({ ...a, status: "pending" }));
setBrandQueue(queue);
for (let i = 0; i < queue.length; i++) {
const app = queue[i];
setBrandQueue(prev => prev.map((a, idx) => idx === i ? { ...a, status: "running" } : a));
try {
const r = await fetch(`${API_BASE}/icons/brand`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
src_path: app.icon_path,
output_name: app.icon_name,
frac: iconFrac,
nexus_ring: iconRing,
reload: false,
}),
});
if (!r.ok) throw new Error(await r.text());
setBrandQueue(prev => prev.map((a, idx) => idx === i ? { ...a, status: "done" } : a));
} catch (e) {
setBrandQueue(prev => prev.map((a, idx) => idx === i ? { ...a, status: "error", err: e.message } : a));
}
}
// Apply cache once after all are done
await fetch(`${API_BASE}/icons/apply`, { method: "POST" }).catch(() => {});
// Mark already_branded in the app list
setIconApps(prev => prev.map(a => {
if (selectedApps.find(s => s.icon_name === a.icon_name)) {
return { ...a, already_branded: true };
}
return a;
}));
setIsBranding(false);
};
const filteredApps = iconApps.filter(a =>
a.name.toLowerCase().includes(iconFilter.toLowerCase())
);
const statusIcon = (status) => {
if (status === "pending") return <span style={{ color: "#666" }}></span>;
if (status === "running") return <span style={{ color: "#8cc63f" }}></span>;
if (status === "done") return <span style={{ color: "#8cc63f" }}></span>;
if (status === "error") return <span style={{ color: "#f44336" }}></span>;
return null;
};
const inputStyle = {
width: "100%",
padding: "0.6rem 0.75rem",
background: "#222",
color: "#eee",
border: "1px solid #333",
borderRadius: "8px",
fontSize: "0.9rem",
boxSizing: "border-box",
};
const labelStyle = {
display: "block",
fontSize: "0.8rem",
color: "#888",
marginBottom: "0.4rem",
textTransform: "uppercase",
letterSpacing: "0.05em",
};
const sectionStyle = {
background: "#161616",
border: "1px solid #333",
borderRadius: "12px",
padding: "1.25rem",
marginBottom: "1rem",
};
const displayQueue = isBranding ? brandQueue : selectedApps;
return (
<div style={{ maxWidth: "720px" }}>
<h2 style={{ margin: "0 0 1.25rem", fontSize: "1.1rem", color: "#eee" }}>Settings</h2>
{/* Generation */}
<div style={sectionStyle}>
<h3 style={{ margin: "0 0 1rem", fontSize: "0.95rem", color: "#bbb" }}>Generation</h3>
<div style={{ marginBottom: "0.25rem" }}>
<label style={labelStyle}>
Temperature
<span style={{ float: "right", color: "#7aa", fontWeight: 600, textTransform: "none", letterSpacing: 0 }}>
{Number(form.temperature).toFixed(2)}
</span>
</label>
<input
type="range"
min="0"
max="2"
step="0.05"
value={form.temperature}
onChange={e => update("temperature", parseFloat(e.target.value))}
style={{ width: "100%", accentColor: "#007acc" }}
/>
<div style={{ display: "flex", justifyContent: "space-between", fontSize: "0.72rem", color: "#555", marginTop: "0.2rem" }}>
<span>0.0 precise</span>
<span>1.0 balanced</span>
<span>2.0 creative</span>
</div>
</div>
<div style={{ marginTop: "1.25rem" }}>
<label style={labelStyle}>
GPU Offload
<span style={{ float: "right", color: "#b040c0", fontWeight: 600, textTransform: "none", letterSpacing: 0 }}>
{form.gpu_offload < 0 ? "Auto" : `${form.gpu_offload}%`}
</span>
</label>
<input
type="range"
min="0"
max="100"
step="5"
value={form.gpu_offload < 0 ? 100 : form.gpu_offload}
disabled={form.gpu_offload < 0}
onChange={e => update("gpu_offload", parseInt(e.target.value))}
style={{ width: "100%", accentColor: "#b040c0", opacity: form.gpu_offload < 0 ? 0.4 : 1 }}
/>
<div style={{ display: "flex", justifyContent: "space-between", fontSize: "0.72rem", color: "#555", marginTop: "0.2rem" }}>
<span>0% all CPU</span>
<span>100% all GPU</span>
</div>
<label style={{ display: "flex", alignItems: "center", gap: "0.5rem", cursor: "pointer", userSelect: "none", marginTop: "0.6rem" }}>
<input
type="checkbox"
checked={form.gpu_offload < 0}
onChange={e => update("gpu_offload", e.target.checked ? -1 : 50)}
style={{ accentColor: "#8cc63f", width: "16px", height: "16px" }}
/>
<span style={{ fontSize: "0.82rem", color: form.gpu_offload < 0 ? "#8cc63f" : "#888" }}>
Auto fit as many layers as VRAM allows (recommended)
</span>
</label>
<p style={{ margin: "0.4rem 0 0", fontSize: "0.72rem", color: "#555" }}>
Lower values push more of the model onto the CPU slower, but frees VRAM and reduces GPU load. Layer count is resolved per model.
</p>
</div>
<div style={{ marginTop: "1.25rem" }}>
<label style={{ display: "flex", alignItems: "center", gap: "0.5rem", cursor: "pointer", userSelect: "none" }}>
<input
type="checkbox"
checked={!!form.think}
onChange={e => update("think", e.target.checked)}
style={{ accentColor: "#b040c0", width: "16px", height: "16px" }}
/>
<span style={{ fontSize: "0.85rem", color: "#ccc", fontWeight: 600 }}>Extended thinking</span>
</label>
<p style={{ margin: "0.4rem 0 0", fontSize: "0.72rem", color: "#555" }}>
Let reasoning models (e.g. Qwen3) work through a hidden thinking step before answering. <strong>Off is much faster</strong> for chat and memory; turn on for hard multi-step problems. Ignored by models with no thinking mode.
</p>
</div>
</div>
{/* Memory Curator */}
<div style={sectionStyle}>
<h3 style={{ margin: "0 0 1rem", fontSize: "0.95rem", color: "#bbb" }}>Memory Curator</h3>
<p style={{ margin: "0 0 1rem", fontSize: "0.75rem", color: "#555" }}>
The model that reviews each exchange and saves new facts to memory, in the background after every reply.
</p>
<div style={{ marginBottom: "1rem" }}>
<label style={labelStyle}>Curator Model</label>
<input
type="text"
value={form.memory_model}
onChange={e => update("memory_model", e.target.value)}
placeholder="mistral:latest (blank = same model as chat)"
style={inputStyle}
/>
<p style={{ margin: "0.35rem 0 0", fontSize: "0.75rem", color: "#555" }}>
A dedicated model like <code>mistral:latest</code> extracts facts more reliably than a small chat model.
</p>
</div>
<div>
<label style={labelStyle}>
Curator GPU Offload
<span style={{ float: "right", color: "#b040c0", fontWeight: 600, textTransform: "none", letterSpacing: 0 }}>
{form.memory_gpu_offload < 0 ? "Auto" : `${form.memory_gpu_offload}%`}
</span>
</label>
<input
type="range"
min="0"
max="100"
step="5"
value={form.memory_gpu_offload < 0 ? 100 : form.memory_gpu_offload}
disabled={form.memory_gpu_offload < 0}
onChange={e => update("memory_gpu_offload", parseInt(e.target.value))}
style={{ width: "100%", accentColor: "#b040c0", opacity: form.memory_gpu_offload < 0 ? 0.4 : 1 }}
/>
<div style={{ display: "flex", justifyContent: "space-between", fontSize: "0.72rem", color: "#555", marginTop: "0.2rem" }}>
<span>0% all CPU/RAM</span>
<span>100% all GPU</span>
</div>
<label style={{ display: "flex", alignItems: "center", gap: "0.5rem", cursor: "pointer", userSelect: "none", marginTop: "0.6rem" }}>
<input
type="checkbox"
checked={form.memory_gpu_offload < 0}
onChange={e => update("memory_gpu_offload", e.target.checked ? -1 : 0)}
style={{ accentColor: "#8cc63f", width: "16px", height: "16px" }}
/>
<span style={{ fontSize: "0.82rem", color: form.memory_gpu_offload < 0 ? "#8cc63f" : "#888" }}>
Auto let Ollama fit layers to spare VRAM
</span>
</label>
<p style={{ margin: "0.4rem 0 0", fontSize: "0.72rem", color: "#555" }}>
Keep at <strong>0% (all CPU/RAM)</strong> on a small GPU so the curator doesn't evict the chat model on a ~4&nbsp;GB GPU that thrash makes extraction time out and silently save nothing. Raise it only if you have spare VRAM.
</p>
</div>
<div style={{ marginTop: "1.25rem" }}>
<label style={{ display: "flex", alignItems: "center", gap: "0.5rem", cursor: "pointer", userSelect: "none" }}>
<input
type="checkbox"
checked={form.memory_merge_threshold > 0}
onChange={e => update("memory_merge_threshold", e.target.checked ? 0.80 : 0)}
style={{ accentColor: "#b040c0", width: "16px", height: "16px" }}
/>
<span style={{ fontSize: "0.85rem", color: "#ccc", fontWeight: 600 }}>Merge similar facts (edit in place)</span>
</label>
<p style={{ margin: "0.4rem 0 0.7rem", fontSize: "0.72rem", color: "#555" }}>
When a newly extracted fact closely matches an existing one, update that entry instead of adding a duplicate. Uses embeddings.
</p>
{form.memory_merge_threshold > 0 && (
<>
<label style={labelStyle}>
Merge threshold
<span style={{ float: "right", color: "#b040c0", fontWeight: 600, textTransform: "none", letterSpacing: 0 }}>
{Number(form.memory_merge_threshold).toFixed(2)}
</span>
</label>
<input
type="range"
min="0.60"
max="0.98"
step="0.01"
value={form.memory_merge_threshold}
onChange={e => update("memory_merge_threshold", parseFloat(e.target.value))}
style={{ width: "100%", accentColor: "#b040c0" }}
/>
<div style={{ display: "flex", justifyContent: "space-between", fontSize: "0.72rem", color: "#555", marginTop: "0.2rem" }}>
<span>0.60 merges more</span>
<span>0.98 only near-identical</span>
</div>
</>
)}
</div>
</div>
{/* Behaviour */}
<div style={sectionStyle}>
<h3 style={{ margin: "0 0 1rem", fontSize: "0.95rem", color: "#bbb" }}>Behaviour</h3>
<div style={{ marginBottom: "1rem" }}>
<label style={labelStyle}>Global System Prompt</label>
<textarea
value={form.system_prompt}
onChange={e => update("system_prompt", e.target.value)}
placeholder="Instructions applied to every conversation when no playbook is active..."
rows={5}
style={{ ...inputStyle, fontFamily: "system-ui", resize: "vertical" }}
/>
<p style={{ margin: "0.35rem 0 0", fontSize: "0.75rem", color: "#555" }}>
Playbook system prompts override this when active.
</p>
</div>
<div>
<label style={labelStyle}>
Request Timeout (seconds)
<span style={{ float: "right", color: "#7aa", fontWeight: 600, textTransform: "none", letterSpacing: 0 }}>
{form.timeout}s
</span>
</label>
<input
type="range"
min="10"
max="600"
step="10"
value={form.timeout}
onChange={e => update("timeout", parseInt(e.target.value))}
style={{ width: "100%", accentColor: "#007acc" }}
/>
<div style={{ display: "flex", justifyContent: "space-between", fontSize: "0.72rem", color: "#555", marginTop: "0.2rem" }}>
<span>10s</span>
<span>300s</span>
<span>600s</span>
</div>
</div>
</div>
{/* Icon Branding */}
<div style={sectionStyle}>
<h3 style={{ margin: "0 0 0.75rem", fontSize: "0.95rem", color: "#bbb" }}>App Icon Branding</h3>
<p style={{ margin: "0 0 1rem", fontSize: "0.78rem", color: "#555" }}>
Select apps on the left to composite their icon onto the NexusOS tile.
</p>
{/* Controls row */}
<div style={{ display: "flex", gap: "1.5rem", marginBottom: "1rem", alignItems: "center", flexWrap: "wrap" }}>
<div style={{ flex: "1 1 180px" }}>
<label style={labelStyle}>
Logo size
<span style={{ float: "right", color: "#b040c0", fontWeight: 600, textTransform: "none", letterSpacing: 0 }}>
{Math.round(iconFrac * 100)}%
</span>
</label>
<input
type="range"
min="0.30"
max="0.85"
step="0.05"
value={iconFrac}
onChange={e => setIconFrac(parseFloat(e.target.value))}
style={{ width: "100%", accentColor: "#b040c0" }}
/>
</div>
<label style={{ display: "flex", alignItems: "center", gap: "0.5rem", cursor: "pointer", userSelect: "none" }}>
<input
type="checkbox"
checked={iconRing}
onChange={e => setIconRing(e.target.checked)}
style={{ accentColor: "#8cc63f", width: "16px", height: "16px" }}
/>
<span style={{ fontSize: "0.85rem", color: iconRing ? "#8cc63f" : "#888" }}>Nexus ring</span>
</label>
</div>
{/* Shuttle */}
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0.75rem" }}>
{/* Left: app list */}
<div style={{ display: "flex", flexDirection: "column", gap: "0.5rem" }}>
<input
type="text"
placeholder="Filter apps…"
value={iconFilter}
onChange={e => setIconFilter(e.target.value)}
style={{ ...inputStyle, padding: "0.4rem 0.6rem", fontSize: "0.82rem" }}
/>
<div style={{ height: "280px", overflowY: "auto", background: "#0d0d0d", border: "1px solid #2a2a2a", borderRadius: "8px" }}>
{filteredApps.length === 0 && (
<div style={{ padding: "1rem", color: "#444", fontSize: "0.82rem", textAlign: "center" }}>
{iconApps.length === 0 ? "Loading…" : "No apps match"}
</div>
)}
{filteredApps.map(app => {
const isSelected = !!selectedApps.find(a => a.icon_name === app.icon_name);
return (
<div
key={app.icon_name}
onClick={() => !isBranding && !isSelected && app.icon_path && toggleAppSelect(app)}
style={{
display: "flex",
alignItems: "center",
gap: "0.5rem",
padding: "0.35rem 0.6rem",
cursor: isBranding || isSelected || !app.icon_path ? "default" : "pointer",
background: isSelected ? "rgba(176,64,192,0.15)" : "transparent",
borderLeft: isSelected ? "2px solid #b040c0" : "2px solid transparent",
opacity: !app.icon_path ? 0.35 : 1,
}}
onMouseEnter={e => { if (!isSelected && app.icon_path && !isBranding) e.currentTarget.style.background = "rgba(255,255,255,0.04)"; }}
onMouseLeave={e => { if (!isSelected) e.currentTarget.style.background = "transparent"; }}
>
{app.icon_path ? (
<img
src={`${API_BASE}/icons/image?path=${encodeURIComponent(app.icon_path)}`}
alt=""
style={{ width: "22px", height: "22px", objectFit: "contain", flexShrink: 0 }}
onError={e => { e.target.style.display = "none"; }}
/>
) : (
<div style={{ width: "22px", height: "22px", background: "#1a1a1a", borderRadius: "4px", flexShrink: 0 }} />
)}
<span style={{ fontSize: "0.82rem", color: "#ccc", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
{app.name}
</span>
{app.already_branded && (
<span style={{ marginLeft: "auto", color: "#8cc63f", fontSize: "0.72rem", flexShrink: 0 }}></span>
)}
</div>
);
})}
</div>
</div>
{/* Right: queue */}
<div style={{ display: "flex", flexDirection: "column", gap: "0.5rem" }}>
<div style={{ fontSize: "0.8rem", color: "#555", padding: "0.4rem 0", minHeight: "2rem" }}>
{isBranding ? `Branding ${brandQueue.length} app${brandQueue.length !== 1 ? "s" : ""}` : `${selectedApps.length} selected`}
</div>
<div style={{ height: "280px", overflowY: "auto", background: "#0d0d0d", border: "1px solid #2a2a2a", borderRadius: "8px" }}>
{displayQueue.length === 0 && (
<div style={{ padding: "1rem", color: "#333", fontSize: "0.82rem", textAlign: "center" }}>
Click apps to add
</div>
)}
{displayQueue.map(app => (
<div
key={app.icon_name}
style={{ display: "flex", alignItems: "center", gap: "0.5rem", padding: "0.35rem 0.6rem" }}
>
{isBranding ? (
<span style={{ fontSize: "1rem", width: "18px", textAlign: "center", flexShrink: 0 }}>
{statusIcon(app.status)}
</span>
) : (
<button
onClick={() => removeFromQueue(app.icon_name)}
style={{ background: "transparent", border: "none", color: "#555", cursor: "pointer", fontSize: "0.9rem", padding: "0 2px", lineHeight: 1, flexShrink: 0 }}
onMouseEnter={e => e.target.style.color = "#f44336"}
onMouseLeave={e => e.target.style.color = "#555"}
>
×
</button>
)}
<span style={{ fontSize: "0.82rem", color: isBranding && app.status === "done" ? "#8cc63f" : "#ccc", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
{app.name}
</span>
</div>
))}
</div>
</div>
</div>
{/* Brand button */}
<div style={{ marginTop: "0.75rem", display: "flex", alignItems: "center", gap: "0.75rem" }}>
<button
onClick={brandAll}
disabled={!selectedApps.length || isBranding}
style={{
padding: "0.6rem 1.25rem",
background: selectedApps.length && !isBranding ? "#5e0066" : "#1a1a1a",
color: selectedApps.length && !isBranding ? "#eee" : "#444",
border: `1px solid ${selectedApps.length && !isBranding ? "#b040c0" : "#2a2a2a"}`,
borderRadius: "8px",
cursor: selectedApps.length && !isBranding ? "pointer" : "default",
fontSize: "0.88rem",
fontWeight: 500,
transition: "background 0.15s",
}}
>
{isBranding ? "Branding…" : `Brand ${selectedApps.length || ""} App${selectedApps.length !== 1 ? "s" : ""}`}
</button>
{!isBranding && brandQueue.length > 0 && brandQueue.every(a => a.status === "done") && (
<span style={{ color: "#8cc63f", fontSize: "0.85rem" }}>Done panel reloaded</span>
)}
</div>
</div>
{/* Actions */}
<div style={{ display: "flex", gap: "0.75rem", alignItems: "center" }}>
<button
onClick={save}
style={{
padding: "0.65rem 1.5rem",
background: "#007acc",
color: "#fff",
border: "none",
borderRadius: "8px",
cursor: "pointer",
fontSize: "0.9rem",
}}
>
Save
</button>
<button
onClick={reset}
style={{
padding: "0.65rem 1.1rem",
background: "#222",
color: "#aaa",
border: "1px solid #444",
borderRadius: "8px",
cursor: "pointer",
fontSize: "0.9rem",
}}
>
Reset to defaults
</button>
{saved && <span style={{ color: "#4caf50", fontSize: "0.85rem" }}>Saved</span>}
{error && <span style={{ color: "#f44336", fontSize: "0.85rem" }}>{error}</span>}
</div>
</div>
);
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 8.5 KiB

+1
View File
@@ -0,0 +1 @@
export const API_BASE = "http://localhost:8000";
+113
View File
@@ -0,0 +1,113 @@
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.3; }
}
:root {
--text: #6b6375;
--text-h: #08060d;
--bg: #fff;
--border: #e5e4e7;
--code-bg: #f4f3ec;
--accent: #aa3bff;
--accent-bg: rgba(170, 59, 255, 0.1);
--accent-border: rgba(170, 59, 255, 0.5);
--social-bg: rgba(244, 243, 236, 0.5);
--shadow:
rgba(0, 0, 0, 0.1) 0 10px 15px -3px, rgba(0, 0, 0, 0.05) 0 4px 6px -2px;
--sans: system-ui, 'Segoe UI', Roboto, sans-serif;
--heading: system-ui, 'Segoe UI', Roboto, sans-serif;
--mono: ui-monospace, Consolas, monospace;
font: 18px/145% var(--sans);
letter-spacing: 0.18px;
color-scheme: light dark;
color: var(--text);
background: var(--bg);
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
@media (max-width: 1024px) {
font-size: 16px;
}
}
@media (prefers-color-scheme: dark) {
:root {
--text: #9ca3af;
--text-h: #f3f4f6;
--bg: #16171d;
--border: #2e303a;
--code-bg: #1f2028;
--accent: #c084fc;
--accent-bg: rgba(192, 132, 252, 0.15);
--accent-border: rgba(192, 132, 252, 0.5);
--social-bg: rgba(47, 48, 58, 0.5);
--shadow:
rgba(0, 0, 0, 0.4) 0 10px 15px -3px, rgba(0, 0, 0, 0.25) 0 4px 6px -2px;
}
#social .button-icon {
filter: invert(1) brightness(2);
}
}
body {
margin: 0;
}
#root {
width: 100%;
text-align: left;
min-height: 100svh;
display: flex;
flex-direction: column;
box-sizing: border-box;
}
h1,
h2 {
font-family: var(--heading);
font-weight: 500;
color: var(--text-h);
}
h1 {
font-size: 56px;
letter-spacing: -1.68px;
margin: 32px 0;
@media (max-width: 1024px) {
font-size: 36px;
margin: 20px 0;
}
}
h2 {
font-size: 24px;
line-height: 118%;
letter-spacing: -0.24px;
margin: 0 0 8px;
@media (max-width: 1024px) {
font-size: 20px;
}
}
p {
margin: 0;
}
code,
.counter {
font-family: var(--mono);
display: inline-flex;
border-radius: 4px;
color: var(--text-h);
}
code {
font-size: 15px;
line-height: 135%;
padding: 4px 8px;
background: var(--code-bg);
}
+10
View File
@@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.jsx'
createRoot(document.getElementById('root')).render(
<StrictMode>
<App />
</StrictMode>,
)
+10
View File
@@ -0,0 +1,10 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
// host: true binds 0.0.0.0 so the Windows browser can reach the dev server
// through WSL2 (loopback-only binding isn't reliably forwarded out of WSL).
server: { host: true },
})