moved from tauri to a server with embedded UI

This commit is contained in:
Dave
2026-02-13 12:31:36 +00:00
parent d4203cfaab
commit 0876c53e17
79 changed files with 5755 additions and 10655 deletions

198
frontend/src/App.css Normal file
View File

@@ -0,0 +1,198 @@
.logo.vite:hover {
filter: drop-shadow(0 0 2em #747bff);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafb);
}
:root {
font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
font-size: 16px;
line-height: 24px;
font-weight: 400;
color: #0f0f0f;
background-color: #f6f6f6;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-text-size-adjust: 100%;
}
.container {
margin: 0;
padding-top: 0;
height: 100vh;
overflow: hidden;
box-sizing: border-box;
display: flex;
flex-direction: column;
justify-content: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: 0.75s;
}
.logo.tauri:hover {
filter: drop-shadow(0 0 2em #24c8db);
}
.row {
display: flex;
justify-content: center;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
h1 {
text-align: center;
}
input,
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
color: #0f0f0f;
background-color: #ffffff;
transition: border-color 0.25s;
box-shadow: 0 2px 2px rgba(0, 0, 0, 0.2);
}
button {
cursor: pointer;
}
button:hover {
border-color: #396cd8;
}
button:active {
border-color: #396cd8;
background-color: #e8e8e8;
}
input,
button {
outline: none;
}
#greet-input {
margin-right: 5px;
}
@media (prefers-color-scheme: dark) {
:root {
color: #f6f6f6;
background-color: #2f2f2f;
}
a:hover {
color: #24c8db;
}
input,
button {
color: #ffffff;
background-color: #0f0f0f98;
}
button:active {
background-color: #0f0f0f69;
}
}
/* Collapsible tool output styling */
details summary {
cursor: pointer;
user-select: none;
}
details summary::-webkit-details-marker {
display: none;
}
details[open] summary span:first-child {
transform: rotate(90deg);
display: inline-block;
transition: transform 0.2s ease;
}
details summary span:first-child {
transition: transform 0.2s ease;
}
/* Markdown body styling for dark theme */
.markdown-body {
color: #ececec;
text-align: left;
}
.markdown-body code {
background: #2f2f2f;
padding: 2px 6px;
border-radius: 3px;
font-family: monospace;
}
.markdown-body pre {
background: #1a1a1a;
padding: 12px;
border-radius: 6px;
overflow-x: auto;
text-align: left;
}
.markdown-body pre code {
background: transparent;
padding: 0;
}
/* Syntax highlighter styling */
.markdown-body div[class*="language-"] {
margin: 0;
border-radius: 6px;
text-align: left;
}
.markdown-body pre[class*="language-"] {
margin: 0;
padding: 12px;
background: #1a1a1a;
text-align: left;
}
/* Hide scroll bars globally while maintaining scroll functionality */
/* Firefox */
* {
scrollbar-width: none;
}
/* Chrome, Safari, Edge */
*::-webkit-scrollbar {
display: none;
}
/* Ensure scroll functionality is maintained */
html,
body,
#root {
height: 100%;
margin: 0;
overflow: hidden;
}

93
frontend/src/App.tsx Normal file
View File

@@ -0,0 +1,93 @@
import * as React from "react";
import { api } from "./api/client";
import { Chat } from "./components/Chat";
import "./App.css";
function App() {
const [projectPath, setProjectPath] = React.useState<string | null>(null);
const [errorMsg, setErrorMsg] = React.useState<string | null>(null);
const [pathInput, setPathInput] = React.useState("");
const [isOpening, setIsOpening] = React.useState(false);
async function openProject(path: string) {
if (!path.trim()) {
setErrorMsg("Please enter a project path.");
return;
}
try {
setErrorMsg(null);
setIsOpening(true);
const confirmedPath = await api.openProject(path.trim());
setProjectPath(confirmedPath);
} catch (e) {
console.error(e);
const message =
e instanceof Error
? e.message
: typeof e === "string"
? e
: "An error occurred opening the project.";
setErrorMsg(message);
} finally {
setIsOpening(false);
}
}
function handleOpen() {
void openProject(pathInput);
}
async function closeProject() {
try {
await api.closeProject();
setProjectPath(null);
} catch (e) {
console.error(e);
}
}
return (
<main
className="container"
style={{ height: "100vh", padding: 0, maxWidth: "100%" }}
>
{!projectPath ? (
<div
className="selection-screen"
style={{ padding: "2rem", maxWidth: "800px", margin: "0 auto" }}
>
<h1>AI Code Assistant</h1>
<p>Paste a project path to start the Story-Driven Spec Workflow.</p>
<input
type="text"
value={pathInput}
placeholder="/path/to/project"
onChange={(event) => setPathInput(event.target.value)}
onKeyDown={(event) => {
if (event.key === "Enter") {
handleOpen();
}
}}
style={{ width: "100%", padding: "10px", marginTop: "12px" }}
/>
<button type="button" onClick={handleOpen} disabled={isOpening}>
{isOpening ? "Opening..." : "Open Project"}
</button>
</div>
) : (
<div className="workspace" style={{ height: "100%" }}>
<Chat projectPath={projectPath} onCloseProject={closeProject} />
</div>
)}
{errorMsg && (
<div className="error-message" style={{ marginTop: "20px" }}>
<p style={{ color: "red" }}>Error: {errorMsg}</p>
</div>
)}
</main>
);
}
export default App;

