feat: initial commit of Claudia v0.1.0

This commit is contained in:
2025-10-11 16:21:11 -07:00
commit 04b490b5b9
35 changed files with 8005 additions and 0 deletions

View File

@@ -0,0 +1,17 @@
{
"permissions": {
"allow": [
"Bash(find:*)",
"Bash(npm run tauri:*)",
"Bash(cargo build:*)",
"Bash(./src-tauri/target/debug/tauri-app:*)",
"Bash(echo $XDG_SESSION_TYPE)",
"Bash(WAYLAND_DISPLAY=\"\" DISPLAY=:0 ./src-tauri/target/debug/tauri-app:*)",
"Bash(ldd:*)",
"Read(//home/matt/.config/claudia/**)",
"WebFetch(domain:github.com)"
],
"deny": [],
"ask": []
}
}

24
.gitignore vendored Normal file
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?

3
.vscode/extensions.json vendored Normal file
View File

@@ -0,0 +1,3 @@
{
"recommendations": ["tauri-apps.tauri-vscode", "rust-lang.rust-analyzer"]
}

61
README.md Normal file
View File

@@ -0,0 +1,61 @@
# Claudia
Beautiful AI desktop companion built with Tauri and Rust.
## Features
### Core Features
- 🎨 **Beautiful glassmorphic UI** with gradient backgrounds and blur effects
- 🔧 **Bring-your-own-API** - supports any Anthropic-compatible API
-**API validation** via /v1/models endpoint
- 💬 **Full conversation context** - AI remembers your entire conversation
- 💾 **Persistent chat history** - conversations saved between sessions
- 🎯 **Custom window controls** - drag, minimize, maximize, close
### Message Display
- 📝 **Full markdown rendering** - headers, lists, tables, links, blockquotes
- 🎨 **Syntax highlighting** - beautiful code blocks with highlight.js
- 📋 **Copy code blocks** - one-click copy button on hover
-**Smooth animations** - elegant message transitions
### User Experience
- ⌨️ **Keyboard shortcuts** - Enter or Ctrl+Enter to send, Shift+Enter for new lines
- 🗑️ **Clear conversations** - easily start fresh
- 🎯 **Auto-resizing input** - textarea grows with your message
- 🎭 **Light/dark mode** - automatic based on system preferences
## Running
```bash
npm install
npm run dev
```
Build:
```bash
npm run build
```
**Note**: The dev script includes `WEBKIT_DISABLE_DMABUF_RENDERER=1` to fix Wayland compatibility issues on KDE Plasma.
## Configuration
On first launch, click settings and configure:
- Base URL (e.g., https://api.anthropic.com)
- API Key
- Model (validated from /v1/models endpoint)
- Config stored in `~/.config/claudia/config.json`
- Chat history stored in `~/.config/claudia/history.json`
## Usage
### Keyboard Shortcuts
- **Enter** - Send message
- **Shift+Enter** - New line in message
### Interface
- **Drag header** - Move window around your desktop
- **Trash icon** - Clear conversation history
- **Settings icon** - Configure API settings
- **Minimize/Maximize** - Window controls

232
package-lock.json generated Normal file
View File

@@ -0,0 +1,232 @@
{
"name": "tauri-app",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "tauri-app",
"version": "0.1.0",
"devDependencies": {
"@tauri-apps/cli": "^2"
}
},
"node_modules/@tauri-apps/cli": {
"version": "2.8.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli/-/cli-2.8.4.tgz",
"integrity": "sha512-ejUZBzuQRcjFV+v/gdj/DcbyX/6T4unZQjMSBZwLzP/CymEjKcc2+Fc8xTORThebHDUvqoXMdsCZt8r+hyN15g==",
"dev": true,
"license": "Apache-2.0 OR MIT",
"bin": {
"tauri": "tauri.js"
},
"engines": {
"node": ">= 10"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/tauri"
},
"optionalDependencies": {
"@tauri-apps/cli-darwin-arm64": "2.8.4",
"@tauri-apps/cli-darwin-x64": "2.8.4",
"@tauri-apps/cli-linux-arm-gnueabihf": "2.8.4",
"@tauri-apps/cli-linux-arm64-gnu": "2.8.4",
"@tauri-apps/cli-linux-arm64-musl": "2.8.4",
"@tauri-apps/cli-linux-riscv64-gnu": "2.8.4",
"@tauri-apps/cli-linux-x64-gnu": "2.8.4",
"@tauri-apps/cli-linux-x64-musl": "2.8.4",
"@tauri-apps/cli-win32-arm64-msvc": "2.8.4",
"@tauri-apps/cli-win32-ia32-msvc": "2.8.4",
"@tauri-apps/cli-win32-x64-msvc": "2.8.4"
}
},
"node_modules/@tauri-apps/cli-darwin-arm64": {
"version": "2.8.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-arm64/-/cli-darwin-arm64-2.8.4.tgz",
"integrity": "sha512-BKu8HRkYV01SMTa7r4fLx+wjgtRK8Vep7lmBdHDioP6b8XH3q2KgsAyPWfEZaZIkZ2LY4SqqGARaE9oilNe0oA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-darwin-x64": {
"version": "2.8.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-x64/-/cli-darwin-x64-2.8.4.tgz",
"integrity": "sha512-imb9PfSd/7G6VAO7v1bQ2A3ZH4NOCbhGJFLchxzepGcXf9NKkfun157JH9mko29K6sqAwuJ88qtzbKCbWJTH9g==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-linux-arm-gnueabihf": {
"version": "2.8.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm-gnueabihf/-/cli-linux-arm-gnueabihf-2.8.4.tgz",
"integrity": "sha512-Ml215UnDdl7/fpOrF1CNovym/KjtUbCuPgrcZ4IhqUCnhZdXuphud/JT3E8X97Y03TZ40Sjz8raXYI2ET0exzw==",
"cpu": [
"arm"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-linux-arm64-gnu": {
"version": "2.8.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-gnu/-/cli-linux-arm64-gnu-2.8.4.tgz",
"integrity": "sha512-pbcgBpMyI90C83CxE5REZ9ODyIlmmAPkkJXtV398X3SgZEIYy5TACYqlyyv2z5yKgD8F8WH4/2fek7+jH+ZXAw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-linux-arm64-musl": {
"version": "2.8.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.8.4.tgz",
"integrity": "sha512-zumFeaU1Ws5Ay872FTyIm7z8kfzEHu8NcIn8M6TxbJs0a7GRV21KBdpW1zNj2qy7HynnpQCqjAYXTUUmm9JAOw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-linux-riscv64-gnu": {
"version": "2.8.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-riscv64-gnu/-/cli-linux-riscv64-gnu-2.8.4.tgz",
"integrity": "sha512-qiqbB3Zz6IyO201f+1ojxLj65WYj8mixL5cOMo63nlg8CIzsP23cPYUrx1YaDPsCLszKZo7tVs14pc7BWf+/aQ==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-linux-x64-gnu": {
"version": "2.8.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-gnu/-/cli-linux-x64-gnu-2.8.4.tgz",
"integrity": "sha512-TaqaDd9Oy6k45Hotx3pOf+pkbsxLaApv4rGd9mLuRM1k6YS/aw81YrsMryYPThrxrScEIUcmNIHaHsLiU4GMkw==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-linux-x64-musl": {
"version": "2.8.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-musl/-/cli-linux-x64-musl-2.8.4.tgz",
"integrity": "sha512-ot9STAwyezN8w+bBHZ+bqSQIJ0qPZFlz/AyscpGqB/JnJQVDFQcRDmUPFEaAtt2UUHSWzN3GoTJ5ypqLBp2WQA==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-win32-arm64-msvc": {
"version": "2.8.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-arm64-msvc/-/cli-win32-arm64-msvc-2.8.4.tgz",
"integrity": "sha512-+2aJ/g90dhLiOLFSD1PbElXX3SoMdpO7HFPAZB+xot3CWlAZD1tReUFy7xe0L5GAR16ZmrxpIDM9v9gn5xRy/w==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-win32-ia32-msvc": {
"version": "2.8.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-ia32-msvc/-/cli-win32-ia32-msvc-2.8.4.tgz",
"integrity": "sha512-yj7WDxkL1t9Uzr2gufQ1Hl7hrHuFKTNEOyascbc109EoiAqCp0tgZ2IykQqOZmZOHU884UAWI1pVMqBhS/BfhA==",
"cpu": [
"ia32"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-win32-x64-msvc": {
"version": "2.8.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-x64-msvc/-/cli-win32-x64-msvc-2.8.4.tgz",
"integrity": "sha512-XuvGB4ehBdd7QhMZ9qbj/8icGEatDuBNxyYHbLKsTYh90ggUlPa/AtaqcC1Fo69lGkTmq9BOKrs1aWSi7xDonA==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
}
}
}

14
package.json Normal file
View File

@@ -0,0 +1,14 @@
{
"name": "tauri-app",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"tauri": "tauri",
"dev": "WEBKIT_DISABLE_DMABUF_RENDERER=1 tauri dev",
"build": "tauri build"
},
"devDependencies": {
"@tauri-apps/cli": "^2"
}
}

7
src-tauri/.gitignore vendored Normal file
View File

@@ -0,0 +1,7 @@
# Generated by Cargo
# will have compiled files and executables
/target/
# Generated by Tauri
# will have schema files for capabilities auto-completion
/gen/schemas

5649
src-tauri/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

28
src-tauri/Cargo.toml Normal file
View File

@@ -0,0 +1,28 @@
[package]
name = "tauri-app"
version = "0.1.0"
description = "A Tauri App"
authors = ["you"]
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
# The `_lib` suffix may seem redundant but it is necessary
# to make the lib name unique and wouldn't conflict with the bin name.
# This seems to be only an issue on Windows, see https://github.com/rust-lang/cargo/issues/8519
name = "tauri_app_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dependencies]
tauri = { version = "2", features = [] }
tauri-plugin-opener = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
reqwest = { version = "0.12", features = ["json"] }
tokio = { version = "1", features = ["full"] }
uuid = { version = "1", features = ["v4"] }

3
src-tauri/build.rs Normal file
View File

@@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}

View File

@@ -0,0 +1,10 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Capability for the main window",
"windows": ["main"],
"permissions": [
"core:default",
"opener:default"
]
}

BIN
src-tauri/icons/128x128.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

BIN
src-tauri/icons/32x32.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 974 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 903 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

BIN
src-tauri/icons/icon.icns Normal file

Binary file not shown.

BIN
src-tauri/icons/icon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

BIN
src-tauri/icons/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

432
src-tauri/src/lib.rs Normal file
View File

@@ -0,0 +1,432 @@
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;
use uuid::Uuid;
#[derive(Debug, Clone, Serialize, Deserialize)]
struct ApiConfig {
base_url: String,
api_key: String,
model: String,
#[serde(default)]
active_character_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Character {
id: String,
name: String,
avatar_path: Option<String>,
system_prompt: String,
greeting: Option<String>,
personality: Option<String>,
created_at: i64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Message {
role: String,
content: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct ChatHistory {
messages: Vec<Message>,
}
#[derive(Debug, Serialize, Deserialize)]
struct ChatRequest {
model: String,
max_tokens: u32,
messages: Vec<Message>,
}
#[derive(Debug, Serialize, Deserialize)]
struct ChatResponse {
choices: Vec<Choice>,
}
#[derive(Debug, Serialize, Deserialize)]
struct Choice {
message: ResponseMessage,
}
#[derive(Debug, Serialize, Deserialize)]
struct ResponseMessage {
content: String,
}
#[derive(Debug, Serialize, Deserialize)]
struct Model {
id: String,
}
#[derive(Debug, Serialize, Deserialize)]
struct ModelsResponse {
data: Vec<Model>,
}
fn get_config_path() -> PathBuf {
let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".to_string());
PathBuf::from(home).join(".config/claudia/config.json")
}
fn get_characters_dir() -> PathBuf {
let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".to_string());
PathBuf::from(home).join(".config/claudia/characters")
}
fn get_character_path(character_id: &str) -> PathBuf {
get_characters_dir().join(format!("{}.json", character_id))
}
fn get_character_history_path(character_id: &str) -> PathBuf {
let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".to_string());
PathBuf::from(home).join(format!(".config/claudia/history_{}.json", character_id))
}
fn load_config() -> Option<ApiConfig> {
let path = get_config_path();
if let Ok(contents) = fs::read_to_string(path) {
serde_json::from_str(&contents).ok()
} else {
None
}
}
fn save_config(config: &ApiConfig) -> Result<(), String> {
let path = get_config_path();
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).map_err(|e| e.to_string())?;
}
let contents = serde_json::to_string_pretty(config).map_err(|e| e.to_string())?;
fs::write(path, contents).map_err(|e| e.to_string())?;
Ok(())
}
fn load_history(character_id: &str) -> ChatHistory {
let path = get_character_history_path(character_id);
if let Ok(contents) = fs::read_to_string(path) {
serde_json::from_str(&contents).unwrap_or(ChatHistory { messages: vec![] })
} else {
ChatHistory { messages: vec![] }
}
}
fn save_history(character_id: &str, history: &ChatHistory) -> Result<(), String> {
let path = get_character_history_path(character_id);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).map_err(|e| e.to_string())?;
}
let contents = serde_json::to_string_pretty(history).map_err(|e| e.to_string())?;
fs::write(path, contents).map_err(|e| e.to_string())?;
Ok(())
}
fn load_character(character_id: &str) -> Option<Character> {
let path = get_character_path(character_id);
if let Ok(contents) = fs::read_to_string(path) {
serde_json::from_str(&contents).ok()
} else {
None
}
}
fn save_character(character: &Character) -> Result<(), String> {
let dir = get_characters_dir();
fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
let path = get_character_path(&character.id);
let contents = serde_json::to_string_pretty(character).map_err(|e| e.to_string())?;
fs::write(path, contents).map_err(|e| e.to_string())?;
Ok(())
}
fn create_default_character() -> Character {
Character {
id: "default".to_string(),
name: "Assistant".to_string(),
avatar_path: None,
system_prompt: "You are a helpful AI assistant. Be friendly, concise, and informative.".to_string(),
greeting: Some("Hello! How can I help you today?".to_string()),
personality: Some("helpful, friendly, knowledgeable".to_string()),
created_at: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs() as i64,
}
}
fn get_active_character() -> Character {
// Try to load active character from config
if let Some(config) = load_config() {
if let Some(character_id) = config.active_character_id {
if let Some(character) = load_character(&character_id) {
return character;
}
}
}
// Try to load default character
if let Some(character) = load_character("default") {
return character;
}
// Create and save default character
let character = create_default_character();
save_character(&character).ok();
character
}
#[tauri::command]
fn get_character() -> Result<Character, String> {
Ok(get_active_character())
}
#[tauri::command]
fn update_character(
name: String,
system_prompt: String,
greeting: Option<String>,
personality: Option<String>,
) -> Result<(), String> {
let mut character = get_active_character();
character.name = name;
character.system_prompt = system_prompt;
character.greeting = greeting;
character.personality = personality;
save_character(&character)
}
#[tauri::command]
async fn validate_api(base_url: String, api_key: String) -> Result<Vec<String>, String> {
let client = reqwest::Client::new();
let base = base_url.trim_end_matches('/');
let url = if base.ends_with("/v1") {
format!("{}/models", base)
} else {
format!("{}/v1/models", base)
};
let response = client
.get(&url)
.header("authorization", format!("Bearer {}", &api_key))
.send()
.await
.map_err(|e| format!("Connection failed: {}", e))?;
if !response.status().is_success() {
return Err(format!("API returned status: {}", response.status()));
}
let models: ModelsResponse = response
.json()
.await
.map_err(|e| format!("Invalid response: {}", e))?;
Ok(models.data.into_iter().map(|m| m.id).collect())
}
#[tauri::command]
async fn save_api_config(base_url: String, api_key: String, model: String) -> Result<(), String> {
// Preserve existing active_character_id if it exists
let active_character_id = load_config().and_then(|c| c.active_character_id);
let config = ApiConfig {
base_url,
api_key,
model,
active_character_id,
};
save_config(&config)
}
#[tauri::command]
fn get_api_config() -> Result<ApiConfig, String> {
println!("Getting API config...");
load_config().ok_or_else(|| "No config found".to_string())
}
#[tauri::command]
async fn chat(message: String) -> Result<String, String> {
let config = load_config().ok_or_else(|| "API not configured".to_string())?;
let character = get_active_character();
let mut history = load_history(&character.id);
// Add user message to history
history.messages.push(Message {
role: "user".to_string(),
content: message.clone(),
});
let client = reqwest::Client::new();
let base = config.base_url.trim_end_matches('/');
let url = if base.ends_with("/v1") {
format!("{}/chat/completions", base)
} else {
format!("{}/v1/chat/completions", base)
};
// Build messages with system prompt first
let mut api_messages = vec![Message {
role: "system".to_string(),
content: character.system_prompt.clone(),
}];
api_messages.extend(history.messages.clone());
let request = ChatRequest {
model: config.model.clone(),
max_tokens: 4096,
messages: api_messages,
};
let response = client
.post(&url)
.header("authorization", format!("Bearer {}", &config.api_key))
.header("content-type", "application/json")
.json(&request)
.send()
.await
.map_err(|e| format!("Request failed: {}", e))?;
if !response.status().is_success() {
return Err(format!("API error: {}", response.status()));
}
let chat_response: ChatResponse = response
.json()
.await
.map_err(|e| format!("Parse error: {}", e))?;
let assistant_message = chat_response
.choices
.first()
.map(|c| c.message.content.clone())
.ok_or_else(|| "No response content".to_string())?;
// Add assistant message to history
history.messages.push(Message {
role: "assistant".to_string(),
content: assistant_message.clone(),
});
// Save history
save_history(&character.id, &history).ok();
Ok(assistant_message)
}
#[tauri::command]
fn get_chat_history() -> Result<Vec<Message>, String> {
let character = get_active_character();
Ok(load_history(&character.id).messages)
}
#[tauri::command]
fn clear_chat_history() -> Result<(), String> {
let character = get_active_character();
let history = ChatHistory { messages: vec![] };
save_history(&character.id, &history)
}
#[tauri::command]
fn create_character(name: String, system_prompt: String) -> Result<Character, String> {
let new_id = Uuid::new_v4().to_string();
let character = Character {
id: new_id.clone(),
name: name.clone(),
avatar_path: None,
system_prompt,
greeting: Some(format!("Hello, I'm {}. How can I help you?", name)),
personality: None,
created_at: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs() as i64,
};
save_character(&character)?;
set_active_character(new_id)?;
Ok(character)
}
#[tauri::command]
fn delete_character(character_id: String) -> Result<(), String> {
if character_id == "default" {
return Err("Cannot delete the default character.".to_string());
}
// Remove character file
let path = get_character_path(&character_id);
if path.exists() {
fs::remove_file(path).map_err(|e| e.to_string())?;
}
// Remove history file
let history_path = get_character_history_path(&character_id);
if history_path.exists() {
fs::remove_file(history_path).map_err(|e| e.to_string())?;
}
// If the deleted character was active, switch to default
if let Some(config) = load_config() {
if config.active_character_id == Some(character_id) {
set_active_character("default".to_string())?;
}
}
Ok(())
}
#[tauri::command]
fn list_characters() -> Result<Vec<Character>, String> {
println!("Listing characters...");
let dir = get_characters_dir();
if !dir.exists() {
return Ok(vec![]);
}
let mut characters = vec![];
for entry in fs::read_dir(dir).map_err(|e| e.to_string())? {
let entry = entry.map_err(|e| e.to_string())?;
let path = entry.path();
if path.is_file() && path.extension().and_then(|s| s.to_str()) == Some("json") {
if let Some(character) = load_character(path.file_stem().unwrap().to_str().unwrap()) {
characters.push(character);
}
}
}
println!("Found {} characters", characters.len());
Ok(characters)
}
#[tauri::command]
fn set_active_character(character_id: String) -> Result<(), String> {
if let Some(mut config) = load_config() {
config.active_character_id = Some(character_id);
save_config(&config)
} else {
Err("API config not found. Please configure API first.".to_string())
}
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_opener::init())
.invoke_handler(tauri::generate_handler![
chat,
validate_api,
save_api_config,
get_api_config,
get_chat_history,
clear_chat_history,
get_character,
update_character,
list_characters,
create_character,
delete_character,
set_active_character
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}

6
src-tauri/src/main.rs Normal file
View File

@@ -0,0 +1,6 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
tauri_app_lib::run()
}

41
src-tauri/tauri.conf.json Normal file
View File

@@ -0,0 +1,41 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Claudia",
"version": "0.1.0",
"identifier": "com.claudia.app",
"build": {
"frontendDist": "../src"
},
"app": {
"withGlobalTauri": true,
"windows": [
{
"title": "Claudia",
"width": 800,
"height": 600,
"minWidth": 400,
"minHeight": 500,
"resizable": true,
"fullscreen": false,
"decorations": true,
"transparent": false,
"alwaysOnTop": false,
"center": true
}
],
"security": {
"csp": null
}
},
"bundle": {
"active": true,
"targets": "all",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
]
}
}

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="32" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path fill="#F7DF1E" d="M0 0h256v256H0V0Z"></path><path d="m67.312 213.932l19.59-11.856c3.78 6.701 7.218 12.371 15.465 12.371c7.905 0 12.89-3.092 12.89-15.12v-81.798h24.057v82.138c0 24.917-14.606 36.259-35.916 36.259c-19.245 0-30.416-9.967-36.087-21.996m85.07-2.576l19.588-11.341c5.157 8.421 11.859 14.607 23.715 14.607c9.969 0 16.325-4.984 16.325-11.858c0-8.248-6.53-11.17-17.528-15.98l-6.013-2.58c-17.357-7.387-28.87-16.667-28.87-36.257c0-18.044 13.747-31.792 35.228-31.792c15.294 0 26.292 5.328 34.196 19.247l-18.732 12.03c-4.125-7.389-8.591-10.31-15.465-10.31c-7.046 0-11.514 4.468-11.514 10.31c0 7.217 4.468 10.14 14.778 14.608l6.014 2.577c20.45 8.765 31.963 17.7 31.963 37.804c0 21.654-17.012 33.51-39.867 33.51c-22.339 0-36.774-10.654-43.819-24.574"></path></svg>

After

Width:  |  Height:  |  Size: 995 B

6
src/assets/tauri.svg Normal file
View File

@@ -0,0 +1,6 @@
<svg width="206" height="231" viewBox="0 0 206 231" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M143.143 84C143.143 96.1503 133.293 106 121.143 106C108.992 106 99.1426 96.1503 99.1426 84C99.1426 71.8497 108.992 62 121.143 62C133.293 62 143.143 71.8497 143.143 84Z" fill="#FFC131"/>
<ellipse cx="84.1426" cy="147" rx="22" ry="22" transform="rotate(180 84.1426 147)" fill="#24C8DB"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M166.738 154.548C157.86 160.286 148.023 164.269 137.757 166.341C139.858 160.282 141 153.774 141 147C141 144.543 140.85 142.121 140.558 139.743C144.975 138.204 149.215 136.139 153.183 133.575C162.73 127.404 170.292 118.608 174.961 108.244C179.63 97.8797 181.207 86.3876 179.502 75.1487C177.798 63.9098 172.884 53.4021 165.352 44.8883C157.82 36.3744 147.99 30.2165 137.042 27.1546C126.095 24.0926 114.496 24.2568 103.64 27.6274C92.7839 30.998 83.1319 37.4317 75.8437 46.1553C74.9102 47.2727 74.0206 48.4216 73.176 49.5993C61.9292 50.8488 51.0363 54.0318 40.9629 58.9556C44.2417 48.4586 49.5653 38.6591 56.679 30.1442C67.0505 17.7298 80.7861 8.57426 96.2354 3.77762C111.685 -1.01901 128.19 -1.25267 143.769 3.10474C159.348 7.46215 173.337 16.2252 184.056 28.3411C194.775 40.457 201.767 55.4101 204.193 71.404C206.619 87.3978 204.374 103.752 197.73 118.501C191.086 133.25 180.324 145.767 166.738 154.548ZM41.9631 74.275L62.5557 76.8042C63.0459 72.813 63.9401 68.9018 65.2138 65.1274C57.0465 67.0016 49.2088 70.087 41.9631 74.275Z" fill="#FFC131"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M38.4045 76.4519C47.3493 70.6709 57.2677 66.6712 67.6171 64.6132C65.2774 70.9669 64 77.8343 64 85.0001C64 87.1434 64.1143 89.26 64.3371 91.3442C60.0093 92.8732 55.8533 94.9092 51.9599 97.4256C42.4128 103.596 34.8505 112.392 30.1816 122.756C25.5126 133.12 23.9357 144.612 25.6403 155.851C27.3449 167.09 32.2584 177.598 39.7906 186.112C47.3227 194.626 57.153 200.784 68.1003 203.846C79.0476 206.907 90.6462 206.743 101.502 203.373C112.359 200.002 122.011 193.568 129.299 184.845C130.237 183.722 131.131 182.567 131.979 181.383C143.235 180.114 154.132 176.91 164.205 171.962C160.929 182.49 155.596 192.319 148.464 200.856C138.092 213.27 124.357 222.426 108.907 227.222C93.458 232.019 76.9524 232.253 61.3736 227.895C45.7948 223.538 31.8055 214.775 21.0867 202.659C10.3679 190.543 3.37557 175.59 0.949823 159.596C-1.47592 143.602 0.768139 127.248 7.41237 112.499C14.0566 97.7497 24.8183 85.2327 38.4045 76.4519ZM163.062 156.711L163.062 156.711C162.954 156.773 162.846 156.835 162.738 156.897C162.846 156.835 162.954 156.773 163.062 156.711Z" fill="#24C8DB"/>
</svg>

After

Width:  |  Height:  |  Size: 2.5 KiB

190
src/index.html Normal file
View File

@@ -0,0 +1,190 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="stylesheet" href="styles.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github-dark.min.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Claudia</title>
<script src="https://cdn.jsdelivr.net/npm/marked@11.1.1/marked.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<script type="module" src="/main.js" defer></script>
</head>
<body>
<div class="app-container">
<header class="app-header">
<div class="header-content">
<div class="character-display">
<div class="avatar-circle"></div>
<span id="character-header-name"></span>
</div>
<div class="character-controls">
<div class="select-wrapper">
<select id="character-select" class="character-select"></select>
</div>
<button id="new-character-btn" class="icon-btn" title="New Character">
<svg width="16" height="16" viewBox="0 0 16 16" fill="none">
<path d="M8 3v10M3 8h10" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
</svg>
</button>
</div>
<div class="header-controls">
<button id="clear-btn" class="icon-btn" title="Clear conversation">
<svg width="16" height="16" viewBox="0 0 16 16" fill="none">
<path d="M3 4h10M6 4V3a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1v1M5 4v8a1 1 0 0 0 1 1h4a1 1 0 0 0 1-1V4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
</svg>
</button>
<button id="settings-btn" class="icon-btn" title="Settings">
<svg width="16" height="16" viewBox="0 0 16 16" fill="none">
<circle cx="8" cy="8" r="2" stroke="currentColor" stroke-width="1.5"/>
<path d="M14 8c0-.5-.1-1-.3-1.4l1.2-.7-1-1.7-1.2.7c-.6-.6-1.3-1-2.1-1.2V2h-2v1.7c-.8.2-1.5.6-2.1 1.2L5.3 4.2l-1 1.7 1.2.7C5.1 7 5 7.5 5 8s.1 1 .3 1.4l-1.2.7 1 1.7 1.2-.7c.6.6 1.3 1 2.1 1.2V14h2v-1.7c.8-.2 1.5-.6 2.1-1.2l1.2.7 1-1.7-1.2-.7c.2-.4.3-.9.3-1.4z" stroke="currentColor" stroke-width="1.5" fill="none"/>
</svg>
</button>
</div>
</div>
</header>
<main class="chat-container" id="chat-view">
<div id="messages" class="messages-list">
<div class="message assistant">
<div class="message-content">
<p>Configure API settings to get started.</p>
</div>
</div>
</div>
</main>
<div class="settings-panel" id="settings-panel" style="display: none;">
<div class="settings-header">
<h2>Settings</h2>
<button id="close-settings-btn" class="icon-btn">
<svg width="16" height="16" viewBox="0 0 16 16" fill="none">
<line x1="4" y1="4" x2="12" y2="12" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
<line x1="12" y1="4" x2="4" y2="12" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
</svg>
</button>
</div>
<div class="settings-tabs">
<button class="tab-btn active" data-tab="api">API</button>
<button class="tab-btn" data-tab="character">Character</button>
</div>
<div id="api-tab" class="tab-content active">
<form id="settings-form" class="settings-form">
<div class="form-group">
<label for="api-base-url">Base URL</label>
<input
type="text"
id="api-base-url"
placeholder="https://api.anthropic.com"
required
/>
</div>
<div class="form-group">
<label for="api-key">API Key</label>
<input
type="password"
id="api-key"
placeholder="sk-ant-..."
required
/>
</div>
<button type="button" id="validate-btn" class="btn-secondary">
Validate
</button>
<div id="models-group" class="form-group" style="display: none;">
<label for="model-select">Model</label>
<select id="model-select" required>
<option value="">Select a model</option>
</select>
</div>
<div id="validation-message" class="validation-message"></div>
<button type="submit" id="save-settings-btn" class="btn-primary" disabled>
Save Configuration
</button>
</form>
</div>
<div id="character-tab" class="tab-content">
<form id="character-form" class="settings-form">
<div class="form-group">
<label for="character-settings-select">Select Character</label>
<select id="character-settings-select"></select>
</div>
<div class="form-group">
<label for="character-name">Character Name</label>
<input
type="text"
id="character-name"
placeholder="Assistant"
required
/>
</div>
<div class="form-group">
<label for="character-system-prompt">System Prompt</label>
<textarea
id="character-system-prompt"
placeholder="You are a helpful AI assistant..."
rows="6"
required
></textarea>
</div>
<div class="form-group">
<label for="character-greeting">Greeting (Optional)</label>
<textarea
id="character-greeting"
placeholder="Hello! How can I help you today?"
rows="2"
></textarea>
</div>
<div class="form-group">
<label for="character-personality">Personality Tags (Optional)</label>
<input
type="text"
id="character-personality"
placeholder="helpful, friendly, knowledgeable"
/>
</div>
<div id="character-message" class="validation-message"></div>
<button type="submit" id="save-character-btn" class="btn-primary">
Save Character
</button>
<button type="button" id="delete-character-btn" class="btn-danger">
Delete Character
</button> </form>
</div>
</div>
<footer class="input-container">
<form id="chat-form" class="chat-form">
<textarea
id="message-input"
placeholder="Ask me anything..."
rows="1"
autocomplete="off"
></textarea>
<button type="submit" id="send-btn" class="send-btn">
<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
<path d="M3 10L17 3L13 10L17 17L3 10Z" fill="currentColor"/>
</svg>
</button>
</form>
<div class="status-bar">
<span id="status-text" class="status-text">Ready</span>
</div>
</footer>
</div>
</body>
</html>

545
src/main.js Normal file
View File

@@ -0,0 +1,545 @@
const { invoke } = window.__TAURI__.core;
let messageInput;
let messagesContainer;
let chatForm;
let sendBtn;
let statusText;
let settingsPanel;
let chatView;
let characterSelect;
let characterHeaderName;
let newCharacterBtn;
let currentCharacter = null;
// Auto-resize textarea
function autoResize(textarea) {
textarea.style.height = 'auto';
textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px';
}
// Add message to chat
function addMessage(content, isUser = false) {
const messageDiv = document.createElement('div');
messageDiv.className = `message ${isUser ? 'user' : 'assistant'}`;
const avatar = document.createElement('div');
avatar.className = 'avatar-circle';
// TODO: Set avatar image
const contentDiv = document.createElement('div');
contentDiv.className = 'message-content';
if (isUser) {
// User messages: plain text
const p = document.createElement('p');
p.textContent = content;
contentDiv.appendChild(p);
} else {
// Assistant messages: render as markdown
contentDiv.innerHTML = marked.parse(content);
// Apply syntax highlighting to code blocks
contentDiv.querySelectorAll('pre code').forEach((block) => {
hljs.highlightElement(block);
// Add copy button to code blocks
const pre = block.parentElement;
if (!pre.querySelector('.copy-btn')) {
const copyBtn = document.createElement('button');
copyBtn.className = 'copy-btn';
copyBtn.innerHTML = `<svg width="16" height="16" viewBox="0 0 16 16" fill="none">
<rect x="5" y="5" width="9" height="9" stroke="currentColor" stroke-width="1.5" fill="none" rx="1"/>
<path d="M3 11V3a1 1 0 0 1 1-1h8" stroke="currentColor" stroke-width="1.5" fill="none"/>
</svg>`;
copyBtn.title = 'Copy code';
copyBtn.addEventListener('click', () => {
navigator.clipboard.writeText(block.textContent);
copyBtn.innerHTML = `<svg width="16" height="16" viewBox="0 0 16 16" fill="none">
<path d="M3 8l3 3 7-7" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>`;
copyBtn.classList.add('copied');
setTimeout(() => {
copyBtn.innerHTML = `<svg width="16" height="16" viewBox="0 0 16 16" fill="none">
<rect x="5" y="5" width="9" height="9" stroke="currentColor" stroke-width="1.5" fill="none" rx="1"/>
<path d="M3 11V3a1 1 0 0 1 1-1h8" stroke="currentColor" stroke-width="1.5" fill="none"/>
</svg>`;
copyBtn.classList.remove('copied');
}, 2000);
});
pre.style.position = 'relative';
pre.appendChild(copyBtn);
}
});
}
if (!isUser) {
messageDiv.appendChild(avatar);
}
messageDiv.appendChild(contentDiv);
messagesContainer.appendChild(messageDiv);
messagesContainer.scrollTop = messagesContainer.scrollHeight;
}
// Show typing indicator
function showTypingIndicator() {
const typingDiv = document.createElement('div');
typingDiv.className = 'message assistant';
typingDiv.id = 'typing-indicator';
const indicatorDiv = document.createElement('div');
indicatorDiv.className = 'typing-indicator';
for (let i = 0; i < 3; i++) {
const dot = document.createElement('div');
dot.className = 'typing-dot';
indicatorDiv.appendChild(dot);
}
typingDiv.appendChild(indicatorDiv);
messagesContainer.appendChild(typingDiv);
messagesContainer.scrollTop = messagesContainer.scrollHeight;
}
// Remove typing indicator
function removeTypingIndicator() {
const indicator = document.getElementById('typing-indicator');
if (indicator) {
indicator.remove();
}
}
// Update status
function setStatus(text) {
statusText.textContent = text;
}
// Show/hide settings
async function showSettings() {
settingsPanel.style.display = 'block';
chatView.style.display = 'none';
await loadCharacterSettings();
}
function hideSettings() {
settingsPanel.style.display = 'none';
chatView.style.display = 'flex';
}
// Tab switching
function setupTabs() {
const tabBtns = document.querySelectorAll('.tab-btn');
const tabContents = document.querySelectorAll('.tab-content');
tabBtns.forEach(btn => {
btn.addEventListener('click', () => {
const targetTab = btn.getAttribute('data-tab');
// Remove active class from all tabs and contents
tabBtns.forEach(b => b.classList.remove('active'));
tabContents.forEach(c => c.classList.remove('active'));
// Add active class to clicked tab and corresponding content
btn.classList.add('active');
document.getElementById(`${targetTab}-tab`).classList.add('active');
});
});
}
// Handle form submission
async function handleSubmit(e) {
e.preventDefault();
const message = messageInput.value.trim();
if (!message) return;
addMessage(message, true);
messageInput.value = '';
autoResize(messageInput);
sendBtn.disabled = true;
messageInput.disabled = true;
setStatus('Thinking...');
showTypingIndicator();
try {
const response = await invoke('chat', { message });
removeTypingIndicator();
addMessage(response, false);
setStatus('Ready');
} catch (error) {
removeTypingIndicator();
if (error.includes('not configured')) {
addMessage('API not configured. Please configure your API settings.', false);
setTimeout(showSettings, 1000);
} else {
addMessage(`Error: ${error}`, false);
}
setStatus('Error');
} finally {
sendBtn.disabled = false;
messageInput.disabled = false;
messageInput.focus();
}
}
// Settings functionality
async function handleValidate() {
const baseUrl = document.getElementById('api-base-url').value.trim();
const apiKey = document.getElementById('api-key').value.trim();
const validateBtn = document.getElementById('validate-btn');
const modelsGroup = document.getElementById('models-group');
const modelSelect = document.getElementById('model-select');
const saveBtn = document.getElementById('save-settings-btn');
const validationMsg = document.getElementById('validation-message');
if (!baseUrl || !apiKey) {
validationMsg.textContent = 'Please fill in all fields';
validationMsg.className = 'validation-message error';
return;
}
validateBtn.disabled = true;
validateBtn.textContent = 'Validating...';
validationMsg.style.display = 'none';
try {
const models = await invoke('validate_api', { baseUrl, apiKey });
validationMsg.textContent = `Found ${models.length} models`;
validationMsg.className = 'validation-message success';
modelSelect.innerHTML = '<option value="">Select a model</option>';
models.forEach(model => {
const option = document.createElement('option');
option.value = model;
option.textContent = model;
modelSelect.appendChild(option);
});
modelsGroup.style.display = 'flex';
saveBtn.disabled = false;
} catch (error) {
validationMsg.textContent = `Validation failed: ${error}`;
validationMsg.className = 'validation-message error';
modelsGroup.style.display = 'none';
saveBtn.disabled = true;
} finally {
validateBtn.disabled = false;
validateBtn.textContent = 'Validate';
}
}
async function handleSaveSettings(e) {
e.preventDefault();
const baseUrl = document.getElementById('api-base-url').value.trim();
const apiKey = document.getElementById('api-key').value.trim();
const model = document.getElementById('model-select').value;
const saveBtn = document.getElementById('save-settings-btn');
const validationMsg = document.getElementById('validation-message');
if (!model) {
validationMsg.textContent = 'Please select a model';
validationMsg.className = 'validation-message error';
return;
}
saveBtn.disabled = true;
saveBtn.textContent = 'Saving...';
try {
await invoke('save_api_config', { baseUrl, apiKey, model });
validationMsg.textContent = 'Configuration saved successfully';
validationMsg.className = 'validation-message success';
setTimeout(() => {
hideSettings();
messagesContainer.innerHTML = '';
addMessage('API configured. Ready to chat.', false);
}, 1000);
} catch (error) {
validationMsg.textContent = `Failed to save: ${error}`;
validationMsg.className = 'validation-message error';
} finally {
saveBtn.disabled = false;
saveBtn.textContent = 'Save Configuration';
}
}
// App controls
function setupAppControls() {
document.getElementById('settings-btn').addEventListener('click', showSettings);
document.getElementById('close-settings-btn').addEventListener('click', hideSettings);
document.getElementById('clear-btn').addEventListener('click', clearHistory);
characterSelect.addEventListener('change', handleCharacterSwitch);
newCharacterBtn.addEventListener('click', handleNewCharacter);
document.getElementById('delete-character-btn').addEventListener('click', handleDeleteCharacter);
document.getElementById('character-settings-select').addEventListener('change', async () => {
const characterId = document.getElementById('character-settings-select').value;
await invoke('set_active_character', { characterId });
await loadCharacterSettings();
});
}
// Keyboard shortcuts
function setupKeyboardShortcuts() {
messageInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSubmit(e);
}
});
messageInput.addEventListener('input', () => {
autoResize(messageInput);
});
}
// Load characters and populate dropdown
async function loadCharacters() {
console.log('Loading characters...');
try {
const characters = await invoke('list_characters');
console.log('Loaded characters:', characters);
characterSelect.innerHTML = '';
characters.forEach(char => {
const option = document.createElement('option');
option.value = char.id;
option.textContent = char.name;
characterSelect.appendChild(option);
});
const activeCharacter = await invoke('get_character');
console.log('Active character:', activeCharacter);
characterSelect.value = activeCharacter.id;
characterHeaderName.textContent = activeCharacter.name;
currentCharacter = activeCharacter;
await loadChatHistory();
} catch (error) {
console.error('Failed to load characters:', error);
addMessage(`Failed to load characters: ${error}`, false);
}
}
// Handle character switching
async function handleCharacterSwitch() {
const characterId = characterSelect.value;
try {
await invoke('set_active_character', { characterId });
messagesContainer.innerHTML = '';
await loadCharacters();
} catch (error) {
console.error('Failed to switch character:', error);
addMessage(`Failed to switch character: ${error}`, false);
}
}
// Handle new character creation
async function handleNewCharacter() {
const name = prompt('Enter a name for the new character:');
if (!name) return;
const systemPrompt = prompt('Enter the system prompt for the new character:', 'You are a helpful AI assistant.');
if (!systemPrompt) return;
try {
const newCharacter = await invoke('create_character', { name, systemPrompt });
await loadCharacters();
characterSelect.value = newCharacter.id;
} catch (error) {
console.error('Failed to create character:', error);
addMessage(`Failed to create character: ${error}`, false);
}
}
// Handle character deletion
async function handleDeleteCharacter() {
if (!currentCharacter || currentCharacter.id === 'default') {
addMessage('Cannot delete the default character.', false);
return;
}
if (confirm(`Are you sure you want to delete ${currentCharacter.name}? This cannot be undone.`)) {
try {
await invoke('delete_character', { characterId: currentCharacter.id });
await loadCharacters();
hideSettings();
} catch (error) {
console.error('Failed to delete character:', error);
addMessage(`Failed to delete character: ${error}`, false);
}
}
}
// Load chat history
async function loadChatHistory() {
try {
const history = await invoke('get_chat_history');
messagesContainer.innerHTML = '';
if (history.length === 0) {
if (currentCharacter && currentCharacter.greeting) {
addMessage(currentCharacter.greeting, false);
} else {
addMessage('API configured. Ready to chat.', false);
}
} else {
history.forEach(msg => {
addMessage(msg.content, msg.role === 'user');
});
}
} catch (error) {
console.error('Failed to load chat history:', error);
messagesContainer.innerHTML = '';
addMessage('API configured. Ready to chat.', false);
}
}
// Clear chat history
async function clearHistory() {
if (!confirm('Clear conversation history? This cannot be undone.')) {
return;
}
try {
await invoke('clear_chat_history');
messagesContainer.innerHTML = '';
if (currentCharacter && currentCharacter.greeting) {
addMessage(currentCharacter.greeting, false);
} else {
addMessage('Conversation cleared. Ready to chat.', false);
}
} catch (error) {
addMessage(`Failed to clear history: ${error}`, false);
}
}
// Load character settings
async function loadCharacterSettings() {
try {
const characters = await invoke('list_characters');
const characterSettingsSelect = document.getElementById('character-settings-select');
characterSettingsSelect.innerHTML = '';
characters.forEach(char => {
const option = document.createElement('option');
option.value = char.id;
option.textContent = char.name;
characterSettingsSelect.appendChild(option);
});
const character = await invoke('get_character');
characterSettingsSelect.value = character.id;
document.getElementById('character-name').value = character.name;
document.getElementById('character-system-prompt').value = character.system_prompt;
document.getElementById('character-greeting').value = character.greeting || '';
document.getElementById('character-personality').value = character.personality || '';
} catch (error) {
console.error('Failed to load character:', error);
}
}
// Save character settings
async function handleSaveCharacter(e) {
e.preventDefault();
const name = document.getElementById('character-name').value.trim();
const systemPrompt = document.getElementById('character-system-prompt').value.trim();
const greeting = document.getElementById('character-greeting').value.trim() || null;
const personality = document.getElementById('character-personality').value.trim() || null;
const saveBtn = document.getElementById('save-character-btn');
const characterMsg = document.getElementById('character-message');
if (!name || !systemPrompt) {
characterMsg.textContent = 'Name and System Prompt are required';
characterMsg.className = 'validation-message error';
return;
}
saveBtn.disabled = true;
saveBtn.textContent = 'Saving...';
try {
await invoke('update_character', {
name,
system_prompt: systemPrompt,
greeting,
personality
});
characterMsg.textContent = 'Character saved successfully';
characterMsg.className = 'validation-message success';
await loadCharacters();
setTimeout(() => {
characterMsg.style.display = 'none';
}, 3000);
} catch (error) {
characterMsg.textContent = `Failed to save: ${error}`;
characterMsg.className = 'validation-message error';
} finally {
saveBtn.disabled = false;
saveBtn.textContent = 'Save Character';
}
}
// Load existing config if available
async function loadExistingConfig() {
console.log('Loading existing config...');
try {
const config = await invoke('get_api_config');
console.log('Loaded config:', config);
document.getElementById('api-base-url').value = config.base_url;
document.getElementById('api-key').value = config.api_key;
const modelSelect = document.getElementById('model-select');
modelSelect.innerHTML = ''; // Clear existing options
const option = document.createElement('option');
option.value = config.model;
option.textContent = config.model;
option.selected = true;
modelSelect.appendChild(option);
// Show the model group since we have a saved model
document.getElementById('models-group').style.display = 'flex';
document.getElementById('save-settings-btn').disabled = false;
// Load characters
await loadCharacters();
} catch (error) {
console.error('Failed to load existing config:', error);
addMessage('API not configured. Please configure your API settings.', false);
showSettings();
}
}
// Initialize app
window.addEventListener('DOMContentLoaded', () => {
messageInput = document.getElementById('message-input');
messagesContainer = document.getElementById('messages');
chatForm = document.getElementById('chat-form');
sendBtn = document.getElementById('send-btn');
statusText = document.getElementById('status-text');
settingsPanel = document.getElementById('settings-panel');
chatView = document.getElementById('chat-view');
characterSelect = document.getElementById('character-select');
characterHeaderName = document.getElementById('character-header-name');
newCharacterBtn = document.getElementById('new-character-btn');
chatForm.addEventListener('submit', handleSubmit);
document.getElementById('settings-form').addEventListener('submit', handleSaveSettings);
document.getElementById('character-form').addEventListener('submit', handleSaveCharacter);
document.getElementById('validate-btn').addEventListener('click', handleValidate);
setupAppControls();
setupKeyboardShortcuts();
setupTabs();
messageInput.focus();
setStatus('Ready');
loadExistingConfig();
});

