Working electron code
This commit is contained in:
parent
584ebc2129
commit
eea1f255cd
21
.gitignore
vendored
Normal file
21
.gitignore
vendored
Normal file
|
@ -0,0 +1,21 @@
|
|||
node_modules
|
||||
|
||||
# Output
|
||||
.output
|
||||
.vercel
|
||||
/.svelte-kit
|
||||
/build
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Env
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
!.env.test
|
||||
|
||||
# Vite
|
||||
vite.config.js.timestamp-*
|
||||
vite.config.ts.timestamp-*
|
4
.prettierignore
Normal file
4
.prettierignore
Normal file
|
@ -0,0 +1,4 @@
|
|||
# Package Managers
|
||||
package-lock.json
|
||||
pnpm-lock.yaml
|
||||
yarn.lock
|
8
.prettierrc
Normal file
8
.prettierrc
Normal file
|
@ -0,0 +1,8 @@
|
|||
{
|
||||
"useTabs": true,
|
||||
"singleQuote": true,
|
||||
"trailingComma": "none",
|
||||
"printWidth": 100,
|
||||
"plugins": ["prettier-plugin-svelte"],
|
||||
"overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }]
|
||||
}
|
38
README.md
38
README.md
|
@ -1,2 +1,38 @@
|
|||
# ai-desktop-demo
|
||||
# create-svelte
|
||||
|
||||
Everything you need to build a Svelte project, powered by [`create-svelte`](https://github.com/sveltejs/kit/tree/main/packages/create-svelte).
|
||||
|
||||
## Creating a project
|
||||
|
||||
If you're seeing this, you've probably already done this step. Congrats!
|
||||
|
||||
```bash
|
||||
# create a new project in the current directory
|
||||
npm create svelte@latest
|
||||
|
||||
# create a new project in my-app
|
||||
npm create svelte@latest my-app
|
||||
```
|
||||
|
||||
## Developing
|
||||
|
||||
Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
|
||||
# or start the server and open the app in a new browser tab
|
||||
npm run dev -- --open
|
||||
```
|
||||
|
||||
## Building
|
||||
|
||||
To create a production version of your app:
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
|
||||
You can preview the production build with `npm run preview`.
|
||||
|
||||
> To deploy your app, you may need to install an [adapter](https://kit.svelte.dev/docs/adapters) for your target environment.
|
||||
|
|
300
electron.cjs
Normal file
300
electron.cjs
Normal file
|
@ -0,0 +1,300 @@
|
|||
const { app, BrowserWindow, ipcMain, protocol, dialog } = require('electron');
|
||||
const { BedrockRuntimeClient, InvokeModelCommand, InvokeModelWithResponseStreamCommand } = require("@aws-sdk/client-bedrock-runtime");
|
||||
const { fromIni } = require("@aws-sdk/credential-provider-ini");
|
||||
const fs = require('fs').promises;
|
||||
const path = require('path');
|
||||
const url = require('url');
|
||||
const axios = require('axios');
|
||||
const cheerio = require('cheerio');
|
||||
|
||||
let bedrockClient;
|
||||
|
||||
async function initializeBedrockClient() {
|
||||
bedrockClient = new BedrockRuntimeClient({
|
||||
region: "us-east-1",
|
||||
credentials: fromIni({ profile: 'default' })
|
||||
});
|
||||
}
|
||||
|
||||
function createWindow() {
|
||||
const win = new BrowserWindow({
|
||||
width: 800,
|
||||
height: 600,
|
||||
webPreferences: {
|
||||
nodeIntegration: true,
|
||||
contextIsolation: false,
|
||||
},
|
||||
});
|
||||
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
win.loadURL('http://localhost:5173');
|
||||
} else {
|
||||
win.loadFile(path.join(__dirname, 'build', 'index.html'));
|
||||
}
|
||||
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
win.webContents.openDevTools();
|
||||
}
|
||||
}
|
||||
|
||||
app.whenReady().then(async () => {
|
||||
await initializeBedrockClient();
|
||||
|
||||
// Register protocol
|
||||
protocol.registerFileProtocol('safe-file', (request, callback) => {
|
||||
const filePath = url.fileURLToPath('file://' + request.url.slice('safe-file://'.length));
|
||||
callback(filePath);
|
||||
});
|
||||
|
||||
|
||||
createWindow();
|
||||
});
|
||||
|
||||
ipcMain.handle('fetch-url-content', async (event, url) => {
|
||||
try {
|
||||
const response = await axios.get(url);
|
||||
const $ = cheerio.load(response.data);
|
||||
|
||||
// Extract text content from the page
|
||||
const content = $('body').text().trim();
|
||||
|
||||
// Limit content to a reasonable length (e.g., 1000 characters)
|
||||
const limitedContent = content.substring(0, 1000);
|
||||
|
||||
event.sender.send('url-content-fetched', limitedContent);
|
||||
} catch (error) {
|
||||
console.error('Error fetching URL:', error);
|
||||
event.sender.send('url-fetch-error', error.message);
|
||||
}
|
||||
});
|
||||
|
||||
async function readDirectory(dirPath) {
|
||||
const fileTree = [];
|
||||
const files = await fs.readdir(dirPath, { withFileTypes: true });
|
||||
|
||||
for (const file of files) {
|
||||
const filePath = path.join(dirPath, file.name);
|
||||
if (file.isDirectory()) {
|
||||
const subDir = await readDirectory(filePath);
|
||||
fileTree.push({ name: file.name, type: 'directory', children: subDir });
|
||||
} else {
|
||||
let content = '';
|
||||
if (file.name.match(/\.(txt|md|js|py|html|css|json)$/i)) {
|
||||
content = await fs.readFile(filePath, 'utf-8');
|
||||
}
|
||||
fileTree.push({ name: file.name, type: 'file', content });
|
||||
}
|
||||
}
|
||||
|
||||
return fileTree;
|
||||
}
|
||||
|
||||
function formatFileTree(fileTree, indent = '') {
|
||||
let result = '';
|
||||
for (const item of fileTree) {
|
||||
result += `${indent}${item.type === 'directory' ? '📁' : '📄'} ${item.name}\n`;
|
||||
if (item.type === 'directory' && item.children) {
|
||||
result += formatFileTree(item.children, indent + ' ');
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
ipcMain.handle('select-directory', async (event) => {
|
||||
const result = await dialog.showOpenDialog({ properties: ['openDirectory'] });
|
||||
if (result.canceled) {
|
||||
return null;
|
||||
}
|
||||
const dirPath = result.filePaths[0];
|
||||
const fileTree = await readDirectory(dirPath);
|
||||
const formattedTree = formatFileTree(fileTree);
|
||||
const fileContents = JSON.stringify(fileTree, null, 2);
|
||||
return { tree: formattedTree, contents: fileContents };
|
||||
});
|
||||
|
||||
|
||||
ipcMain.handle('generate-response-stream', async (event, { prompt, imagePath, model, temperature, maxTokens, context, fileTree, fileContents }) => {
|
||||
if (!bedrockClient) {
|
||||
throw new Error('Bedrock client not initialized');
|
||||
}
|
||||
|
||||
console.log("DEBUG: Generating response for prompt:", prompt);
|
||||
|
||||
try {
|
||||
const requestBody = {
|
||||
anthropic_version: "bedrock-2023-05-31",
|
||||
max_tokens: maxTokens,
|
||||
temperature: temperature,
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: [
|
||||
{ type: "text", text: `Context: ${context || ''}\n\nFile Tree:\n${fileTree || ''}\n\nFile Contents:\n${fileContents || ''}\n\nUser: ${prompt}` }
|
||||
]
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
if (imagePath) {
|
||||
const imageBuffer = await fs.readFile(imagePath);
|
||||
const base64Image = imageBuffer.toString('base64');
|
||||
|
||||
requestBody.messages[0].content.unshift({
|
||||
type: "image",
|
||||
source: {
|
||||
type: "base64",
|
||||
media_type: "image/jpeg",
|
||||
data: base64Image
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const params = {
|
||||
modelId: "anthropic.claude-3-sonnet-20240229-v1:0", // or your preferred Claude 3 model
|
||||
contentType: "application/json",
|
||||
accept: "application/json",
|
||||
body: JSON.stringify(requestBody),
|
||||
};
|
||||
|
||||
const command = new InvokeModelWithResponseStreamCommand(params);
|
||||
const response = await bedrockClient.send(command);
|
||||
|
||||
for await (const chunk of response.body) {
|
||||
if (chunk.chunk && chunk.chunk.bytes) {
|
||||
const decodedChunk = JSON.parse(new TextDecoder().decode(chunk.chunk.bytes));
|
||||
if (decodedChunk.type === 'content_block_delta' && decodedChunk.delta && decodedChunk.delta.text) {
|
||||
event.sender.send('response-chunk', decodedChunk.delta.text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
event.sender.send('response-end');
|
||||
} catch (error) {
|
||||
console.error("ERROR: Failed to generate text with Bedrock:", error);
|
||||
event.sender.send('response-error', error.message);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
ipcMain.handle('generate-response', async (event, { prompt, imagePath }) => {
|
||||
if (!bedrockClient) {
|
||||
throw new Error('Bedrock client not initialized');
|
||||
}
|
||||
|
||||
console.log("DEBUG: Generating response for prompt:", prompt);
|
||||
|
||||
try {
|
||||
const requestBody = {
|
||||
anthropic_version: "bedrock-2023-05-31",
|
||||
max_tokens: 20000,
|
||||
temperature: 0.7,
|
||||
top_p: 0.9,
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: []
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
if (imagePath) {
|
||||
const imageBuffer = await fs.readFile(imagePath);
|
||||
const base64Image = imageBuffer.toString('base64');
|
||||
|
||||
requestBody.messages[0].content.push({
|
||||
type: "image",
|
||||
source: {
|
||||
type: "base64",
|
||||
media_type: "image/jpeg",
|
||||
data: base64Image
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
requestBody.messages[0].content.push({
|
||||
type: "text",
|
||||
text: prompt
|
||||
});
|
||||
|
||||
const params = {
|
||||
modelId: "anthropic.claude-3-sonnet-20240229-v1:0",
|
||||
contentType: "application/json",
|
||||
accept: "application/json",
|
||||
body: JSON.stringify(requestBody),
|
||||
};
|
||||
|
||||
const command = new InvokeModelCommand(params);
|
||||
const response = await bedrockClient.send(command);
|
||||
const responseBody = JSON.parse(new TextDecoder().decode(response.body));
|
||||
console.log("DEBUG: Raw response from Bedrock:", JSON.stringify(responseBody));
|
||||
|
||||
if (responseBody.content && Array.isArray(responseBody.content) && responseBody.content.length > 0) {
|
||||
const generatedText = responseBody.content[0].text;
|
||||
if (generatedText) {
|
||||
console.log("DEBUG: Generated text:", generatedText);
|
||||
return generatedText;
|
||||
} else {
|
||||
console.log("WARNING: Generated text is empty. Full response:", JSON.stringify(responseBody));
|
||||
return "No response generated";
|
||||
}
|
||||
} else {
|
||||
console.log("WARNING: Unexpected response format. Full response:", JSON.stringify(responseBody));
|
||||
return "Unexpected response format";
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("ERROR: Failed to generate text with Bedrock:", error);
|
||||
return "Error: " + error.message;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('generate-image', async (event, { prompt }) => {
|
||||
if (!bedrockClient) {
|
||||
throw new Error('Bedrock client not initialized');
|
||||
}
|
||||
|
||||
console.log("DEBUG: Generating image for prompt:", prompt);
|
||||
|
||||
try {
|
||||
const requestBody = {
|
||||
text_prompts: [{ text: prompt }],
|
||||
cfg_scale: 10,
|
||||
steps: 50,
|
||||
seed: Math.floor(Math.random() * 1000000),
|
||||
};
|
||||
|
||||
const params = {
|
||||
modelId: "stability.stable-diffusion-xl-v1",
|
||||
contentType: "application/json",
|
||||
accept: "application/json",
|
||||
body: JSON.stringify(requestBody),
|
||||
};
|
||||
|
||||
const command = new InvokeModelCommand(params);
|
||||
const response = await bedrockClient.send(command);
|
||||
const responseBody = JSON.parse(new TextDecoder().decode(response.body));
|
||||
|
||||
if (responseBody.artifacts && responseBody.artifacts.length > 0) {
|
||||
const imageBase64 = responseBody.artifacts[0].base64;
|
||||
const imagePath = path.join(app.getPath('userData'), `generated_image_${Date.now()}.png`);
|
||||
await fs.writeFile(imagePath, imageBase64, 'base64');
|
||||
return `safe-file://${imagePath}`; // Return the safe-file URL instead of the direct file path
|
||||
} else {
|
||||
throw new Error('No image generated');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("ERROR: Failed to generate image with Bedrock:", error);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
|
||||
app.on('window-all-closed', () => {
|
||||
if (process.platform !== 'darwin') {
|
||||
app.quit();
|
||||
}
|
||||
});
|
||||
|
||||
app.on('activate', () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
createWindow();
|
||||
}
|
||||
});
|
23
eslint.config.js
Normal file
23
eslint.config.js
Normal file
|
@ -0,0 +1,23 @@
|
|||
import js from '@eslint/js';
|
||||
import svelte from 'eslint-plugin-svelte';
|
||||
import prettier from 'eslint-config-prettier';
|
||||
import globals from 'globals';
|
||||
|
||||
/** @type {import('eslint').Linter.Config[]} */
|
||||
export default [
|
||||
js.configs.recommended,
|
||||
...svelte.configs['flat/recommended'],
|
||||
prettier,
|
||||
...svelte.configs['flat/prettier'],
|
||||
{
|
||||
languageOptions: {
|
||||
globals: {
|
||||
...globals.browser,
|
||||
...globals.node
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
ignores: ['build/', '.svelte-kit/', 'dist/']
|
||||
}
|
||||
];
|
19
jsconfig.json
Normal file
19
jsconfig.json
Normal file
|
@ -0,0 +1,19 @@
|
|||
{
|
||||
"extends": "./.svelte-kit/tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"allowJs": true,
|
||||
"checkJs": true,
|
||||
"esModuleInterop": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true,
|
||||
"skipLibCheck": true,
|
||||
"sourceMap": true,
|
||||
"strict": true,
|
||||
"moduleResolution": "bundler"
|
||||
}
|
||||
// Path aliases are handled by https://kit.svelte.dev/docs/configuration#alias
|
||||
// except $lib which is handled by https://kit.svelte.dev/docs/configuration#files
|
||||
//
|
||||
// If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes
|
||||
// from the referenced tsconfig.json - TypeScript does not merge them in
|
||||
}
|
1406
models/main.log
Normal file
1406
models/main.log
Normal file
File diff suppressed because it is too large
Load Diff
9773
package-lock.json
generated
Normal file
9773
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
54
package.json
Normal file
54
package.json
Normal file
|
@ -0,0 +1,54 @@
|
|||
{
|
||||
"name": "ai-rnl-answers-desktop",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"main": "electron.cjs",
|
||||
"scripts": {
|
||||
"dev": "vite dev",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"check": "svelte-kit sync && svelte-check --tsconfig ./jsconfig.json",
|
||||
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./jsconfig.json --watch",
|
||||
"lint": "prettier --check . && eslint .",
|
||||
"format": "prettier --write .",
|
||||
"electron-dev": "cross-env NODE_ENV=development concurrently \"npm run dev\" \"wait-on http://localhost:5173 && electron .\"",
|
||||
"electron-build": "npm run build && electron-builder"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@sveltejs/adapter-auto": "^3.0.0",
|
||||
"@sveltejs/adapter-static": "^3.0.2",
|
||||
"@sveltejs/kit": "^2.5.18",
|
||||
"@sveltejs/vite-plugin-svelte": "^3.0.0",
|
||||
"@tailwindcss/typography": "^0.5.13",
|
||||
"@types/eslint": "^9.6.0",
|
||||
"autoprefixer": "^10.4.19",
|
||||
"cross-env": "^7.0.3",
|
||||
"electron": "^31.3.0",
|
||||
"electron-builder": "^24.13.3",
|
||||
"eslint": "^9.0.0",
|
||||
"eslint-config-prettier": "^9.1.0",
|
||||
"eslint-plugin-svelte": "^2.36.0",
|
||||
"globals": "^15.0.0",
|
||||
"postcss": "^8.4.40",
|
||||
"prettier": "^3.1.1",
|
||||
"prettier-plugin-svelte": "^3.1.2",
|
||||
"svelte": "^4.2.7",
|
||||
"svelte-check": "^3.6.0",
|
||||
"svelte-preprocess": "^6.0.2",
|
||||
"tailwindcss": "^3.4.7",
|
||||
"typescript": "^5.0.0",
|
||||
"vite": "^5.0.3",
|
||||
"wait-on": "^7.2.0"
|
||||
},
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-bedrock-runtime": "^3.620.0",
|
||||
"@aws-sdk/credential-provider-ini": "^3.620.0",
|
||||
"axios": "^1.7.2",
|
||||
"cheerio": "^1.0.0-rc.12",
|
||||
"highlight.js": "^11.10.0",
|
||||
"marked": "^13.0.3",
|
||||
"nedb": "^1.8.0",
|
||||
"node-llama-cpp": "^2.8.14"
|
||||
}
|
||||
}
|
6
postcss.config.cjs
Normal file
6
postcss.config.cjs
Normal file
|
@ -0,0 +1,6 @@
|
|||
module.exports = {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
}
|
6
postcss.config.js
Normal file
6
postcss.config.js
Normal file
|
@ -0,0 +1,6 @@
|
|||
module.exports = {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
}
|
25
src/app.css
Normal file
25
src/app.css
Normal file
|
@ -0,0 +1,25 @@
|
|||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
@layer components {
|
||||
.markdown-content {
|
||||
@apply prose max-w-none;
|
||||
}
|
||||
|
||||
.dark .markdown-content {
|
||||
@apply prose-invert;
|
||||
}
|
||||
|
||||
.markdown-content pre {
|
||||
@apply p-4 rounded-lg;
|
||||
}
|
||||
|
||||
.markdown-content code {
|
||||
@apply text-sm;
|
||||
}
|
||||
}
|
||||
|
||||
.dark {
|
||||
@apply bg-gray-900 text-white;
|
||||
}
|
13
src/app.d.ts
vendored
Normal file
13
src/app.d.ts
vendored
Normal file
|
@ -0,0 +1,13 @@
|
|||
// See https://kit.svelte.dev/docs/types#app
|
||||
// for information about these interfaces
|
||||
declare global {
|
||||
namespace App {
|
||||
// interface Error {}
|
||||
// interface Locals {}
|
||||
// interface PageData {}
|
||||
// interface PageState {}
|
||||
// interface Platform {}
|
||||
}
|
||||
}
|
||||
|
||||
export {};
|
12
src/app.html
Normal file
12
src/app.html
Normal file
|
@ -0,0 +1,12 @@
|
|||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
%sveltekit.head%
|
||||
</head>
|
||||
<body data-sveltekit-preload-data="hover">
|
||||
<div style="display: contents">%sveltekit.body%</div>
|
||||
</body>
|
||||
</html>
|
21
src/lib/db.js
Normal file
21
src/lib/db.js
Normal file
|
@ -0,0 +1,21 @@
|
|||
import Datastore from 'nedb';
|
||||
|
||||
const db = new Datastore({ filename: 'chat.db', autoload: true });
|
||||
|
||||
export function saveMessage(message) {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.insert(message, (err, newDoc) => {
|
||||
if (err) reject(err);
|
||||
else resolve(newDoc);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function getMessages() {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.find({}).sort({ timestamp: 1 }).exec((err, docs) => {
|
||||
if (err) reject(err);
|
||||
else resolve(docs);
|
||||
});
|
||||
});
|
||||
}
|
1
src/lib/index.js
Normal file
1
src/lib/index.js
Normal file
|
@ -0,0 +1 @@
|
|||
// place files you want to import through the `$lib` alias in this folder.
|
5
src/routes/+layout.svelte
Normal file
5
src/routes/+layout.svelte
Normal file
|
@ -0,0 +1,5 @@
|
|||
<script>
|
||||
import '../app.css';
|
||||
</script>
|
||||
|
||||
<slot />
|
464
src/routes/+page.svelte
Normal file
464
src/routes/+page.svelte
Normal file
|
@ -0,0 +1,464 @@
|
|||
<script>
|
||||
import { onMount } from 'svelte';
|
||||
import { fade, fly } from 'svelte/transition';
|
||||
import { marked } from 'marked';
|
||||
import hljs from 'highlight.js';
|
||||
import 'highlight.js/styles/github-dark.css';
|
||||
import '../app.css';
|
||||
|
||||
let messages = [];
|
||||
let newMessage = '';
|
||||
let imagePath = '';
|
||||
let ipcRenderer;
|
||||
let currentStreamingMessage = '';
|
||||
let isGenerating = false;
|
||||
let fileInput;
|
||||
let sidebarOpen = false;
|
||||
let selectedModel = 'claude-3-sonnet';
|
||||
let temperature = 0.7;
|
||||
let maxTokens = 2000;
|
||||
let darkMode = false;
|
||||
let imagePrompt = '';
|
||||
let generatedImagePath = '';
|
||||
let fileTree = '';
|
||||
let fileContents = '';
|
||||
|
||||
let urlInput = '';
|
||||
let urlContent = '';
|
||||
let isLoadingUrl = false;
|
||||
|
||||
const models = [
|
||||
{ id: 'claude-3-sonnet', name: 'Claude 3 Sonnet' },
|
||||
{ id: 'claude-3-opus', name: 'Claude 3 Opus' },
|
||||
{ id: 'gpt-4', name: 'GPT-4' },
|
||||
{ id: 'llama-2-70b', name: 'LLaMA 2 70B' }
|
||||
];
|
||||
|
||||
onMount(() => {
|
||||
if (typeof window !== 'undefined' && window.require) {
|
||||
ipcRenderer = window.require('electron').ipcRenderer;
|
||||
|
||||
ipcRenderer.on('response-chunk', (event, chunk) => {
|
||||
currentStreamingMessage += chunk;
|
||||
messages = [...messages.slice(0, -1), { content: currentStreamingMessage, sender: 'ai' }];
|
||||
});
|
||||
|
||||
ipcRenderer.on('response-end', () => {
|
||||
isGenerating = false;
|
||||
currentStreamingMessage = '';
|
||||
});
|
||||
|
||||
ipcRenderer.on('response-error', (event, errorMessage) => {
|
||||
messages = [...messages, { content: 'Error: ' + errorMessage, sender: 'system' }];
|
||||
isGenerating = false;
|
||||
currentStreamingMessage = '';
|
||||
});
|
||||
|
||||
ipcRenderer.on('directory-content-fetched', (event, { tree, contents }) => {
|
||||
fileTree = tree;
|
||||
fileContents = contents;
|
||||
});
|
||||
}
|
||||
|
||||
// Configure marked to use highlight.js for code highlighting
|
||||
marked.setOptions({
|
||||
highlight: function (code, lang) {
|
||||
const language = hljs.getLanguage(lang) ? lang : 'plaintext';
|
||||
return hljs.highlight(code, { language }).value;
|
||||
},
|
||||
langPrefix: 'hljs language-'
|
||||
});
|
||||
|
||||
if (ipcRenderer) {
|
||||
ipcRenderer.on('url-content-fetched', (event, content) => {
|
||||
urlContent = content;
|
||||
isLoadingUrl = false;
|
||||
});
|
||||
|
||||
ipcRenderer.on('url-fetch-error', (event, error) => {
|
||||
console.error('Error fetching URL content:', error);
|
||||
urlContent = '';
|
||||
isLoadingUrl = false;
|
||||
messages = [
|
||||
...messages,
|
||||
{ content: `Error fetching URL content: ${error}`, sender: 'system' }
|
||||
];
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
async function selectDirectory() {
|
||||
if (ipcRenderer) {
|
||||
const result = await ipcRenderer.invoke('select-directory');
|
||||
if (result) {
|
||||
fileTree = result.tree;
|
||||
fileContents = result.contents;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function generateImage() {
|
||||
if (imagePrompt.trim()) {
|
||||
isGenerating = true;
|
||||
try {
|
||||
generatedImagePath = await ipcRenderer.invoke('generate-image', { prompt: imagePrompt });
|
||||
messages = [
|
||||
...messages,
|
||||
{
|
||||
content: {
|
||||
text: `Generated image for prompt: ${imagePrompt}`,
|
||||
image: generatedImagePath
|
||||
},
|
||||
sender: 'system'
|
||||
}
|
||||
];
|
||||
imagePrompt = '';
|
||||
} catch (error) {
|
||||
console.error('Error generating image:', error);
|
||||
messages = [
|
||||
...messages,
|
||||
{ content: 'Error generating image: ' + error.message, sender: 'system' }
|
||||
];
|
||||
} finally {
|
||||
isGenerating = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function handleFileUpload(event) {
|
||||
const file = event.target.files[0];
|
||||
if (file) {
|
||||
imagePath = file.path;
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchUrlContent() {
|
||||
if (urlInput.trim()) {
|
||||
isLoadingUrl = true;
|
||||
if (ipcRenderer) {
|
||||
ipcRenderer.invoke('fetch-url-content', urlInput);
|
||||
} else {
|
||||
// Fallback for browser environment or error
|
||||
isLoadingUrl = false;
|
||||
messages = [
|
||||
...messages,
|
||||
{ content: 'URL fetching is only available in the Electron app.', sender: 'system' }
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function sendMessage() {
|
||||
if (newMessage.trim() || imagePath || urlContent || fileTree) {
|
||||
const userMessage = { text: newMessage, image: imagePath };
|
||||
messages = [
|
||||
...messages,
|
||||
{ content: userMessage, sender: 'user' },
|
||||
{ content: '', sender: 'ai' }
|
||||
];
|
||||
const promptToSend = newMessage;
|
||||
newMessage = '';
|
||||
const imagePathToSend = imagePath;
|
||||
imagePath = '';
|
||||
isGenerating = true;
|
||||
currentStreamingMessage = '';
|
||||
|
||||
if (ipcRenderer) {
|
||||
ipcRenderer.invoke('generate-response-stream', {
|
||||
prompt: promptToSend,
|
||||
imagePath: imagePathToSend,
|
||||
model: selectedModel,
|
||||
temperature,
|
||||
maxTokens,
|
||||
context: urlContent,
|
||||
fileTree,
|
||||
fileContents
|
||||
});
|
||||
urlContent = '';
|
||||
fileTree = '';
|
||||
fileContents = '';
|
||||
} else {
|
||||
// Fallback for browser environment
|
||||
messages = [
|
||||
...messages,
|
||||
{ content: 'This feature is only available in the Electron app.', sender: 'system' }
|
||||
];
|
||||
isGenerating = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function triggerFileUpload() {
|
||||
fileInput.click();
|
||||
}
|
||||
|
||||
function toggleDarkMode() {
|
||||
darkMode = !darkMode;
|
||||
if (darkMode) {
|
||||
document.documentElement.classList.add('dark');
|
||||
} else {
|
||||
document.documentElement.classList.remove('dark');
|
||||
}
|
||||
}
|
||||
|
||||
$: formattedMessages = messages.map((message) => {
|
||||
if (message.sender === 'ai') {
|
||||
return { ...message, content: marked(message.content) };
|
||||
}
|
||||
return message;
|
||||
});
|
||||
</script>
|
||||
|
||||
<main class="flex h-screen bg-gray-100 transition-colors duration-200">
|
||||
<!-- Sidebar -->
|
||||
<div
|
||||
class="w-64 bg-white shadow-md transition-all duration-300 ease-in-out {sidebarOpen
|
||||
? 'translate-x-0'
|
||||
: '-translate-x-full'} absolute inset-y-0 left-0 z-30 lg:relative lg:translate-x-0"
|
||||
>
|
||||
<div class="p-4">
|
||||
<h2 class="text-xl font-bold mb-4 dark:text-white">Settings</h2>
|
||||
<div class="mb-4">
|
||||
<label
|
||||
class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
|
||||
for="model-select">Model</label
|
||||
>
|
||||
<select
|
||||
id="model-select"
|
||||
bind:value={selectedModel}
|
||||
class="w-full p-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
|
||||
>
|
||||
{#each models as model}
|
||||
<option value={model.id}>{model.name}</option>
|
||||
{/each}
|
||||
</select>
|
||||
</div>
|
||||
<div class="mb-4">
|
||||
<label
|
||||
class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
|
||||
for="temperature">Temperature: {temperature}</label
|
||||
>
|
||||
<input
|
||||
type="range"
|
||||
id="temperature"
|
||||
bind:value={temperature}
|
||||
min="0"
|
||||
max="1"
|
||||
step="0.1"
|
||||
class="w-full"
|
||||
/>
|
||||
</div>
|
||||
<div class="mb-4">
|
||||
<label
|
||||
class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
|
||||
for="max-tokens">Max Tokens: {maxTokens}</label
|
||||
>
|
||||
<input
|
||||
type="range"
|
||||
id="max-tokens"
|
||||
bind:value={maxTokens}
|
||||
min="100"
|
||||
max="4000"
|
||||
step="100"
|
||||
class="w-full"
|
||||
/>
|
||||
</div>
|
||||
<div class="mb-4">
|
||||
<label class="flex items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
bind:checked={darkMode}
|
||||
on:change={toggleDarkMode}
|
||||
class="form-checkbox h-5 w-5 text-indigo-600"
|
||||
/>
|
||||
<span class="ml-2 text-gray-700 dark:text-gray-300">Dark Mode</span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="p-4 border-t border-gray-200 dark:border-gray-700">
|
||||
<h3 class="text-lg font-semibold mb-2 dark:text-white">Image Generation</h3>
|
||||
<input
|
||||
bind:value={imagePrompt}
|
||||
placeholder="Enter image prompt"
|
||||
class="w-full p-2 rounded-md border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white mb-2"
|
||||
/>
|
||||
<button
|
||||
on:click={generateImage}
|
||||
class="w-full p-2 bg-green-500 text-white rounded-md hover:bg-green-600 transition-colors"
|
||||
disabled={isGenerating}
|
||||
>
|
||||
Generate Image
|
||||
</button>
|
||||
</div>
|
||||
<!-- Add URL input section -->
|
||||
<div class="p-4 border-t border-gray-200 dark:border-gray-700">
|
||||
<h3 class="text-lg font-semibold mb-2 dark:text-white">URL Context</h3>
|
||||
<input
|
||||
bind:value={urlInput}
|
||||
placeholder="Enter URL to fetch content"
|
||||
class="w-full p-2 rounded-md border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white mb-2"
|
||||
/>
|
||||
<button
|
||||
on:click={fetchUrlContent}
|
||||
class="w-full p-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition-colors"
|
||||
disabled={isLoadingUrl}
|
||||
>
|
||||
{isLoadingUrl ? 'Fetching...' : 'Fetch URL Content'}
|
||||
</button>
|
||||
{#if urlContent}
|
||||
<p class="mt-2 text-sm text-gray-600 dark:text-gray-300">
|
||||
URL content fetched and ready to use as context.
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Add Directory Selection section -->
|
||||
<div class="p-4 border-t border-gray-200 dark:border-gray-700">
|
||||
<h3 class="text-lg font-semibold mb-2 dark:text-white">Directory Context</h3>
|
||||
<button
|
||||
on:click={selectDirectory}
|
||||
class="w-full p-2 bg-purple-500 text-white rounded-md hover:bg-purple-600 transition-colors"
|
||||
>
|
||||
Select Directory
|
||||
</button>
|
||||
{#if fileTree}
|
||||
<p class="mt-2 text-sm text-gray-600 dark:text-gray-300">
|
||||
Directory content fetched and ready to use as context.
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Main content -->
|
||||
<div class="flex-1 flex flex-col">
|
||||
<!-- Chat area -->
|
||||
<div class="flex-1 overflow-y-auto p-4 space-y-4">
|
||||
{#each messages as message, i (i)}
|
||||
<div
|
||||
class="flex {message.sender === 'user' ? 'justify-end' : 'justify-start'}"
|
||||
transition:fly={{ y: 20, duration: 300 }}
|
||||
>
|
||||
<div
|
||||
class="max-w-xs lg:max-w-md xl:max-w-lg rounded-lg p-3 {message.sender === 'user'
|
||||
? 'bg-indigo-500 text-white'
|
||||
: 'bg-white dark:bg-gray-700 text-gray-800 dark:text-white'} shadow"
|
||||
>
|
||||
{#if message.content.image}
|
||||
<img
|
||||
src={message.content.image}
|
||||
alt="Generated or uploaded image"
|
||||
class="max-w-full rounded-lg mb-2"
|
||||
/>
|
||||
{/if}
|
||||
{#if typeof message.content === 'string'}
|
||||
<div class="text-sm markdown-content">
|
||||
{@html marked(message.content)}
|
||||
</div>
|
||||
{:else}
|
||||
<p class="text-sm">{message.content.text}</p>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
{#if isGenerating}
|
||||
<div class="flex justify-start" transition:fade>
|
||||
<div class="bg-gray-200 dark:bg-gray-600 rounded-lg px-4 py-2">
|
||||
<span class="animate-pulse dark:text-white">AI is thinking...</span>
|
||||
{#if currentStreamingMessage}
|
||||
<div class="text-sm markdown-content mt-2">
|
||||
{@html marked(currentStreamingMessage)}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Input area -->
|
||||
<div class="bg-white dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700 p-4">
|
||||
<div class="flex items-start space-x-2">
|
||||
<button
|
||||
on:click={triggerFileUpload}
|
||||
class="p-2 rounded-full bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 transition-colors flex-shrink-0"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
class="h-6 w-6 text-gray-600 dark:text-gray-300"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
<textarea
|
||||
bind:value={newMessage}
|
||||
on:keypress={(e) => e.key === 'Enter' && !e.shiftKey && sendMessage()}
|
||||
placeholder="Type your message..."
|
||||
class="flex-1 p-2 rounded-lg border border-gray-300 dark:border-gray-600 focus:outline-none focus:ring-2 focus:ring-indigo-500 resize-none dark:bg-gray-700 dark:text-white"
|
||||
rows="3"
|
||||
></textarea>
|
||||
<button
|
||||
on:click={sendMessage}
|
||||
class="p-2 rounded-full bg-indigo-500 hover:bg-indigo-600 transition-colors flex-shrink-0"
|
||||
disabled={isGenerating}
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
class="h-6 w-6 text-white"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*"
|
||||
on:change={handleFileUpload}
|
||||
class="hidden"
|
||||
bind:this={fileInput}
|
||||
/>
|
||||
|
||||
<!-- Mobile sidebar toggle -->
|
||||
<button
|
||||
on:click={() => (sidebarOpen = !sidebarOpen)}
|
||||
class="fixed bottom-4 right-4 p-2 rounded-full bg-indigo-500 text-white shadow-lg lg:hidden z-40"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
class="h-6 w-6"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"
|
||||
/>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</main>
|
BIN
static/favicon.png
Normal file
BIN
static/favicon.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 1.5 KiB |
10
svelte.config.js
Normal file
10
svelte.config.js
Normal file
|
@ -0,0 +1,10 @@
|
|||
import adapter from '@sveltejs/adapter-static';
|
||||
|
||||
/** @type {import('@sveltejs/kit').Config} */
|
||||
const config = {
|
||||
kit: {
|
||||
adapter: adapter()
|
||||
}
|
||||
};
|
||||
|
||||
export default config;
|
11
tailwind.config.js
Normal file
11
tailwind.config.js
Normal file
|
@ -0,0 +1,11 @@
|
|||
/** @type {import('tailwindcss').Config} */
|
||||
module.exports = {
|
||||
content: ['./src/**/*.{html,js,svelte,ts}'],
|
||||
darkMode: 'class',
|
||||
theme: {
|
||||
extend: {},
|
||||
},
|
||||
plugins: [
|
||||
require('@tailwindcss/typography'),
|
||||
],
|
||||
}
|
13
vite.config.js
Normal file
13
vite.config.js
Normal file
|
@ -0,0 +1,13 @@
|
|||
import { sveltekit } from '@sveltejs/kit/vite';
|
||||
import { defineConfig } from 'vite';
|
||||
import tailwindcss from 'tailwindcss';
|
||||
import autoprefixer from 'autoprefixer';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [sveltekit()],
|
||||
css: {
|
||||
postcss: {
|
||||
plugins: [tailwindcss, autoprefixer],
|
||||
},
|
||||
},
|
||||
});
|
Loading…
Reference in New Issue
Block a user