226
frontend/src/api/client.ts Normal file
View File

@@ -0,0 +1,226 @@
export type WsRequest =
| {
type: "chat";
messages: Message[];
config: ProviderConfig;
}
| {
type: "cancel";
};
export type WsResponse =
| { type: "token"; content: string }
| { type: "update"; messages: Message[] }
| { type: "error"; message: string };
export interface ProviderConfig {
provider: string;
model: string;
base_url?: string;
enable_tools?: boolean;
}
export type Role = "system" | "user" | "assistant" | "tool";
export interface ToolCall {
id?: string;
type: string;
function: {
name: string;
arguments: string;
};
}
export interface Message {
role: Role;
content: string;
tool_calls?: ToolCall[];
tool_call_id?: string;
}
export interface FileEntry {
name: string;
kind: "file" | "dir";
}
export interface SearchResult {
path: string;
matches: number;
}
export interface CommandOutput {
stdout: string;
stderr: string;
exit_code: number;
}
const DEFAULT_API_BASE = "/api";
const DEFAULT_WS_PATH = "/ws";
function buildApiUrl(path: string, baseUrl = DEFAULT_API_BASE): string {
return `${baseUrl}${path}`;
}
async function requestJson<T>(
path: string,
options: RequestInit = {},
baseUrl = DEFAULT_API_BASE,
): Promise<T> {
const res = await fetch(buildApiUrl(path, baseUrl), {
headers: {
"Content-Type": "application/json",
...(options.headers ?? {}),
},
...options,
});
if (!res.ok) {
const text = await res.text();
throw new Error(text || `Request failed (${res.status})`);
}
return res.json() as Promise<T>;
}
export const api = {
getCurrentProject(baseUrl?: string) {
return requestJson<string | null>("/project", {}, baseUrl);
},
openProject(path: string, baseUrl?: string) {
return requestJson<string>(
"/project",
{ method: "POST", body: JSON.stringify({ path }) },
baseUrl,
);
},
closeProject(baseUrl?: string) {
return requestJson<boolean>("/project", { method: "DELETE" }, baseUrl);
},
getModelPreference(baseUrl?: string) {
return requestJson<string | null>("/model", {}, baseUrl);
},
setModelPreference(model: string, baseUrl?: string) {
return requestJson<boolean>(
"/model",
{ method: "POST", body: JSON.stringify({ model }) },
baseUrl,
);
},
getOllamaModels(baseUrlParam?: string, baseUrl?: string) {
const url = new URL(
buildApiUrl("/ollama/models", baseUrl),
window.location.origin,
);
if (baseUrlParam) {
url.searchParams.set("base_url", baseUrlParam);
}
return requestJson<string[]>(url.pathname + url.search, {}, "");
},
getAnthropicApiKeyExists(baseUrl?: string) {
return requestJson<boolean>("/anthropic/key/exists", {}, baseUrl);
},
setAnthropicApiKey(api_key: string, baseUrl?: string) {
return requestJson<boolean>(
"/anthropic/key",
{ method: "POST", body: JSON.stringify({ api_key }) },
baseUrl,
);
},
readFile(path: string, baseUrl?: string) {
return requestJson<string>(
"/fs/read",
{ method: "POST", body: JSON.stringify({ path }) },
baseUrl,
);
},
writeFile(path: string, content: string, baseUrl?: string) {
return requestJson<boolean>(
"/fs/write",
{ method: "POST", body: JSON.stringify({ path, content }) },
baseUrl,
);
},
listDirectory(path: string, baseUrl?: string) {
return requestJson<FileEntry[]>(
"/fs/list",
{ method: "POST", body: JSON.stringify({ path }) },
baseUrl,
);
},
searchFiles(query: string, baseUrl?: string) {
return requestJson<SearchResult[]>(
"/fs/search",
{ method: "POST", body: JSON.stringify({ query }) },
baseUrl,
);
},
execShell(command: string, args: string[], baseUrl?: string) {
return requestJson<CommandOutput>(
"/shell/exec",
{ method: "POST", body: JSON.stringify({ command, args }) },
baseUrl,
);
},
cancelChat(baseUrl?: string) {
return requestJson<boolean>("/chat/cancel", { method: "POST" }, baseUrl);
},
};
export class ChatWebSocket {
private socket?: WebSocket;
private onToken?: (content: string) => void;
private onUpdate?: (messages: Message[]) => void;
private onError?: (message: string) => void;
connect(
handlers: {
onToken?: (content: string) => void;
onUpdate?: (messages: Message[]) => void;
onError?: (message: string) => void;
},
wsPath = DEFAULT_WS_PATH,
) {
this.onToken = handlers.onToken;
this.onUpdate = handlers.onUpdate;
this.onError = handlers.onError;
const protocol = window.location.protocol === "https:" ? "wss" : "ws";
const wsUrl = `${protocol}://${window.location.host}${wsPath}`;
this.socket = new WebSocket(wsUrl);
this.socket.onmessage = (event) => {
try {
const data = JSON.parse(event.data) as WsResponse;
if (data.type === "token") this.onToken?.(data.content);
if (data.type === "update") this.onUpdate?.(data.messages);
if (data.type === "error") this.onError?.(data.message);
} catch (err) {
this.onError?.(String(err));
}
};
this.socket.onerror = () => {
this.onError?.("WebSocket error");
};
}
sendChat(messages: Message[], config: ProviderConfig) {
this.send({ type: "chat", messages, config });
}
cancel() {
this.send({ type: "cancel" });
}
close() {
this.socket?.close();
}
private send(payload: WsRequest) {
if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
this.onError?.("WebSocket is not connected");
return;
}
this.socket.send(JSON.stringify(payload));
}
}

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