736
src/styles.css Normal file
View File

@@ -0,0 +1,736 @@
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
:root {
--bg-primary: #1a1a1a;
--bg-secondary: #252525;
--bg-tertiary: #2f2f2f;
--text-primary: #e8e8e8;
--text-secondary: #a0a0a0;
--accent: #6366f1;
--accent-hover: #4f46e5;
--user-msg: #4f46e5;
--assistant-msg: #2f2f2f;
--border: #3a3a3a;
--shadow: rgba(0, 0, 0, 0.5);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
font-size: 14px;
line-height: 1.6;
font-weight: 400;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
body {
background: var(--bg-primary);
color: var(--text-primary);
overflow: hidden;
height: 100vh;
}
.app-container {
display: flex;
flex-direction: column;
height: 100vh;
background: linear-gradient(135deg, #1a1a1a 0%, #2a1a2a 100%);
position: relative;
}
.app-container::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
height: 300px;
background: radial-gradient(circle at top center, rgba(99, 102, 241, 0.1) 0%, transparent 70%);
pointer-events: none;
}
/* Header */
.app-header {
background: rgba(37, 37, 37, 0.8);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
border-bottom: 1px solid rgba(58, 58, 58, 0.5);
padding: 12px 16px;
user-select: none;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.header-content {
display: flex;
justify-content: space-between;
align-items: center;
}
.character-display {
display: flex;
align-items: center;
gap: 8px;
}
.avatar-circle {
width: 28px;
height: 28px;
border-radius: 50%;
background: var(--bg-tertiary);
border: 1px solid var(--border);
}
#character-header-name {
font-weight: 500;
color: var(--text-primary);
}
.character-controls {
display: flex;
align-items: center;
gap: 8px;
}
.character-select {
background: var(--bg-tertiary);
border: 1px solid var(--border);
border-radius: 6px;
color: var(--text-primary);
padding: 6px 10px;
font-family: inherit;
font-size: 13px;
transition: border-color 0.2s ease;
}
.character-select:hover {
border-color: var(--accent);
}
.select-wrapper {
position: relative;
display: inline-block;
}
.select-wrapper::after {
content: "▼";
position: absolute;
top: 50%;
right: 10px;
transform: translateY(-50%);
font-size: 12px;
color: var(--text-secondary);
pointer-events: none;
}
.character-select {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background: transparent;
padding-right: 30px;
}
.btn-danger {
background-color: #ef4444;
color: white;
}
.btn-danger:hover {
background-color: #dc2626;
}
.header-controls {
display: flex;
gap: 8px;
}
.icon-btn {
width: 28px;
height: 28px;
border: none;
background: transparent;
color: var(--text-secondary);
border-radius: 6px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s ease;
}
.icon-btn:hover {
background: var(--bg-tertiary);
color: var(--text-primary);
}
.icon-btn.close:hover {
background: #ef4444;
color: white;
}
/* Chat Container */
.chat-container {
flex: 1;
overflow: hidden;
background: var(--bg-primary);
}
.messages-list {
height: 100%;
overflow-y: auto;
padding: 20px;
display: flex;
flex-direction: column;
gap: 16px;
}
.messages-list::-webkit-scrollbar {
width: 8px;
}
.messages-list::-webkit-scrollbar-track {
background: var(--bg-primary);
}
.messages-list::-webkit-scrollbar-thumb {
background: var(--bg-tertiary);
border-radius: 4px;
}
.messages-list::-webkit-scrollbar-thumb:hover {
background: var(--border);
}
.message {
display: flex;
animation: slideIn 0.3s ease;
}
@keyframes slideIn {
from {
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.message.user {
justify-content: flex-end;
}
.message.assistant {
justify-content: flex-start;
gap: 10px;
}
.message-content {
max-width: 80%;
padding: 12px 16px;
border-radius: 12px;
line-height: 1.6;
}
.message.user .message-content {
background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%);
color: white;
border-bottom-right-radius: 4px;
box-shadow: 0 2px 8px rgba(99, 102, 241, 0.3);
}
.message.assistant .message-content {
background: rgba(47, 47, 47, 0.6);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
color: var(--text-primary);
border-bottom-left-radius: 4px;
border: 1px solid rgba(58, 58, 58, 0.5);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}
.message-content p {
margin: 0;
word-wrap: break-word;
}
.message-content p + p {
margin-top: 12px;
}
.message-content code {
background: rgba(0, 0, 0, 0.3);
padding: 2px 6px;
border-radius: 4px;
font-family: 'Monaco', 'Courier New', monospace;
font-size: 0.9em;
}
.message-content pre {
background: rgba(0, 0, 0, 0.3);
padding: 12px;
border-radius: 6px;
overflow-x: auto;
margin: 8px 0;
}
.message-content pre code {
background: none;
padding: 0;
}
/* Copy button for code blocks */
.copy-btn {
position: absolute;
top: 8px;
right: 8px;
background: var(--bg-tertiary);
border: 1px solid var(--border);
border-radius: 6px;
padding: 6px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
color: var(--text-secondary);
opacity: 0;
transition: all 0.2s ease;
}
.message-content pre:hover .copy-btn {
opacity: 1;
}
.copy-btn:hover {
background: var(--border);
color: var(--text-primary);
}
.copy-btn.copied {
color: #22c55e;
border-color: #22c55e;
}
/* Enhanced markdown styles */
.message-content h1,
.message-content h2,
.message-content h3 {
margin-top: 16px;
margin-bottom: 8px;
font-weight: 600;
}
.message-content h1 {
font-size: 1.5em;
}
.message-content h2 {
font-size: 1.3em;
}
.message-content h3 {
font-size: 1.1em;
}
.message-content ul,
.message-content ol {
margin: 8px 0;
padding-left: 24px;
}
.message-content li {
margin: 4px 0;
}
.message-content a {
color: var(--accent);
text-decoration: none;
border-bottom: 1px solid transparent;
transition: border-color 0.2s;
}
.message-content a:hover {
border-bottom-color: var(--accent);
}
.message-content blockquote {
border-left: 3px solid var(--accent);
padding-left: 12px;
margin: 8px 0;
color: var(--text-secondary);
font-style: italic;
}
.message-content hr {
border: none;
border-top: 1px solid var(--border);
margin: 16px 0;
}
.message-content table {
border-collapse: collapse;
width: 100%;
margin: 12px 0;
}
.message-content th,
.message-content td {
border: 1px solid var(--border);
padding: 8px;
text-align: left;
}
.message-content th {
background: var(--bg-tertiary);
font-weight: 600;
}
/* Typing indicator */
.typing-indicator {
display: flex;
gap: 4px;
padding: 12px 16px;
}
.typing-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--text-secondary);
animation: typing 1.4s infinite;
}
.typing-dot:nth-child(2) {
animation-delay: 0.2s;
}
.typing-dot:nth-child(3) {
animation-delay: 0.4s;
}
@keyframes typing {
0%, 60%, 100% {
opacity: 0.3;
transform: translateY(0);
}
30% {
opacity: 1;
transform: translateY(-8px);
}
}
/* Input Container */
.input-container {
background: rgba(37, 37, 37, 0.8);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
border-top: 1px solid rgba(58, 58, 58, 0.5);
padding: 16px;
box-shadow: 0 -4px 6px rgba(0, 0, 0, 0.1);
}
.chat-form {
display: flex;
gap: 12px;
align-items: flex-end;
margin-bottom: 8px;
}
#message-input {
flex: 1;
background: var(--bg-tertiary);
border: 1px solid var(--border);
border-radius: 12px;
padding: 12px 16px;
color: var(--text-primary);
font-size: 14px;
font-family: inherit;
resize: none;
max-height: 120px;
transition: border-color 0.2s ease;
}
#message-input:focus {
outline: none;
border-color: var(--accent);
}
#message-input::placeholder {
color: var(--text-secondary);
}
.send-btn {
width: 44px;
height: 44px;
background: var(--accent);
border: none;
border-radius: 12px;
color: white;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s ease;
flex-shrink: 0;
}
.send-btn:hover {
background: var(--accent-hover);
transform: scale(1.05);
}
.send-btn:active {
transform: scale(0.95);
}
.send-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
transform: none;
}
.status-bar {
display: flex;
justify-content: space-between;
align-items: center;
}
.status-text {
font-size: 12px;
color: var(--text-secondary);
}
/* Light mode support */
@media (prefers-color-scheme: light) {
:root {
--bg-primary: #ffffff;
--bg-secondary: #f5f5f5;
--bg-tertiary: #e8e8e8;
--text-primary: #1a1a1a;
--text-secondary: #666666;
--accent: #6366f1;
--accent-hover: #4f46e5;
--user-msg: #6366f1;
--assistant-msg: #f5f5f5;
--border: #e0e0e0;
--shadow: rgba(0, 0, 0, 0.1);
}
.message.assistant .message-content {
border: 1px solid var(--border);
}
}
/* Settings Panel */
.settings-panel {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: var(--bg-primary);
z-index: 1000;
overflow-y: auto;
padding: 60px 20px 20px;
}
.settings-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
}
.settings-header h2 {
font-size: 20px;
font-weight: 600;
color: var(--text-primary);
margin: 0;
}
.settings-tabs {
display: flex;
gap: 8px;
margin-bottom: 24px;
max-width: 400px;
margin-left: auto;
margin-right: auto;
}
.tab-btn {
flex: 1;
padding: 10px 16px;
background: var(--bg-tertiary);
border: 1px solid var(--border);
border-radius: 8px;
color: var(--text-secondary);
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: all 0.2s ease;
font-family: inherit;
}
.tab-btn:hover {
background: var(--border);
color: var(--text-primary);
}
.tab-btn.active {
background: var(--accent);
color: white;
border-color: var(--accent);
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
.settings-form {
max-width: 400px;
margin: 0 auto;
display: flex;
flex-direction: column;
gap: 20px;
}
.form-group {
display: flex;
flex-direction: column;
gap: 8px;
}
.form-group label {
font-size: 13px;
font-weight: 500;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.5px;
}
.form-group input,
.form-group select,
.form-group textarea {
background: var(--bg-tertiary);
border: 1px solid var(--border);
border-radius: 8px;
padding: 12px;
color: var(--text-primary);
font-size: 14px;
font-family: inherit;
transition: border-color 0.2s ease;
}
.form-group textarea {
resize: vertical;
min-height: 80px;
}
.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
outline: none;
border-color: var(--accent);
}
.form-group select {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background: var(--bg-tertiary) url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236B7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e") no-repeat right 0.75rem center/1.5em 1.5em;
}
.btn-danger {
background-color: #ef4444;
color: white;
}
.btn-danger:hover {
background-color: #dc2626;
}
.btn-primary,
.btn-secondary {
padding: 12px 24px;
border: none;
border-radius: 8px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: all 0.2s ease;
font-family: inherit;
}
.btn-primary {
background: var(--accent);
color: white;
}
.btn-primary:hover:not(:disabled) {
background: var(--accent-hover);
}
.btn-primary:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.btn-secondary {
background: var(--bg-tertiary);
color: var(--text-primary);
border: 1px solid var(--border);
}
.btn-secondary:hover {
background: var(--border);
}
.validation-message {
padding: 12px;
border-radius: 8px;
font-size: 13px;
display: none;
}
.validation-message.success {
display: block;
background: rgba(34, 197, 94, 0.1);
color: #22c55e;
border: 1px solid rgba(34, 197, 94, 0.2);
}
.validation-message.error {
display: block;
background: rgba(239, 68, 68, 0.1);
color: #ef4444;
border: 1px solid rgba(239, 68, 68, 0.2);
}
/* Responsive */
@media (max-width: 600px) {
.messages-list {
padding: 12px;
}
.message-content {
max-width: 90%;
}
.input-container {
padding: 12px;
}
.settings-panel {
padding: 60px 16px 16px;
}
}