View File

@@ -0,0 +1,906 @@
import * as React from "react";
import Markdown from "react-markdown";
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import { oneDark } from "react-syntax-highlighter/dist/esm/styles/prism";
import { api, ChatWebSocket } from "../api/client";
import type { Message, ProviderConfig, ToolCall } from "../types";
const { useCallback, useEffect, useRef, useState } = React;
interface ChatProps {
projectPath: string;
onCloseProject: () => void;
}
export function Chat({ projectPath, onCloseProject }: ChatProps) {
const [messages, setMessages] = useState<Message[]>([]);
const [input, setInput] = useState("");
const [loading, setLoading] = useState(false);
const [model, setModel] = useState("llama3.1");
const [enableTools, setEnableTools] = useState(true);
const [availableModels, setAvailableModels] = useState<string[]>([]);
const [claudeModels] = useState<string[]>([
"claude-3-5-sonnet-20241022",
"claude-3-5-haiku-20241022",
]);
const [streamingContent, setStreamingContent] = useState("");
const [showApiKeyDialog, setShowApiKeyDialog] = useState(false);
const [apiKeyInput, setApiKeyInput] = useState("");
const wsRef = useRef<ChatWebSocket | null>(null);
const messagesEndRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const scrollContainerRef = useRef<HTMLDivElement>(null);
const shouldAutoScrollRef = useRef(true);
const lastScrollTopRef = useRef(0);
const userScrolledUpRef = useRef(false);
const pendingMessageRef = useRef<string>("");
const estimateTokens = (text: string): number => Math.ceil(text.length / 4);
const getContextWindowSize = (modelName: string): number => {
if (modelName.startsWith("claude-")) return 200000;
if (modelName.includes("llama3")) return 8192;
if (modelName.includes("qwen2.5")) return 32768;
if (modelName.includes("deepseek")) return 16384;
return 8192;
};
const calculateContextUsage = (): {
used: number;
total: number;
percentage: number;
} => {
let totalTokens = 0;
totalTokens += 200;
for (const msg of messages) {
totalTokens += estimateTokens(msg.content);
if (msg.tool_calls) {
totalTokens += estimateTokens(JSON.stringify(msg.tool_calls));
}
}
if (streamingContent) {
totalTokens += estimateTokens(streamingContent);
}
const contextWindow = getContextWindowSize(model);
const percentage = Math.round((totalTokens / contextWindow) * 100);
return {
used: totalTokens,
total: contextWindow,
percentage,
};
};
const contextUsage = calculateContextUsage();
const getContextEmoji = (percentage: number): string => {
if (percentage >= 90) return "🔴";
if (percentage >= 75) return "🟡";
return "🟢";
};
useEffect(() => {
api
.getOllamaModels()
.then(async (models) => {
if (models.length > 0) {
const sortedModels = models.sort((a, b) =>
a.toLowerCase().localeCompare(b.toLowerCase()),
);
setAvailableModels(sortedModels);
try {
const savedModel = await api.getModelPreference();
if (savedModel) {
setModel(savedModel);
} else if (sortedModels.length > 0) {
setModel(sortedModels[0]);
}
} catch (e) {
console.error(e);
}
}
})
.catch((err) => console.error(err));
}, []);
useEffect(() => {
const ws = new ChatWebSocket();
wsRef.current = ws;
ws.connect({
onToken: (content) => {
setStreamingContent((prev: string) => prev + content);
},
onUpdate: (history) => {
setMessages(history);
setStreamingContent("");
const last = history[history.length - 1];
if (last?.role === "assistant" && !last.tool_calls) {
setLoading(false);
}
},
onError: (message) => {
console.error("WebSocket error:", message);
setLoading(false);
},
});
return () => {
ws.close();
wsRef.current = null;
};
}, []);
const scrollToBottom = useCallback(() => {
const element = scrollContainerRef.current;
if (element) {
element.scrollTop = element.scrollHeight;
lastScrollTopRef.current = element.scrollHeight;
}
}, []);
const handleScroll = () => {
const element = scrollContainerRef.current;
if (!element) return;
const currentScrollTop = element.scrollTop;
const isAtBottom =
element.scrollHeight - element.scrollTop - element.clientHeight < 5;
if (currentScrollTop < lastScrollTopRef.current) {
userScrolledUpRef.current = true;
shouldAutoScrollRef.current = false;
}
if (isAtBottom) {
userScrolledUpRef.current = false;
shouldAutoScrollRef.current = true;
}
lastScrollTopRef.current = currentScrollTop;
};
const autoScrollKey = messages.length + streamingContent.length;
useEffect(() => {
if (
autoScrollKey >= 0 &&
shouldAutoScrollRef.current &&
!userScrolledUpRef.current
) {
scrollToBottom();
}
}, [autoScrollKey, scrollToBottom]);
useEffect(() => {
inputRef.current?.focus();
}, []);
const cancelGeneration = async () => {
try {
wsRef.current?.cancel();
await api.cancelChat();
if (streamingContent) {
setMessages((prev: Message[]) => [
...prev,
{ role: "assistant", content: streamingContent },
]);
setStreamingContent("");
}
setLoading(false);
} catch (e) {
console.error("Failed to cancel chat:", e);
}
};
const sendMessage = async (messageOverride?: string) => {
const messageToSend = messageOverride ?? input;
if (!messageToSend.trim() || loading) return;
if (model.startsWith("claude-")) {
const hasKey = await api.getAnthropicApiKeyExists();
if (!hasKey) {
pendingMessageRef.current = messageToSend;
setShowApiKeyDialog(true);
return;
}
}
const userMsg: Message = { role: "user", content: messageToSend };
const newHistory = [...messages, userMsg];
setMessages(newHistory);
if (!messageOverride || messageOverride === input) {
setInput("");
}
setLoading(true);
setStreamingContent("");
try {
const config: ProviderConfig = {
provider: model.startsWith("claude-") ? "anthropic" : "ollama",
model,
base_url: "http://localhost:11434",
enable_tools: enableTools,
};
wsRef.current?.sendChat(newHistory, config);
} catch (e) {
console.error("Chat error:", e);
const errorMessage = String(e);
if (!errorMessage.includes("Chat cancelled by user")) {
setMessages((prev: Message[]) => [
...prev,
{ role: "assistant", content: `**Error:** ${e}` },
]);
}
setLoading(false);
}
};
const handleSaveApiKey = async () => {
if (!apiKeyInput.trim()) return;
try {
await api.setAnthropicApiKey(apiKeyInput);
setShowApiKeyDialog(false);
setApiKeyInput("");
const pendingMessage = pendingMessageRef.current;
pendingMessageRef.current = "";
if (pendingMessage.trim()) {
sendMessage(pendingMessage);
}
} catch (e) {
console.error("Failed to save API key:", e);
alert(`Failed to save API key: ${e}`);
}
};
const clearSession = async () => {
const confirmed = window.confirm(
"Are you sure? This will clear all messages and reset the conversation context.",
);
if (confirmed) {
try {
await api.cancelChat();
wsRef.current?.cancel();
} catch (e) {
console.error("Failed to cancel chat:", e);
}
setMessages([]);
setStreamingContent("");
setLoading(false);
}
};
return (
<div
className="chat-container"
style={{
display: "flex",
flexDirection: "column",
height: "100%",
backgroundColor: "#171717",
color: "#ececec",
}}
>
<div
style={{
padding: "12px 24px",
borderBottom: "1px solid #333",
display: "flex",
alignItems: "center",
justifyContent: "space-between",
background: "#171717",
flexShrink: 0,
fontSize: "0.9rem",
color: "#ececec",
}}
>
<div
style={{
display: "flex",
alignItems: "center",
gap: "12px",
overflow: "hidden",
flex: 1,
marginRight: "20px",
}}
>
<div
title={projectPath}
style={{
whiteSpace: "nowrap",
overflow: "hidden",
textOverflow: "ellipsis",
fontWeight: "500",
color: "#aaa",
direction: "rtl",
textAlign: "left",
fontFamily: "monospace",
fontSize: "0.85em",
}}
>
{projectPath}
</div>
<button
type="button"
onClick={onCloseProject}
style={{
background: "transparent",
border: "none",
cursor: "pointer",
color: "#999",
fontSize: "0.8em",
padding: "4px 8px",
borderRadius: "4px",
}}
onMouseOver={(e) => {
e.currentTarget.style.background = "#333";
}}
onMouseOut={(e) => {
e.currentTarget.style.background = "transparent";
}}
onFocus={(e) => {
e.currentTarget.style.background = "#333";
}}
onBlur={(e) => {
e.currentTarget.style.background = "transparent";
}}
>
</button>
</div>
<div style={{ display: "flex", alignItems: "center", gap: "16px" }}>
<div
style={{
fontSize: "0.9em",
color: "#ccc",
whiteSpace: "nowrap",
}}
title={`Context: ${contextUsage.used.toLocaleString()} / ${contextUsage.total.toLocaleString()} tokens (${contextUsage.percentage}%)`}
>
{getContextEmoji(contextUsage.percentage)} {contextUsage.percentage}
%
</div>
<button
type="button"
onClick={clearSession}
style={{
padding: "6px 12px",
borderRadius: "99px",
border: "none",
fontSize: "0.85em",
backgroundColor: "#2f2f2f",
color: "#888",
cursor: "pointer",
outline: "none",
transition: "all 0.2s",
}}
onMouseOver={(e) => {
e.currentTarget.style.backgroundColor = "#3f3f3f";
e.currentTarget.style.color = "#ccc";
}}
onMouseOut={(e) => {
e.currentTarget.style.backgroundColor = "#2f2f2f";
e.currentTarget.style.color = "#888";
}}
onFocus={(e) => {
e.currentTarget.style.backgroundColor = "#3f3f3f";
e.currentTarget.style.color = "#ccc";
}}
onBlur={(e) => {
e.currentTarget.style.backgroundColor = "#2f2f2f";
e.currentTarget.style.color = "#888";
}}
>
🔄 New Session
</button>
{availableModels.length > 0 || claudeModels.length > 0 ? (
<select
value={model}
onChange={(e) => {
const newModel = e.target.value;
setModel(newModel);
api.setModelPreference(newModel).catch(console.error);
}}
style={{
padding: "6px 32px 6px 16px",
borderRadius: "99px",
border: "none",
fontSize: "0.9em",
backgroundColor: "#2f2f2f",
color: "#ececec",
cursor: "pointer",
outline: "none",
appearance: "none",
WebkitAppearance: "none",
backgroundImage: `url("data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22292.4%22%20height%3D%22292.4%22%3E%3Cpath%20fill%3D%22%23ececec%22%20d%3D%22M287%2069.4a17.6%2017.6%200%200%200-13-5.4H18.4c-5%200-9.3%201.8-12.9%205.4A17.6%2017.6%200%200%200%200%2082.2c0%205%201.8%209.3%205.4%2012.9l128%20127.9c3.6%203.6%207.8%205.4%2012.8%205.4s9.2-1.8%2012.8-5.4L287%2095c3.5-3.5%205.4-7.8%205.4-12.8%200-5-1.9-9.2-5.5-12.8z%22%2F%3E%3C%2Fsvg%3E")`,
backgroundRepeat: "no-repeat",
backgroundPosition: "right 12px center",
backgroundSize: "10px",
}}
>
{claudeModels.length > 0 && (
<optgroup label="Anthropic">
{claudeModels.map((m: string) => (
<option key={m} value={m}>
{m}
</option>
))}
</optgroup>
)}
{availableModels.length > 0 && (
<optgroup label="Ollama">
{availableModels.map((m: string) => (
<option key={m} value={m}>
{m}
</option>
))}
</optgroup>
)}
</select>
) : (
<input
value={model}
onChange={(e) => {
const newModel = e.target.value;
setModel(newModel);
api.setModelPreference(newModel).catch(console.error);
}}
placeholder="Model"
style={{
padding: "6px 12px",
borderRadius: "99px",
border: "none",
fontSize: "0.9em",
background: "#2f2f2f",
color: "#ececec",
outline: "none",
}}
/>
)}
<label
style={{
display: "flex",
alignItems: "center",
gap: "6px",
cursor: "pointer",
fontSize: "0.9em",
color: "#aaa",
}}
title="Allow the Agent to read/write files"
>
<input
type="checkbox"
checked={enableTools}
onChange={(e) => setEnableTools(e.target.checked)}
style={{ accentColor: "#000" }}
/>
<span>Tools</span>
</label>
</div>
</div>
<div
ref={scrollContainerRef}
onScroll={handleScroll}
style={{
flex: 1,
overflowY: "auto",
padding: "20px 0",
display: "flex",
flexDirection: "column",
gap: "24px",
}}
>
<div
style={{
maxWidth: "768px",
margin: "0 auto",
width: "100%",
padding: "0 24px",
display: "flex",
flexDirection: "column",
gap: "24px",
}}
>
{messages.map((msg: Message, idx: number) => (
<div
key={`msg-${idx}-${msg.role}-${msg.content.substring(0, 20)}`}
style={{
display: "flex",
flexDirection: "column",
alignItems: msg.role === "user" ? "flex-end" : "flex-start",
}}
>
<div
style={{
maxWidth: "100%",
padding: msg.role === "user" ? "10px 16px" : "0",
borderRadius: msg.role === "user" ? "20px" : "0",
background:
msg.role === "user"
? "#2f2f2f"
: msg.role === "tool"
? "#222"
: "transparent",
color: "#ececec",
border: msg.role === "tool" ? "1px solid #333" : "none",
fontFamily: msg.role === "tool" ? "monospace" : "inherit",
fontSize: msg.role === "tool" ? "0.85em" : "1em",
fontWeight: "500",
whiteSpace: msg.role === "tool" ? "pre-wrap" : "normal",
lineHeight: "1.6",
}}
>
{msg.role === "user" ? (
msg.content
) : msg.role === "tool" ? (
<details style={{ cursor: "pointer" }}>
<summary
style={{
color: "#aaa",
fontSize: "0.9em",
marginBottom: "8px",
listStyle: "none",
display: "flex",
alignItems: "center",
gap: "6px",
}}
>
<span style={{ fontSize: "0.8em" }}></span>
<span>
Tool Output
{msg.tool_call_id && ` (${msg.tool_call_id})`}
</span>
</summary>
<pre
style={{
maxHeight: "300px",
overflow: "auto",
margin: 0,
padding: "8px",
background: "#1a1a1a",
borderRadius: "4px",
fontSize: "0.85em",
whiteSpace: "pre-wrap",
wordBreak: "break-word",
}}
>
{msg.content}
</pre>
</details>
) : (
<div className="markdown-body">
<Markdown
components={{
// eslint-disable-next-line @typescript-eslint/no-explicit-any
// biome-ignore lint/suspicious/noExplicitAny: react-markdown requires any for component props
code: ({ className, children, ...props }: any) => {
const match = /language-(\w+)/.exec(className || "");
const isInline = !className;
return !isInline && match ? (
<SyntaxHighlighter
// biome-ignore lint/suspicious/noExplicitAny: oneDark style types are incompatible
style={oneDark as any}
language={match[1]}
PreTag="div"
>
{String(children).replace(/\n$/, "")}
</SyntaxHighlighter>
) : (
<code className={className} {...props}>
{children}
</code>
);
},
}}
>
{msg.content}
</Markdown>
</div>
)}
{msg.tool_calls && (
<div
style={{
marginTop: "12px",
fontSize: "0.85em",
color: "#aaa",
display: "flex",
flexDirection: "column",
gap: "8px",
}}
>
{msg.tool_calls.map((tc: ToolCall, i: number) => {
let argsSummary = "";
try {
const args = JSON.parse(tc.function.arguments);
const firstKey = Object.keys(args)[0];
if (firstKey && args[firstKey]) {
argsSummary = String(args[firstKey]);
if (argsSummary.length > 50) {
argsSummary = `${argsSummary.substring(0, 47)}...`;
}
}
} catch (_e) {
// ignore
}
return (
<div
key={`tool-${i}-${tc.function.name}`}
style={{
display: "flex",
alignItems: "center",
gap: "8px",
fontFamily: "monospace",
}}
>
<span style={{ color: "#888" }}></span>
<span
style={{
background: "#333",
padding: "2px 6px",
borderRadius: "4px",
}}
>
{tc.function.name}
{argsSummary && `(${argsSummary})`}
</span>
</div>
);
})}
</div>
)}
</div>
</div>
))}
{loading && streamingContent && (
<div
style={{
display: "flex",
flexDirection: "column",
alignItems: "flex-start",
}}
>
<div
style={{
maxWidth: "85%",
padding: "16px 20px",
borderRadius: "12px",
background: "#262626",
color: "#fff",
border: "1px solid #404040",
fontFamily: "system-ui, -apple-system, sans-serif",
fontSize: "0.95rem",
fontWeight: 400,
whiteSpace: "pre-wrap",
lineHeight: 1.6,
}}
>
<Markdown
components={{
// eslint-disable-next-line @typescript-eslint/no-explicit-any
// biome-ignore lint/suspicious/noExplicitAny: react-markdown requires any for component props
code: ({ className, children, ...props }: any) => {
const match = /language-(\w+)/.exec(className || "");
const isInline = !className;
return !isInline && match ? (
<SyntaxHighlighter
// biome-ignore lint/suspicious/noExplicitAny: oneDark style types are incompatible
style={oneDark as any}
language={match[1]}
PreTag="div"
>
{String(children).replace(/\n$/, "")}
</SyntaxHighlighter>
) : (
<code className={className} {...props}>
{children}
</code>
);
},
}}
>
{streamingContent}
</Markdown>
</div>
</div>
)}
{loading && !streamingContent && (
<div
style={{
alignSelf: "flex-start",
color: "#888",
fontSize: "0.9em",
marginTop: "10px",
}}
>
<span className="pulse">Thinking...</span>
</div>
)}
<div ref={messagesEndRef} />
</div>
</div>
<div
style={{
padding: "24px",
background: "#171717",
display: "flex",
justifyContent: "center",
}}
>
<div
style={{
maxWidth: "768px",
width: "100%",
display: "flex",
gap: "8px",
alignItems: "center",
}}
>
<input
ref={inputRef}
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") {
sendMessage();
}
}}
placeholder="Send a message..."
style={{
flex: 1,
padding: "14px 20px",
borderRadius: "24px",
border: "1px solid #333",
outline: "none",
fontSize: "1rem",
fontWeight: "500",
background: "#2f2f2f",
color: "#ececec",
boxShadow: "0 2px 6px rgba(0,0,0,0.02)",
}}
/>
<button
type="button"
onClick={loading ? cancelGeneration : () => sendMessage()}
disabled={!loading && !input.trim()}
style={{
background: "#ececec",
color: "black",
border: "none",
borderRadius: "50%",
width: "32px",
height: "32px",
display: "flex",
alignItems: "center",
justifyContent: "center",
cursor: "pointer",
opacity: !loading && !input.trim() ? 0.5 : 1,
flexShrink: 0,
}}
>
{loading ? "■" : "↑"}
</button>
</div>
</div>
{showApiKeyDialog && (
<div
style={{
position: "fixed",
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: "rgba(0, 0, 0, 0.7)",
display: "flex",
alignItems: "center",
justifyContent: "center",
zIndex: 1000,
}}
>
<div
style={{
backgroundColor: "#2f2f2f",
padding: "32px",
borderRadius: "12px",
maxWidth: "500px",
width: "90%",
border: "1px solid #444",
}}
>
<h2 style={{ marginTop: 0, color: "#ececec" }}>
Enter Anthropic API Key
</h2>
<p
style={{ color: "#aaa", fontSize: "0.9em", marginBottom: "20px" }}
>
To use Claude models, please enter your Anthropic API key. Your
key will be stored server-side and reused across sessions.
</p>
<input
type="password"
value={apiKeyInput}
onChange={(e) => setApiKeyInput(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && handleSaveApiKey()}
placeholder="sk-ant-..."
style={{
width: "100%",
padding: "12px",
borderRadius: "8px",
border: "1px solid #555",
backgroundColor: "#1a1a1a",
color: "#ececec",
fontSize: "1em",
marginBottom: "20px",
outline: "none",
}}
/>
<div
style={{
display: "flex",
gap: "12px",
justifyContent: "flex-end",
}}
>
<button
type="button"
onClick={() => {
setShowApiKeyDialog(false);
setApiKeyInput("");
pendingMessageRef.current = "";
}}
style={{
padding: "10px 20px",
borderRadius: "8px",
border: "1px solid #555",
backgroundColor: "transparent",
color: "#aaa",
cursor: "pointer",
fontSize: "0.9em",
}}
>
Cancel
</button>
<button
type="button"
onClick={handleSaveApiKey}
disabled={!apiKeyInput.trim()}
style={{
padding: "10px 20px",
borderRadius: "8px",
border: "none",
backgroundColor: apiKeyInput.trim() ? "#ececec" : "#555",
color: apiKeyInput.trim() ? "#000" : "#888",
cursor: apiKeyInput.trim() ? "pointer" : "not-allowed",
fontSize: "0.9em",
}}
>
Save Key
</button>
</div>
</div>
</div>
)}
</div>
);
}

9
frontend/src/main.tsx Normal file
View File

@@ -0,0 +1,9 @@
import * as React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
<App />
</React.StrictMode>,
);

66
frontend/src/types.ts Normal file
View File

@@ -0,0 +1,66 @@
export type Role = "system" | "user" | "assistant" | "tool";
export interface ToolCall {
id?: string;
type: string;
function: {
name: string;
arguments: string;
};
}
export interface Message {
role: Role;
content: string;
tool_calls?: ToolCall[];
tool_call_id?: string;
}
export interface ProviderConfig {
provider: string;
model: string;
base_url?: string;
enable_tools?: boolean;
}
export interface FileEntry {
name: string;
kind: "file" | "dir";
}
export interface SearchResult {
path: string;
matches: number;
}
export interface CommandOutput {
stdout: string;
stderr: string;
exit_code: number;
}
export type WsRequest =
| {
type: "chat";
messages: Message[];
config: ProviderConfig;
}
| {
type: "cancel";
};
export type WsResponse =
| { type: "token"; content: string }
| { type: "update"; messages: Message[] }
| { type: "error"; message: string };
// Re-export API client types for convenience
export type {
Message as ApiMessage,
ProviderConfig as ApiProviderConfig,
FileEntry as ApiFileEntry,
SearchResult as ApiSearchResult,
CommandOutput as ApiCommandOutput,
WsRequest as ApiWsRequest,
WsResponse as ApiWsResponse,
};

10
frontend/src/vite-env.d.ts vendored Normal file
View File

@@ -0,0 +1,10 @@
/// <reference types="vite/client" />
declare module "react" {
interface InputHTMLAttributes<T> {
webkitdirectory?: string;
directory?: string;
}
}
export {};