mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 16:03:34 +00:00
Compare commits
259
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
31b2a1eb4e | ||
|
|
2f50b2611c | ||
|
|
6bbee282be | ||
|
|
dd0f105c87 | ||
|
|
83b20c88f0 | ||
|
|
52863b808b | ||
|
|
0fb4bcf375 | ||
|
|
8f66e44162 | ||
|
|
4e231844a5 | ||
|
|
3a546880f8 | ||
|
|
4106bc77b3 | ||
|
|
77f29c12af | ||
|
|
d8806d1ee4 | ||
|
|
3592aff575 | ||
|
|
62b1a19f2d | ||
|
|
d8bf0d0432 | ||
|
|
c03e630d66 | ||
|
|
73ccd7cb73 | ||
|
|
a9b22e2381 | ||
|
|
f7b2d754e9 | ||
|
|
9c86ced552 | ||
|
|
631cd98a1b | ||
|
|
48cbc46d9b | ||
|
|
5fab750222 | ||
|
|
de3fb92304 | ||
|
|
ed426b0eab | ||
|
|
2eda6749ce | ||
|
|
3f0d49ceb3 | ||
|
|
f42ca5897a | ||
|
|
3b44deb26f | ||
|
|
b2266581ad | ||
|
|
147a620a0f | ||
|
|
25d065f112 | ||
|
|
9181124467 | ||
|
|
465364ffc0 | ||
|
|
0b076d2114 | ||
|
|
e1028e9f5e | ||
|
|
1f850bc8a2 | ||
|
|
8aa04464db | ||
|
|
db2739cb77 | ||
|
|
60a4f77364 | ||
|
|
0d524f7c36 | ||
|
|
6455b1d933 | ||
|
|
d35b6601c5 | ||
|
|
fefd589187 | ||
|
|
38450a4793 | ||
|
|
1f15dc7380 | ||
|
|
084b1e4d72 | ||
|
|
49300ed7b0 | ||
|
|
c2ccc3e60b | ||
|
|
d97bf1e2aa | ||
|
|
67a2290b89 | ||
|
|
b9bc22eaf0 | ||
|
|
21341304b8 | ||
|
|
799aaa5696 | ||
|
|
32892c8840 | ||
|
|
8b1f2e381c | ||
|
|
16b49e82bb | ||
|
|
6885e2beec | ||
|
|
b8638ac13a | ||
|
|
ff51fa2f77 | ||
|
|
8b193c3a33 | ||
|
|
6ba82b5e4a | ||
|
|
8bad3cfc81 | ||
|
|
3f792defcc | ||
|
|
274f9715ba | ||
|
|
bbee14b675 | ||
|
|
048846865f | ||
|
|
87fb13c131 | ||
|
|
dea9288fd4 | ||
|
|
6899220f27 | ||
|
|
16e1577dc9 | ||
|
|
487d3c378d | ||
|
|
25c2da6dd5 | ||
|
|
083ae9d82e | ||
|
|
c962e9632e | ||
|
|
32f12f08c1 | ||
|
|
5840a3ffe8 | ||
|
|
15690f25e5 | ||
|
|
26f02819b1 | ||
|
|
bc976fd58e | ||
|
|
5bcaff0536 | ||
|
|
8c5dd1f49c | ||
|
|
096e703c20 | ||
|
|
e6c7cc4316 | ||
|
|
b13b96c8fb | ||
|
|
7f378311ca | ||
|
|
720aba0ff7 | ||
|
|
67fc846ba3 | ||
|
|
9a288c38c7 | ||
|
|
acadf07a68 | ||
|
|
9005a2c38e | ||
|
|
4c9e688009 | ||
|
|
96b9088551 | ||
|
|
7b84447f29 | ||
|
|
2a39dcaf86 | ||
|
|
2096c83b3c | ||
|
|
bbb4a2534b | ||
|
|
5685c6f52f | ||
|
|
12c4acf3d5 | ||
|
|
77a648e77e | ||
|
|
ff6932ecda | ||
|
|
74b5f60df8 | ||
|
|
6c4bd9bd7c | ||
|
|
45061bfbb9 | ||
|
|
6ce25ad2a1 | ||
|
|
1f896b2ab5 | ||
|
|
ed7f60692d | ||
|
|
cc8a02a564 | ||
|
|
9017c5c382 | ||
|
|
3f3ac26c65 | ||
|
|
fef40abcae | ||
|
|
b345145ad3 | ||
|
|
46db6542aa | ||
|
|
f41d70442a | ||
|
|
6f94aaa45e | ||
|
|
18d088660f | ||
|
|
7e7ef35ff6 | ||
|
|
63d23f5510 | ||
|
|
a2ffc7bf9c | ||
|
|
4bc223e5af | ||
|
|
2179c8fdce | ||
|
|
00b476085d | ||
|
|
7badd0113f | ||
|
|
b3f47d41cb | ||
|
|
8cf2b8a9d4 | ||
|
|
f8743e3c63 | ||
|
|
ca0ae22cd3 | ||
|
|
01df64fce0 | ||
|
|
300fd26268 | ||
|
|
0c42af082a | ||
|
|
4f552334b2 | ||
|
|
bb9245118c | ||
|
|
2c42efd4e1 | ||
|
|
d3187d8c77 | ||
|
|
ab039d2fb7 | ||
|
|
02dcd5cbe8 | ||
|
|
69d8dfa9cd | ||
|
|
43ad67b048 | ||
|
|
5d1e2ddea0 | ||
|
|
e83ff56722 | ||
|
|
56d9bca5c7 | ||
|
|
89244d88e5 | ||
|
|
2096d526c4 | ||
|
|
367a6834eb | ||
|
|
9ede6bbd21 | ||
|
|
c1ad18bab7 | ||
|
|
0e27c4d394 | ||
|
|
cd77a8edd5 | ||
|
|
e05baee1f4 | ||
|
|
efbfd19f10 | ||
|
|
f256de7ab3 | ||
|
|
5d65638f32 | ||
|
|
2e65e1ee6c | ||
|
|
dfc372e1d4 | ||
|
|
e8c3406e55 | ||
|
|
0a191be435 | ||
|
|
40062b6b92 | ||
|
|
6540ab28e6 | ||
|
|
93ae204e5e | ||
|
|
2c9e8abf5d | ||
|
|
b47f715362 | ||
|
|
eadb628094 | ||
|
|
db05223c68 | ||
|
|
0a20d736ab | ||
|
|
fe0becb2c8 | ||
|
|
6941710a3d | ||
|
|
b67417115c | ||
|
|
23ad0a9d35 | ||
|
|
7112591aa3 | ||
|
|
8a65c76197 | ||
|
|
009142b854 | ||
|
|
f0c1784288 | ||
|
|
94b4dcbda6 | ||
|
|
c49e8811af | ||
|
|
37c72391a0 | ||
|
|
6c92b2dc4d | ||
|
|
676655ef66 | ||
|
|
27f9435be9 | ||
|
|
32656a8f5c | ||
|
|
bd9a276275 | ||
|
|
7fa4330249 | ||
|
|
b5c2c79feb | ||
|
|
f3a3d31977 | ||
|
|
68eee82c92 | ||
|
|
cd006889c8 | ||
|
|
d23778547f | ||
|
|
627a43309c | ||
|
|
07d594a373 | ||
|
|
5b8cb25675 | ||
|
|
89de28cb0c | ||
|
|
c5e5cafb77 | ||
|
|
926e63bb81 | ||
|
|
c768f5fbe6 | ||
|
|
2db50808d5 | ||
|
|
b7a55f7fd7 | ||
|
|
7fb9d765be | ||
|
|
1f570a0d8f | ||
|
|
d2a8ee36f7 | ||
|
|
f148bee88b | ||
|
|
199043e4bc | ||
|
|
4f73d99f64 | ||
|
|
3050e93555 | ||
|
|
fcc2b9902a | ||
|
|
30ead01178 | ||
|
|
393ed3ebca | ||
|
|
870b7ffb93 | ||
|
|
e2f816b6c1 | ||
|
|
c22332a7ce | ||
|
|
8199ca5a18 | ||
|
|
dc549e64bd | ||
|
|
e88b8c90d9 | ||
|
|
766aea14b9 | ||
|
|
653a7c0f0c | ||
|
|
42637458c9 | ||
|
|
a6caf93e8b | ||
|
|
b55fd857e1 | ||
|
|
65c51e865a | ||
|
|
8ecf460140 | ||
|
|
8ee4efdee3 | ||
|
|
5ac5fcc212 | ||
|
|
58c24f615d | ||
|
|
d1cbcda5d5 | ||
|
|
c30ed35c67 | ||
|
|
dea364c2a6 | ||
|
|
eabba1ecec | ||
|
|
db02b9fb94 | ||
|
|
4d88823c2d | ||
|
|
933530a96c | ||
|
|
43f4e0d15d | ||
|
|
21e522cba7 | ||
|
|
d8bfa10b43 | ||
|
|
7a000a80f0 | ||
|
|
866155d907 | ||
|
|
72439d4ec9 | ||
|
|
51f079696a | ||
|
|
abe3368115 | ||
|
|
16d357364d | ||
|
|
2d505588c7 | ||
|
|
a9ab551ca2 | ||
|
|
075d6aba2d | ||
|
|
a1f571b2d8 | ||
|
|
d4eca86ec6 | ||
|
|
44a208aed5 | ||
|
|
ccc3613c83 | ||
|
|
fd309e0aab | ||
|
|
3d06e0cb57 | ||
|
|
dbf5cfe0a3 | ||
|
|
0b66f81bfc | ||
|
|
35a85c18bd | ||
|
|
e116f7e9ec | ||
|
|
cbf18d482d | ||
|
|
d11a52992e | ||
|
|
056f2a0b5f | ||
|
|
50897e1164 | ||
|
|
db001beeb5 | ||
|
|
301b0d526b | ||
|
|
c474cd5c6c | ||
|
|
465bef91e8 |
No files matched your search
@@ -38,7 +38,6 @@ Shakespeare provides AI agents with specialized tools for project development (n
|
||||
- **TextEditorWriteTool**: Create or overwrite files with new content
|
||||
- **TextEditorStrReplaceTool**: Replace strings in files
|
||||
- **BuildProjectTool**: Build and compile projects
|
||||
- **TypecheckTool**: Run TypeScript type checking
|
||||
- **NpmAddPackageTool**: Add npm packages to projects
|
||||
- **NpmRemovePackageTool**: Remove npm packages from projects
|
||||
- **GitCommitTool**: Commit changes to Git repositories
|
||||
@@ -91,6 +90,7 @@ Shakespeare provides full Git functionality in the browser using `isomorphic-git
|
||||
- **LightningFSAdapter**: Adapts LightningFS to the unified JSRuntimeFS interface
|
||||
- **GitCommitTool**: AI tool for automated commits with staging and validation
|
||||
- **useGitStatus Hook**: Real-time Git status monitoring (updates every 5 seconds)
|
||||
- **useGitFetch Hook**: Automatic remote fetch with change detection (updates every 60 seconds, shows toast notifications)
|
||||
- **ProjectsManager**: Handles project creation, Git initialization, and template cloning
|
||||
|
||||
#### Core Features
|
||||
@@ -219,6 +219,7 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
|
||||
- `useGitSettings`: Manage Git credentials and repository settings
|
||||
- `useSessionManager`: Access session management for AI chat sessions
|
||||
- `useGitStatus`: Real-time Git repository status monitoring
|
||||
- `useGitFetch`: Automatic remote fetch with change detection and toast notifications
|
||||
- `useProjects`: Project management and CRUD operations
|
||||
- `useProjectsManager`: Advanced project operations (creation, cloning, building, ZIP import)
|
||||
- `useTheme`: Theme management
|
||||
@@ -239,7 +240,7 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
|
||||
- Unix-style commands: `cat`, `cd`, `cp`, `find`, `grep`, `ls`, `mkdir`, `mv`, `rm`, etc.
|
||||
- `/src/lib/tools/`: AI tool implementations for project development
|
||||
- File operations: `TextEditorViewTool`, `TextEditorWriteTool`, `TextEditorStrReplaceTool`
|
||||
- Project tools: `BuildProjectTool`, `TypecheckTool`, `DeployProjectTool`
|
||||
- Project tools: `BuildProjectTool`, `DeployProjectTool`
|
||||
- Package management: `NpmAddPackageTool`, `NpmRemovePackageTool`
|
||||
- Git integration: `GitCommitTool`
|
||||
- Shell access: `ShellTool`
|
||||
|
||||
@@ -34,7 +34,6 @@ Shakespeare is proudly Open Source software licensed under the GNU AGPLv3. The p
|
||||
Shakespeare is available on the following URLs:
|
||||
|
||||
- [shakespeare.diy](https://shakespeare.diy)
|
||||
- [shakespeare.soapbox.dev](https://shakespeare.soapbox.dev)
|
||||
- [shakespeare-diy.github.io](https://shakespeare-diy.github.io)
|
||||
- [shakespeare-b0b9c8.gitlab.io](https://shakespeare-b0b9c8.gitlab.io)
|
||||
|
||||
|
||||
+35
-20
@@ -178,9 +178,13 @@ ipcMain.handle('get-platform', () => {
|
||||
});
|
||||
|
||||
// Helper function to expand tilde (~) in paths
|
||||
// Handles both Unix (~/) and Windows (~\) style paths
|
||||
function expandTilde(filepath) {
|
||||
if (filepath.startsWith('~/') || filepath === '~') {
|
||||
return path.join(os.homedir(), filepath.slice(1));
|
||||
if (filepath === '~') {
|
||||
return os.homedir();
|
||||
}
|
||||
if (filepath.startsWith('~/') || filepath.startsWith('~\\')) {
|
||||
return path.join(os.homedir(), filepath.slice(2));
|
||||
}
|
||||
return filepath;
|
||||
}
|
||||
@@ -188,10 +192,8 @@ function expandTilde(filepath) {
|
||||
// Filesystem IPC handlers
|
||||
ipcMain.handle('fs:readFile', async (event, filePath, encoding) => {
|
||||
if (!filePath) {
|
||||
const err = new Error('Failed to read file: path is required');
|
||||
err.code = 'EINVAL';
|
||||
// Don't log - empty paths are expected from isomorphic-git's ref resolution
|
||||
throw err;
|
||||
// Return error object instead of throwing to avoid Electron's noisy error logging
|
||||
return { __error: true, code: 'EINVAL', message: 'Failed to read file: path is required' };
|
||||
}
|
||||
try {
|
||||
const fullPath = expandTilde(filePath);
|
||||
@@ -199,10 +201,13 @@ ipcMain.handle('fs:readFile', async (event, filePath, encoding) => {
|
||||
// If no encoding, convert Buffer to array for IPC serialization
|
||||
return encoding ? data : Array.from(data);
|
||||
} catch (error) {
|
||||
// Re-throw with original error code preserved for ENOENT handling
|
||||
// Serialize the error code as a regular property so it survives IPC
|
||||
// For ENOENT/EINVAL errors, return error info instead of throwing to avoid Electron's noisy error logging
|
||||
// These are expected during module resolution and git operations
|
||||
if (error.code === 'ENOENT' || error.code === 'EINVAL') {
|
||||
return { __error: true, code: error.code, message: `Failed to read file ${filePath}: ${error.message}` };
|
||||
}
|
||||
// Re-throw other errors with original error code preserved
|
||||
const err = new Error(`Failed to read file ${filePath}: ${error.message}`);
|
||||
// Copy enumerable properties including code
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
@@ -211,11 +216,7 @@ ipcMain.handle('fs:readFile', async (event, filePath, encoding) => {
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
// Don't log ENOENT errors - these are expected for git packed objects and missing refs
|
||||
// Only log unexpected errors
|
||||
if (error.code !== 'ENOENT' && error.code !== 'EINVAL') {
|
||||
console.error(err);
|
||||
}
|
||||
console.error(err);
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
@@ -263,7 +264,11 @@ ipcMain.handle('fs:readdir', async (event, dirPath, withFileTypes) => {
|
||||
|
||||
return entries;
|
||||
} catch (error) {
|
||||
// Re-throw with original error code preserved for ENOENT handling
|
||||
// Return error object instead of throwing for expected errors to suppress Electron's noisy logging
|
||||
if (error.code === 'ENOTDIR' || error.code === 'ENOENT') {
|
||||
return { __error: true, message: error.message, code: error.code };
|
||||
}
|
||||
// For other errors, re-throw with original error code preserved
|
||||
const err = new Error(`Failed to read directory ${dirPath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
@@ -273,10 +278,6 @@ ipcMain.handle('fs:readdir', async (event, dirPath, withFileTypes) => {
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
// Only log non-ENOTDIR errors (ENOTDIR is expected when checking if a file is a directory)
|
||||
if (error.code !== 'ENOTDIR') {
|
||||
console.error(err);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
@@ -323,7 +324,12 @@ ipcMain.handle('fs:stat', async (event, filePath) => {
|
||||
atime: stats.atime?.getTime() ?? now,
|
||||
};
|
||||
} catch (error) {
|
||||
// Re-throw with original error code preserved for ENOENT handling
|
||||
// For ENOENT errors, return error info instead of throwing to avoid Electron's noisy error logging
|
||||
// These are expected during module resolution and git operations
|
||||
if (error.code === 'ENOENT') {
|
||||
return { __error: true, code: 'ENOENT', message: `Failed to stat ${filePath}: ${error.message}` };
|
||||
}
|
||||
// Re-throw other errors with original error code preserved
|
||||
const err = new Error(`Failed to stat ${filePath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
@@ -361,6 +367,10 @@ ipcMain.handle('fs:lstat', async (event, filePath) => {
|
||||
atime: stats.atime?.getTime() ?? now,
|
||||
};
|
||||
} catch (error) {
|
||||
// For ENOENT errors, return error info instead of throwing to avoid Electron's noisy error logging
|
||||
if (error.code === 'ENOENT') {
|
||||
return { __error: true, code: 'ENOENT', message: `Failed to lstat ${filePath}: ${error.message}` };
|
||||
}
|
||||
const err = new Error(`Failed to lstat ${filePath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
@@ -379,6 +389,11 @@ ipcMain.handle('fs:unlink', async (event, filePath) => {
|
||||
const fullPath = expandTilde(filePath);
|
||||
await fs.unlink(fullPath);
|
||||
} catch (error) {
|
||||
// Return error object instead of throwing for ENOENT to suppress Electron's noisy logging
|
||||
// This is expected when isomorphic-git tries to delete .git/shallow on non-shallow clones
|
||||
if (error.code === 'ENOENT') {
|
||||
return { __error: true, message: error.message, code: error.code };
|
||||
}
|
||||
const err = new Error(`Failed to unlink ${filePath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@
|
||||
<meta property="og:title" content="Shakespeare - Open Source AI Builder">
|
||||
<meta property="og:description" content="Build custom apps with AI assistance using Shakespeare, an open-source development environment">
|
||||
<meta property="og:image" content="https://shakespeare.diy/og-image.png">
|
||||
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: http: wss: ws:; img-src 'self' data: blob: https:; media-src 'self' https:">
|
||||
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self' 'unsafe-eval' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; worker-src 'self' blob:; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: http: wss: ws:; img-src 'self' data: blob: https:; media-src 'self' https:">
|
||||
<link rel="icon" type="image/png" href="/shakespeare-192x192.png">
|
||||
<link rel="apple-touch-icon" href="/shakespeare-192x192.png" sizes="192x192">
|
||||
<meta name="theme-color" content="#2b0037">
|
||||
|
||||
Generated
+745
-21
File diff suppressed because it is too large.
Load diff
+4
-1
@@ -18,7 +18,7 @@
|
||||
"build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
|
||||
"typecheck": "npm i --silent && tsc --noEmit",
|
||||
"test": "npm i --silent && eslint && vitest run --reporter=dot --silent && echo 'All tests passed!'",
|
||||
"electron": "npm run build && rm -rf electron/dist && cp -r dist electron/dist && electron electron",
|
||||
"electron": "npm run build && rm -rf electron/dist && cp -r dist electron/dist && node scripts/prepare-electron-publish.js && electron electron",
|
||||
"electron:publish": "npm run build && node scripts/prepare-electron-publish.js && cd electron && npm publish"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -29,6 +29,7 @@
|
||||
"@getalby/sdk": "^6.0.1",
|
||||
"@hookform/resolvers": "^3.9.0",
|
||||
"@isomorphic-git/lightning-fs": "^4.6.2",
|
||||
"@modelcontextprotocol/sdk": "^1.22.0",
|
||||
"@mozilla/readability": "^0.6.0",
|
||||
"@nostrify/nostrify": "^0.47.1",
|
||||
"@nostrify/react": "^0.2.17",
|
||||
@@ -81,6 +82,7 @@
|
||||
"lucide-react": "^0.525.0",
|
||||
"mime": "^4.1.0",
|
||||
"nostr-tools": "^2.15.2",
|
||||
"nunjucks": "^3.2.4",
|
||||
"openai": "^5.15.0",
|
||||
"path-browserify": "^1.0.1",
|
||||
"prismjs": "^1.30.0",
|
||||
@@ -118,6 +120,7 @@
|
||||
"@testing-library/user-event": "^14.6.1",
|
||||
"@types/jszip": "^3.4.0",
|
||||
"@types/node": "^22.5.5",
|
||||
"@types/nunjucks": "^3.2.6",
|
||||
"@types/path-browserify": "^1.0.3",
|
||||
"@types/prismjs": "^1.26.5",
|
||||
"@types/qrcode": "^1.5.5",
|
||||
|
||||
+2
-1
@@ -1 +1,2 @@
|
||||
/* /index.html 200
|
||||
/assets/* /assets/:splat 200
|
||||
/* /index.html 200
|
||||
+2
-2
@@ -13,7 +13,7 @@ export default {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
"Access-Control-Allow-Methods": "GET,HEAD,POST,OPTIONS",
|
||||
"Access-Control-Allow-Methods": "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS",
|
||||
"Access-Control-Allow-Headers": "*", // Or specify specific headers
|
||||
"Access-Control-Max-Age": "86400", // Cache preflight for 24 hours
|
||||
}
|
||||
@@ -32,7 +32,7 @@ export default {
|
||||
const response = new Response(targetResponse.body, targetResponse);
|
||||
|
||||
response.headers.set("Access-Control-Allow-Origin", "*");
|
||||
response.headers.set("Access-Control-Allow-Methods", "GET,HEAD,POST,OPTIONS");
|
||||
response.headers.set("Access-Control-Allow-Methods", "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS");
|
||||
response.headers.set("Access-Control-Allow-Headers", "*");
|
||||
|
||||
return response;
|
||||
|
||||
+46
-7
@@ -48,7 +48,7 @@ const queryClient = new QueryClient({
|
||||
});
|
||||
|
||||
// Get OS-specific default paths for Electron
|
||||
function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: string; fsPathTmp: string; fsPathPlugins: string } {
|
||||
function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: string; fsPathTmp: string; fsPathPlugins: string; fsPathTemplates: string } {
|
||||
if (!globalThis.electron) {
|
||||
// Browser defaults - use virtual filesystem paths
|
||||
return {
|
||||
@@ -56,6 +56,7 @@ function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: stri
|
||||
fsPathConfig: "/config",
|
||||
fsPathTmp: "/tmp",
|
||||
fsPathPlugins: "/plugins",
|
||||
fsPathTemplates: "/templates",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -70,6 +71,7 @@ function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: stri
|
||||
fsPathConfig: "~/AppData/Local/shakespeare",
|
||||
fsPathTmp: "~/AppData/Local/Temp/shakespeare",
|
||||
fsPathPlugins: "~/AppData/Local/shakespeare/plugins",
|
||||
fsPathTemplates: "~/AppData/Local/shakespeare/templates",
|
||||
};
|
||||
} else if (platform.includes('mac')) {
|
||||
// macOS
|
||||
@@ -78,6 +80,7 @@ function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: stri
|
||||
fsPathConfig: "~/Library/Application Support/shakespeare",
|
||||
fsPathTmp: "/tmp/shakespeare",
|
||||
fsPathPlugins: "~/Library/Application Support/shakespeare/plugins",
|
||||
fsPathTemplates: "~/Library/Application Support/shakespeare/templates",
|
||||
};
|
||||
} else {
|
||||
// Linux and other Unix-like systems
|
||||
@@ -86,6 +89,7 @@ function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: stri
|
||||
fsPathConfig: "~/.config/shakespeare",
|
||||
fsPathTmp: "/tmp/shakespeare",
|
||||
fsPathPlugins: "~/.config/shakespeare/plugins",
|
||||
fsPathTemplates: "~/.config/shakespeare/templates",
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -102,7 +106,23 @@ const defaultConfig: AppConfig = {
|
||||
],
|
||||
updatedAt: 0,
|
||||
},
|
||||
projectTemplate: "https://gitlab.com/soapbox-pub/mkstack.git",
|
||||
templates: [
|
||||
{
|
||||
name: "MKStack",
|
||||
description: "Build Nostr clients with React. This is the default template that you should choose in the majority of cases. It ships with complete Nostr integration out of the box, enabling a variety of use-cases from social media to blogging to AI-powered apps. If you're not sure which template to choose, choose this one.",
|
||||
url: "https://gitlab.com/soapbox-pub/mkstack.git",
|
||||
},
|
||||
{
|
||||
name: "Nutstack",
|
||||
description: "This is a variant of MKStack extended to support Cashu integration. Choose this template only if the user has indicated they require Cashu integration.",
|
||||
url: "https://gitlab.com/lemonknowsall/nutstack.git",
|
||||
},
|
||||
{
|
||||
name: "Luvstack",
|
||||
description: "Barebones React template. Choose this to build mockups or demo sites that don't require Nostr functionality. Only choose this if the user has indicated they want to create a demo or mockup site, as it cannot support any sort of backend functionality or remote storage. It might also work for simple PWAs.",
|
||||
url: "https://gitlab.com/soapbox-pub/luvstack.git",
|
||||
}
|
||||
],
|
||||
esmUrl: "https://esm.sh",
|
||||
corsProxy: "https://proxy.shakespeare.diy/?url={href}",
|
||||
faviconUrl: "https://favicon.shakespeare.diy/?url={href}",
|
||||
@@ -114,6 +134,7 @@ const defaultConfig: AppConfig = {
|
||||
fsPathConfig: electronPaths.fsPathConfig,
|
||||
fsPathTmp: electronPaths.fsPathTmp,
|
||||
fsPathPlugins: electronPaths.fsPathPlugins,
|
||||
fsPathTemplates: electronPaths.fsPathTemplates,
|
||||
sentryDsn: import.meta.env.VITE_SENTRY_DSN || "",
|
||||
sentryEnabled: true,
|
||||
};
|
||||
@@ -125,15 +146,33 @@ const fs = globalThis.electron
|
||||
? new ElectronFSAdapter()
|
||||
: new LightningFSAdapter(new LightningFS('shakespeare-fs').promises);
|
||||
|
||||
// Component to handle filesystem cleanup on startup
|
||||
// Automatically removes files older than 1 hour from tmp directory
|
||||
// Component to handle filesystem initialization and cleanup on startup
|
||||
// Ensures tmp directory exists and removes files older than 1 hour
|
||||
function FSCleanupHandler() {
|
||||
const { config } = useAppContext();
|
||||
|
||||
useEffect(() => {
|
||||
// Run cleanup on application startup to remove stale temporary files
|
||||
// This helps prevent the VFS from accumulating old files over time
|
||||
cleanupTmpDirectory(fs, config.fsPathTmp).catch(console.error);
|
||||
// Ensure tmp directory exists before cleanup
|
||||
const initializeAndCleanup = async () => {
|
||||
try {
|
||||
// Create tmp directory if it doesn't exist
|
||||
try {
|
||||
await fs.stat(config.fsPathTmp);
|
||||
} catch {
|
||||
// Directory doesn't exist, create it
|
||||
await fs.mkdir(config.fsPathTmp);
|
||||
console.log(`Created ${config.fsPathTmp} directory`);
|
||||
}
|
||||
|
||||
// Run cleanup to remove stale temporary files
|
||||
// This helps prevent the VFS from accumulating old files over time
|
||||
await cleanupTmpDirectory(fs, config.fsPathTmp);
|
||||
} catch (error) {
|
||||
console.error(`Error during filesystem initialization:`, error);
|
||||
}
|
||||
};
|
||||
|
||||
initializeAndCleanup();
|
||||
}, [config.fsPathTmp]);
|
||||
|
||||
return null;
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { memo, useState } from 'react';
|
||||
import { Streamdown } from 'streamdown';
|
||||
import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus, Terminal, Globe, CheckCircle, Lightbulb, Loader2, Logs, Send, Puzzle } from 'lucide-react';
|
||||
import { Lightbulb, Loader2 } from 'lucide-react';
|
||||
import type { AIMessage } from '@/lib/SessionManager';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { UserMessage } from '@/components/UserMessage';
|
||||
import { ImageLightbox } from '@/components/ImageLightbox';
|
||||
import { ToolCallDisplay } from '@/components/ToolCallDisplay';
|
||||
import OpenAI from 'openai';
|
||||
import { useTheme } from '@/hooks/useTheme';
|
||||
import { isEmptyMessage } from '@/lib/isEmptyMessage';
|
||||
@@ -24,8 +26,8 @@ export const AIMessageItem = memo(({
|
||||
isCurrentlyLoading = false,
|
||||
toolCall,
|
||||
}: AIMessageItemProps) => {
|
||||
const [isToolExpanded, setIsToolExpanded] = useState(false);
|
||||
const [isReasoningExpanded, setIsReasoningExpanded] = useState(false);
|
||||
const [expandedImageUrl, setExpandedImageUrl] = useState<string | null>(null);
|
||||
const { displayTheme } = useTheme();
|
||||
|
||||
// Get content to display
|
||||
@@ -47,162 +49,11 @@ export const AIMessageItem = memo(({
|
||||
return '';
|
||||
};
|
||||
|
||||
// Get tool info including icon and title
|
||||
const getToolInfo = () => {
|
||||
if (message.role === 'tool' && toolCall) {
|
||||
if (toolCall.type === 'function') {
|
||||
const toolName = toolCall.function.name;
|
||||
let args;
|
||||
|
||||
try {
|
||||
args = JSON.parse(toolCall.function.arguments);
|
||||
} catch {
|
||||
args = {};
|
||||
}
|
||||
|
||||
// Generate icons and titles based on tool name and arguments
|
||||
switch (toolName) {
|
||||
case 'shell':
|
||||
return {
|
||||
icon: Terminal,
|
||||
title: args.command ? args.command : 'Shell Command'
|
||||
};
|
||||
case 'text_editor_view': {
|
||||
const title = args.path
|
||||
? (args.start_line || args.end_line
|
||||
? `Viewed ${args.path} (lines ${args.start_line || 1}-${args.end_line || 'end'})`
|
||||
: `Viewed ${args.path}`)
|
||||
: 'Viewed File';
|
||||
return { icon: Eye, title };
|
||||
}
|
||||
case 'text_editor_write':
|
||||
return {
|
||||
icon: FileText,
|
||||
title: args.path ? `Wrote ${args.path}` : 'Wrote File'
|
||||
};
|
||||
case 'text_editor_str_replace':
|
||||
return {
|
||||
icon: Edit,
|
||||
title: args.path ? `Edited ${args.path}` : 'Edited File'
|
||||
};
|
||||
case 'npm_add_package': {
|
||||
const installTitle = args.name
|
||||
? (args.dev ? `Installed ${args.name} (dev)` : `Installed ${args.name}`)
|
||||
: 'Installed Package';
|
||||
return { icon: Package, title: installTitle };
|
||||
}
|
||||
case 'npm_remove_package':
|
||||
return {
|
||||
icon: PackageMinus,
|
||||
title: args.name ? `Removed ${args.name}` : 'Removed Package'
|
||||
};
|
||||
case 'git_commit':
|
||||
return {
|
||||
icon: GitCommit,
|
||||
title: args.message ? `Committed: ${args.message}` : 'Committed Changes'
|
||||
};
|
||||
case 'build_project':
|
||||
return {
|
||||
icon: Package,
|
||||
title: 'Built Project'
|
||||
};
|
||||
case 'nostr_read_nip':
|
||||
return {
|
||||
icon: BookOpen,
|
||||
title: args.nip ? `Read NIP-${args.nip}` : 'Read NIP'
|
||||
};
|
||||
case 'nostr_fetch_event':
|
||||
return {
|
||||
icon: Download,
|
||||
title: args.identifier ? `Fetched ${args.identifier.slice(0, 16)}...` : 'Fetched Event'
|
||||
};
|
||||
case 'nostr_read_kind':
|
||||
return {
|
||||
icon: Hash,
|
||||
title: args.kind !== undefined ? `Read Kind ${args.kind}` : 'Read Kind'
|
||||
};
|
||||
case 'nostr_read_tag':
|
||||
return {
|
||||
icon: Tag,
|
||||
title: args.tag ? `Read Tag "${args.tag}"` : 'Read Tag'
|
||||
};
|
||||
case 'nostr_read_protocol':
|
||||
return {
|
||||
icon: Network,
|
||||
title: args.doc ? `Read Protocol: ${args.doc}` : 'Read Protocol'
|
||||
};
|
||||
case 'nostr_read_nips_index':
|
||||
return {
|
||||
icon: List,
|
||||
title: 'Read NIPs Index'
|
||||
};
|
||||
case 'nostr_generate_kind':
|
||||
return {
|
||||
icon: Plus,
|
||||
title: args.range ? `Generated ${args.range} kind` : 'Generated Kind'
|
||||
};
|
||||
case 'nostr_publish_events': {
|
||||
const eventCount = args.events?.length || 0;
|
||||
return {
|
||||
icon: Send,
|
||||
title: eventCount > 1 ? `Published ${eventCount} Nostr events` : 'Published Nostr event'
|
||||
};
|
||||
}
|
||||
case 'deploy_project':
|
||||
return {
|
||||
icon: Globe,
|
||||
title: args.deployServer ? `Deployed to ${args.deployServer}` : 'Deployed Project'
|
||||
};
|
||||
case 'typecheck':
|
||||
return {
|
||||
icon: CheckCircle,
|
||||
title: 'TypeScript'
|
||||
};
|
||||
case 'read_console_messages':
|
||||
return {
|
||||
icon: Logs,
|
||||
title: 'Read Console'
|
||||
};
|
||||
case 'skill':
|
||||
return {
|
||||
icon: Puzzle,
|
||||
title: args.name ? `Skill: ${args.name}` : 'Skill'
|
||||
};
|
||||
default:
|
||||
return {
|
||||
icon: Wrench,
|
||||
title: toolName.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to extracting from content
|
||||
if (message.role === 'tool') {
|
||||
const content = getContent();
|
||||
const lines = content.split('\n');
|
||||
const firstLine = lines[0];
|
||||
|
||||
if (firstLine && firstLine.length < 100) {
|
||||
return {
|
||||
icon: Wrench,
|
||||
title: firstLine.replace(/^(Error |Tool |Executing |Result: )/i, '').trim()
|
||||
};
|
||||
}
|
||||
|
||||
return { icon: Wrench, title: 'Tool Result' };
|
||||
}
|
||||
|
||||
return { icon: Wrench, title: 'Tool' };
|
||||
};
|
||||
|
||||
// Special rendering for tool messages
|
||||
if (message.role === 'tool') {
|
||||
const content = getContent();
|
||||
const toolInfo = getToolInfo();
|
||||
const IconComponent = toolInfo.icon;
|
||||
|
||||
// Get tool call arguments for special rendering
|
||||
// Get tool call arguments
|
||||
let toolArgs: Record<string, unknown> = {};
|
||||
let toolName = '';
|
||||
if (toolCall?.type === 'function') {
|
||||
@@ -214,101 +65,82 @@ export const AIMessageItem = memo(({
|
||||
}
|
||||
}
|
||||
|
||||
// Special rendering for tools
|
||||
const renderSpecialContent = () => {
|
||||
if (toolName === 'text_editor_write' && toolArgs.file_text) {
|
||||
return (
|
||||
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
|
||||
<div className="whitespace-pre-wrap break-words font-mono">
|
||||
{toolArgs.file_text as string}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (toolName === 'text_editor_str_replace' && toolArgs.old_str && toolArgs.new_str) {
|
||||
const oldLines = (toolArgs.old_str as string).split('\n');
|
||||
const newLines = (toolArgs.new_str as string).split('\n');
|
||||
|
||||
return (
|
||||
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs font-mono">
|
||||
<div className="space-y-1">
|
||||
{/* Old content (removed) */}
|
||||
<div className="space-y-0">
|
||||
{oldLines.map((line, index) => (
|
||||
<div key={`old-${index}`} className="flex">
|
||||
<span className="text-red-500 select-none mr-2">-</span>
|
||||
<span className="bg-red-50 dark:bg-red-950/30 text-red-700 dark:text-red-300 flex-1 whitespace-pre-wrap break-words">
|
||||
{line}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* New content (added) */}
|
||||
<div className="space-y-0">
|
||||
{newLines.map((line, index) => (
|
||||
<div key={`new-${index}`} className="flex">
|
||||
<span className="text-green-500 select-none mr-2">+</span>
|
||||
<span className="bg-green-50 dark:bg-green-950/30 text-green-700 dark:text-green-300 flex-1 whitespace-pre-wrap break-words">
|
||||
{line}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Default rendering for other tools
|
||||
return (
|
||||
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
|
||||
<div className="whitespace-pre-wrap break-words font-mono">
|
||||
{content}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// Regular tool message rendering
|
||||
return (
|
||||
<div className="-mt-2"> {/* -mt-2 to make it snug with the previous assistant message */}
|
||||
<button
|
||||
onClick={() => setIsToolExpanded(!isToolExpanded)}
|
||||
className={cn(
|
||||
"w-full flex items-center gap-2 px-2 py-1 text-xs",
|
||||
"hover:bg-muted/30 rounded transition-colors duration-200"
|
||||
)}
|
||||
>
|
||||
<IconComponent className="h-3 w-3 text-muted-foreground flex-shrink-0" />
|
||||
<span className="text-muted-foreground font-medium truncate flex-1 text-left">
|
||||
{toolInfo.title}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{isToolExpanded && renderSpecialContent()}
|
||||
</div>
|
||||
<ToolCallDisplay
|
||||
toolName={toolName}
|
||||
toolArgs={toolArgs}
|
||||
state="completed"
|
||||
result={content}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Regular rendering for non-tool messages
|
||||
if (message.role === 'user') {
|
||||
// User messages: right-aligned bubble without avatar/name
|
||||
// Extract text and image parts from message content
|
||||
const contentArray = Array.isArray(message.content) ? message.content : null;
|
||||
const textParts = contentArray
|
||||
? contentArray.filter(part => part.type === 'text') as OpenAI.Chat.Completions.ChatCompletionContentPartText[]
|
||||
: [];
|
||||
const userContent = typeof message.content === 'string'
|
||||
? message.content
|
||||
: Array.isArray(message.content)
|
||||
? message.content.filter(part => part.type === 'text') as OpenAI.Chat.Completions.ChatCompletionContentPartText[]
|
||||
: textParts.length > 0
|
||||
? textParts.map(part => part.text).join('\n')
|
||||
: '';
|
||||
|
||||
// Extract image URLs from content array
|
||||
const imageUrls = contentArray
|
||||
? contentArray
|
||||
.filter(part => part.type === 'image_url')
|
||||
.map(part => (part as OpenAI.Chat.Completions.ChatCompletionContentPartImage).image_url.url)
|
||||
: [];
|
||||
|
||||
return (
|
||||
<div className="flex justify-end py-6">
|
||||
<div className="max-w-[80%] bg-secondary rounded-2xl rounded-br-md px-4 py-3">
|
||||
<div className="text-sm break-words">
|
||||
<UserMessage content={userContent} />
|
||||
<>
|
||||
<div className="flex justify-end py-6">
|
||||
<div className="max-w-[80%] bg-secondary rounded-2xl rounded-br-md px-4 py-3">
|
||||
<div className="text-sm break-words space-y-2">
|
||||
{/* Render text content and attachments first */}
|
||||
{userContent && <UserMessage content={userContent} />}
|
||||
{/* Render images after text and attachments */}
|
||||
{imageUrls.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
{imageUrls.map((url, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="rounded-lg overflow-hidden border border-border cursor-pointer hover:opacity-90 transition-opacity"
|
||||
onClick={() => setExpandedImageUrl(url)}
|
||||
>
|
||||
<img
|
||||
src={url}
|
||||
alt={`User uploaded image ${index + 1}`}
|
||||
className="max-w-full h-auto max-h-96 object-contain"
|
||||
loading="lazy"
|
||||
onError={(e) => {
|
||||
// Fallback if image fails to load
|
||||
const target = e.target as HTMLImageElement;
|
||||
target.style.display = 'none';
|
||||
const fallback = document.createElement('div');
|
||||
fallback.className = 'p-2 text-xs text-muted-foreground bg-muted rounded';
|
||||
fallback.textContent = `Image failed to load: ${url}`;
|
||||
target.parentElement?.appendChild(fallback);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Image expansion lightbox */}
|
||||
<ImageLightbox
|
||||
imageUrl={expandedImageUrl}
|
||||
onClose={() => setExpandedImageUrl(null)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -322,7 +154,7 @@ export const AIMessageItem = memo(({
|
||||
}
|
||||
|
||||
// Assistant messages: left-aligned without avatar/name
|
||||
return (
|
||||
const assistantContent = (
|
||||
<div className="flex">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm space-y-3">
|
||||
@@ -380,6 +212,18 @@ export const AIMessageItem = memo(({
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{assistantContent}
|
||||
|
||||
{/* Image expansion lightbox */}
|
||||
<ImageLightbox
|
||||
imageUrl={expandedImageUrl}
|
||||
onClose={() => setExpandedImageUrl(null)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
AIMessageItem.displayName = 'AIMessageItem';
|
||||
@@ -125,6 +125,7 @@ describe('AISettingsProvider', () => {
|
||||
providers: [
|
||||
{
|
||||
id: 'openrouter',
|
||||
name: 'OpenRouter',
|
||||
baseURL: 'https://openrouter.ai/api/v1',
|
||||
apiKey: 'test-key'
|
||||
}
|
||||
@@ -173,6 +174,7 @@ describe('AISettingsProvider', () => {
|
||||
providers: [
|
||||
{
|
||||
id: 'test-provider',
|
||||
name: 'Test Provider',
|
||||
baseURL: 'https://api.test.com/v1',
|
||||
apiKey: 'test-key'
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { ReactNode, useState, useEffect } from 'react';
|
||||
import { AISettingsContext, type AISettings, type AIProvider, type AISettingsContextType } from '@/contexts/AISettingsContext';
|
||||
import { AISettingsContext, type AISettings, type AIProvider, type MCPServer, type AISettingsContextType } from '@/contexts/AISettingsContext';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { readAISettings, writeAISettings } from '@/lib/configUtils';
|
||||
@@ -12,6 +12,7 @@ interface AISettingsProviderProps {
|
||||
const DEFAULT_SETTINGS: AISettings = {
|
||||
providers: [],
|
||||
recentlyUsedModels: [],
|
||||
mcpServers: {},
|
||||
};
|
||||
|
||||
export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
@@ -128,6 +129,27 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
});
|
||||
};
|
||||
|
||||
const setMCPServer = (name: string, server: MCPServer) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
mcpServers: {
|
||||
...(prev.mcpServers || {}),
|
||||
[name]: server,
|
||||
},
|
||||
}));
|
||||
};
|
||||
|
||||
const removeMCPServer = (name: string) => {
|
||||
setSettings(prev => {
|
||||
const newMCPServers = { ...(prev.mcpServers || {}) };
|
||||
delete newMCPServers[name];
|
||||
return {
|
||||
...prev,
|
||||
mcpServers: newMCPServers,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const isConfigured = settings.providers.length > 0;
|
||||
|
||||
const contextValue: AISettingsContextType = {
|
||||
@@ -137,6 +159,8 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
removeProvider,
|
||||
setProviders,
|
||||
addRecentlyUsedModel,
|
||||
setMCPServer,
|
||||
removeMCPServer,
|
||||
isConfigured,
|
||||
};
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { useAICredits } from '@/hooks/useAICredits';
|
||||
import { getShakespeareProvider } from '@/lib/aiProviderPresets';
|
||||
import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets';
|
||||
|
||||
interface Act1DialogProps {
|
||||
open: boolean;
|
||||
@@ -14,6 +14,15 @@ interface Act1DialogProps {
|
||||
|
||||
type DialogStep = 'welcome' | 'migration' | 'credits' | 'conclusion';
|
||||
|
||||
// Helper function to get the Shakespeare provider preset
|
||||
function getShakespeareProvider(): PresetProvider {
|
||||
const shakespeare = AI_PROVIDER_PRESETS.find(preset => preset.id === "shakespeare");
|
||||
if (!shakespeare) {
|
||||
throw new Error("Shakespeare provider preset not found");
|
||||
}
|
||||
return shakespeare;
|
||||
}
|
||||
|
||||
export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) {
|
||||
const [step, setStep] = useState<DialogStep>('welcome');
|
||||
const { data: creditsData } = useAICredits(getShakespeareProvider());
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
DropdownMenu,
|
||||
@@ -13,10 +14,12 @@ import {
|
||||
History,
|
||||
Folder,
|
||||
Rocket,
|
||||
Copy,
|
||||
} from 'lucide-react';
|
||||
import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog';
|
||||
import { GitDialog } from '@/components/GitDialog';
|
||||
import { DeployDialog } from '@/components/DeployDialog';
|
||||
import { DuplicateProjectDialog } from '@/components/DuplicateProjectDialog';
|
||||
|
||||
interface ActionsMenuProps {
|
||||
projectId: string;
|
||||
@@ -39,9 +42,11 @@ export function ActionsMenu({
|
||||
disabled = false,
|
||||
onFirstInteraction: _onFirstInteraction,
|
||||
}: ActionsMenuProps) {
|
||||
const { t } = useTranslation();
|
||||
const [gitHistoryOpen, setGitHistoryOpen] = useState(false);
|
||||
const [gitDialogOpen, setGitDialogOpen] = useState(false);
|
||||
const [deployDialogOpen, setDeployDialogOpen] = useState(false);
|
||||
const [duplicateDialogOpen, setDuplicateDialogOpen] = useState(false);
|
||||
|
||||
const isAnyLoading = isLoading || isBuildLoading;
|
||||
|
||||
@@ -98,6 +103,15 @@ export function ActionsMenu({
|
||||
Deploy
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={() => setDuplicateDialogOpen(true)}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
<Copy className="h-4 w-4" />
|
||||
{t('duplicateProject')}
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={onProjectDetails}
|
||||
disabled={isAnyLoading}
|
||||
@@ -131,6 +145,13 @@ export function ActionsMenu({
|
||||
onOpenChange={setDeployDialogOpen}
|
||||
/>
|
||||
|
||||
<DuplicateProjectDialog
|
||||
projectId={projectId}
|
||||
projectName={projectName}
|
||||
open={duplicateDialogOpen}
|
||||
onOpenChange={setDuplicateDialogOpen}
|
||||
/>
|
||||
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
describe('AddProviderDialog', () => {
|
||||
const mockProvider: AIProvider = {
|
||||
id: 'test-provider',
|
||||
name: 'Test Provider',
|
||||
baseURL: 'https://api.test.com/v1',
|
||||
apiKey: 'sk-test-key-123',
|
||||
};
|
||||
@@ -92,6 +93,7 @@ describe('AddProviderDialog', () => {
|
||||
// Use a provider that exists in presets
|
||||
const openrouterProvider: AIProvider = {
|
||||
id: 'openrouter',
|
||||
name: 'OpenRouter',
|
||||
baseURL: 'https://openrouter.ai/api/v1',
|
||||
apiKey: 'sk-test-123',
|
||||
};
|
||||
@@ -114,6 +116,7 @@ describe('AddProviderDialog', () => {
|
||||
const onOpenChange = vi.fn();
|
||||
const customProvider: AIProvider = {
|
||||
id: 'my-custom-provider',
|
||||
name: 'My Custom Provider',
|
||||
baseURL: 'https://api.custom.com/v1',
|
||||
};
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import { Button } from '@/components/ui/button';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
interface AddProviderDialogProps {
|
||||
@@ -156,7 +157,11 @@ export function AddProviderDialog({ open, onOpenChange, provider }: AddProviderD
|
||||
// New provider
|
||||
<div className="space-y-6">
|
||||
<div className="mx-auto w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center">
|
||||
<Sparkles className="h-8 w-8 text-primary" />
|
||||
<ExternalFavicon
|
||||
url={provider.baseURL}
|
||||
size={32}
|
||||
fallback={<Sparkles className="h-8 w-8 text-primary" />}
|
||||
/>
|
||||
</div>
|
||||
<div className="text-center space-y-2">
|
||||
<h2 className="text-2xl font-bold">{providerName}</h2>
|
||||
|
||||
@@ -99,7 +99,7 @@ export function AppLayout({
|
||||
onClick={() => setIsSidebarVisible(false)}
|
||||
/>
|
||||
{/* Sidebar - positioned above the backdrop */}
|
||||
<div className="relative left-0 top-0 h-full w-80 max-w-[80vw] bg-background border-r shadow-lg z-10">
|
||||
<div className="relative left-0 top-0 h-full w-72 max-w-[80vw] bg-background border-r shadow-lg z-10">
|
||||
<ProjectSidebar
|
||||
selectedProject={selectedProject}
|
||||
onSelectProject={(project) => {
|
||||
@@ -123,7 +123,7 @@ export function AppLayout({
|
||||
<div className="min-h-screen flex bg-background">
|
||||
{/* Fixed Sidebar - show if showSidebar is true and sidebar is visible */}
|
||||
{showSidebar && isSidebarVisible && (
|
||||
<div className="w-80 border-r bg-sidebar transition-all duration-300">
|
||||
<div className="w-72 border-r bg-sidebar transition-all duration-300">
|
||||
<ProjectSidebar
|
||||
selectedProject={selectedProject}
|
||||
onSelectProject={handleProjectSelect}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { z } from 'zod';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { AppContext, type AppConfig, type AppContextType, type Theme, type RelayMetadata } from '@/contexts/AppContext';
|
||||
import i18n from '@/lib/i18n';
|
||||
import { expandTildePath, normalizeToForwardSlashes } from '@/lib/pathUtils';
|
||||
|
||||
interface AppProviderProps {
|
||||
children: ReactNode;
|
||||
@@ -22,11 +23,18 @@ const RelayMetadataSchema = z.object({
|
||||
updatedAt: z.number(),
|
||||
}) satisfies z.ZodType<RelayMetadata>;
|
||||
|
||||
// Zod schema for ProjectTemplate
|
||||
const ProjectTemplateSchema = z.object({
|
||||
name: z.string().min(1),
|
||||
description: z.string().min(1),
|
||||
url: z.string().url(),
|
||||
});
|
||||
|
||||
// Zod schema for AppConfig validation
|
||||
const AppConfigSchema = z.object({
|
||||
theme: z.enum(['dark', 'light', 'system']),
|
||||
relayMetadata: RelayMetadataSchema,
|
||||
projectTemplate: z.string().url(),
|
||||
templates: z.array(ProjectTemplateSchema),
|
||||
esmUrl: z.string().url(),
|
||||
corsProxy: z.string().url(),
|
||||
faviconUrl: z.string().url(),
|
||||
@@ -39,8 +47,10 @@ const AppConfigSchema = z.object({
|
||||
fsPathConfig: z.string().min(1),
|
||||
fsPathTmp: z.string().min(1),
|
||||
fsPathPlugins: z.string().min(1),
|
||||
fsPathTemplates: z.string().min(1),
|
||||
sentryDsn: z.string(),
|
||||
sentryEnabled: z.boolean(),
|
||||
systemPrompt: z.string(),
|
||||
}) satisfies z.ZodType<AppConfig>;
|
||||
|
||||
export function AppProvider(props: AppProviderProps) {
|
||||
@@ -76,9 +86,11 @@ export function AppProvider(props: AppProviderProps) {
|
||||
config.fsPathProjects = expandPath(config.fsPathProjects);
|
||||
config.fsPathTmp = expandPath(config.fsPathTmp);
|
||||
config.fsPathPlugins = expandPath(config.fsPathPlugins);
|
||||
config.fsPathTemplates = expandPath(config.fsPathTemplates);
|
||||
|
||||
const appContextValue: AppContextType = {
|
||||
config,
|
||||
defaultConfig,
|
||||
updateConfig,
|
||||
};
|
||||
|
||||
@@ -145,16 +157,16 @@ function useApplyLanguage(language?: string): void {
|
||||
}, [language]);
|
||||
}
|
||||
|
||||
/** Expand FS paths with the user's home directory, if available. */
|
||||
/** Expand FS paths with the user's home directory, if available.
|
||||
* Also normalizes to forward slashes for cross-platform consistency.
|
||||
*/
|
||||
function expandPath(path: string): string {
|
||||
const homedir = window.electron?.homedir;
|
||||
if (!homedir) {
|
||||
return path;
|
||||
} else if (path.startsWith('~/')) {
|
||||
return homedir + path.slice(1);
|
||||
} else if (path === '~') {
|
||||
return homedir;
|
||||
} else {
|
||||
return path;
|
||||
}
|
||||
// Expand tilde and normalize to forward slashes for consistency
|
||||
// This ensures paths work correctly on Windows where homedir uses backslashes
|
||||
const expanded = expandTildePath(path, homedir);
|
||||
return normalizeToForwardSlashes(expanded);
|
||||
}
|
||||
@@ -17,6 +17,7 @@ global.fetch = vi.fn();
|
||||
|
||||
const mockProvider = {
|
||||
id: 'test-provider',
|
||||
name: 'Test Provider',
|
||||
baseURL: 'https://api.test.com/v1',
|
||||
apiKey: 'test-key',
|
||||
};
|
||||
|
||||
@@ -9,6 +9,7 @@ global.fetch = vi.fn();
|
||||
|
||||
const mockProvider: AIProvider = {
|
||||
id: 'test-provider',
|
||||
name: 'Test Provider',
|
||||
baseURL: 'https://api.test.com/v1',
|
||||
apiKey: 'test-key',
|
||||
nostr: false,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import QRCode from 'qrcode';
|
||||
import { CreditCard, Zap, ExternalLink, RefreshCw, Check, X, Clock, AlertCircle, Copy, RotateCcw, ArrowLeft, Gift, Plus, History, DollarSign, Printer, Download } from 'lucide-react';
|
||||
@@ -85,17 +85,33 @@ const PRESET_AMOUNTS = [5, 10, 25, 50, 100];
|
||||
interface LightningPaymentProps {
|
||||
invoice: string;
|
||||
amount: number;
|
||||
paymentId: string;
|
||||
provider: AIProvider;
|
||||
onClose: () => void;
|
||||
onPaymentCompleted: () => void;
|
||||
}
|
||||
|
||||
function LightningPayment({ invoice, amount, onClose }: LightningPaymentProps) {
|
||||
function LightningPayment({ invoice, amount, paymentId, provider, onClose, onPaymentCompleted }: LightningPaymentProps) {
|
||||
const { t } = useTranslation();
|
||||
const { user } = useCurrentUser();
|
||||
const { config } = useAppContext();
|
||||
const queryClient = useQueryClient();
|
||||
const [qrDataUrl, setQrDataUrl] = useState<string>('');
|
||||
const [isWebLNAvailable, setIsWebLNAvailable] = useState(false);
|
||||
const [isPayingWithWebLN, setIsPayingWithWebLN] = useState(false);
|
||||
const [showCopiedTooltip, setShowCopiedTooltip] = useState(false);
|
||||
const [paymentCompleted, setPaymentCompleted] = useState(false);
|
||||
const { toast } = useToast();
|
||||
|
||||
const formatCurrency = useCallback((amount: number) => {
|
||||
return new Intl.NumberFormat('en-US', {
|
||||
style: 'currency',
|
||||
currency: 'USD',
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
}).format(amount);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
// Generate QR code
|
||||
QRCode.toDataURL(invoice, {
|
||||
@@ -113,6 +129,98 @@ function LightningPayment({ invoice, amount, onClose }: LightningPaymentProps) {
|
||||
setIsWebLNAvailable(typeof window !== 'undefined' && 'webln' in window);
|
||||
}, [invoice]);
|
||||
|
||||
// Poll payment status
|
||||
useEffect(() => {
|
||||
// Don't poll if payment already completed
|
||||
if (paymentCompleted) return;
|
||||
|
||||
let intervalId: NodeJS.Timeout | null = null;
|
||||
|
||||
const pollPaymentStatus = async () => {
|
||||
// Double-check in case state updated during async operation
|
||||
if (paymentCompleted) return;
|
||||
|
||||
try {
|
||||
const ai = createAIClient(provider, user, config.corsProxy);
|
||||
const payment = await ai.get(`/credits/payments/${paymentId}`) as Payment;
|
||||
|
||||
if (payment.status === 'completed') {
|
||||
// Mark as completed to prevent further polling
|
||||
setPaymentCompleted(true);
|
||||
|
||||
// Clear the interval immediately
|
||||
if (intervalId) {
|
||||
clearInterval(intervalId);
|
||||
intervalId = null;
|
||||
}
|
||||
|
||||
// Update credits balance
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
|
||||
});
|
||||
|
||||
// Update payments list
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
|
||||
});
|
||||
|
||||
// Show toast
|
||||
toast({
|
||||
title: t('paymentCompleted'),
|
||||
description: t('creditsAddedToAccount', { amount: formatCurrency(payment.amount) }),
|
||||
});
|
||||
|
||||
// Close dialog immediately
|
||||
onPaymentCompleted();
|
||||
} else if (payment.status === 'failed') {
|
||||
// Mark as completed to prevent further polling
|
||||
setPaymentCompleted(true);
|
||||
|
||||
// Clear the interval immediately
|
||||
if (intervalId) {
|
||||
clearInterval(intervalId);
|
||||
intervalId = null;
|
||||
}
|
||||
|
||||
toast({
|
||||
title: t('paymentFailed'),
|
||||
description: t('paymentFailed'),
|
||||
variant: 'destructive',
|
||||
});
|
||||
} else if (payment.status === 'expired') {
|
||||
// Mark as completed to prevent further polling
|
||||
setPaymentCompleted(true);
|
||||
|
||||
// Clear the interval immediately
|
||||
if (intervalId) {
|
||||
clearInterval(intervalId);
|
||||
intervalId = null;
|
||||
}
|
||||
|
||||
toast({
|
||||
title: t('paymentExpired'),
|
||||
description: t('paymentExpiredMessage'),
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to poll payment status:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// Poll immediately on mount
|
||||
pollPaymentStatus();
|
||||
|
||||
// Then poll every 3 seconds
|
||||
intervalId = setInterval(pollPaymentStatus, 3000);
|
||||
|
||||
return () => {
|
||||
if (intervalId) {
|
||||
clearInterval(intervalId);
|
||||
}
|
||||
};
|
||||
}, [paymentId, provider, user, config.corsProxy, queryClient, toast, t, onPaymentCompleted, formatCurrency, paymentCompleted]);
|
||||
|
||||
const handleWebLNPay = async () => {
|
||||
if (!window.webln) return;
|
||||
|
||||
@@ -145,15 +253,6 @@ function LightningPayment({ invoice, amount, onClose }: LightningPaymentProps) {
|
||||
setTimeout(() => setShowCopiedTooltip(false), 2000);
|
||||
};
|
||||
|
||||
const formatCurrency = (amount: number) => {
|
||||
return new Intl.NumberFormat('en-US', {
|
||||
style: 'currency',
|
||||
currency: 'USD',
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
}).format(amount);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="text-center">
|
||||
@@ -223,6 +322,7 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
|
||||
const [amount, setAmount] = useState<number>(10);
|
||||
const [paymentMethod, setPaymentMethod] = useState<'stripe' | 'lightning'>('stripe');
|
||||
const [lightningInvoice, setLightningInvoice] = useState<string | null>(null);
|
||||
const [lightningPaymentId, setLightningPaymentId] = useState<string | null>(null);
|
||||
const [refreshingPayments, setRefreshingPayments] = useState<Set<string>>(new Set());
|
||||
const [giftcardAmount, setGiftcardAmount] = useState<number>(10);
|
||||
const [giftcardQuantity, setGiftcardQuantity] = useState<number>(1);
|
||||
@@ -301,6 +401,7 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
|
||||
} else if (payment.method === 'lightning') {
|
||||
// Show Lightning payment interface
|
||||
setLightningInvoice(payment.url);
|
||||
setLightningPaymentId(payment.id);
|
||||
}
|
||||
|
||||
// Refresh payments list
|
||||
@@ -486,6 +587,7 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
|
||||
} else if (paymentPreview.method === 'lightning') {
|
||||
// Show Lightning payment interface
|
||||
setLightningInvoice(paymentPreview.url);
|
||||
setLightningPaymentId(paymentPreview.id);
|
||||
}
|
||||
|
||||
// Refresh payments list
|
||||
@@ -882,27 +984,37 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
|
||||
</DialogHeader>
|
||||
|
||||
{/* Lightning Payment Interface */}
|
||||
{lightningInvoice ? (
|
||||
{lightningInvoice && lightningPaymentId ? (
|
||||
<div className="flex-1 overflow-y-auto px-1 -mx-1">
|
||||
<LightningPayment
|
||||
invoice={lightningInvoice}
|
||||
amount={amount}
|
||||
onClose={() => setLightningInvoice(null)}
|
||||
paymentId={lightningPaymentId}
|
||||
provider={provider}
|
||||
onClose={() => {
|
||||
setLightningInvoice(null);
|
||||
setLightningPaymentId(null);
|
||||
}}
|
||||
onPaymentCompleted={() => {
|
||||
// Close the lightning payment view immediately
|
||||
setLightningInvoice(null);
|
||||
setLightningPaymentId(null);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex-1 overflow-y-auto px-1 -mx-1">
|
||||
<Accordion type="multiple" defaultValue={["add"]} className="w-full">
|
||||
<Accordion type="multiple" defaultValue={["add"]} className="w-full space-y-2">
|
||||
{/* Buy Credits Accordion */}
|
||||
<AccordionItem value="add">
|
||||
<AccordionTrigger className="hover:no-underline">
|
||||
<AccordionTrigger className="hover:no-underline px-4 py-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<DollarSign className="h-4 w-4" />
|
||||
<DollarSign className="h-4 w-4 text-muted-foreground" />
|
||||
{t('buyCredits')}
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent>
|
||||
<div className="space-y-3 pt-2">
|
||||
<AccordionContent className="px-4">
|
||||
<div className="space-y-3 pt-2 pb-3">
|
||||
<div className="space-y-3">
|
||||
<Label htmlFor="amount" className="text-sm font-medium">{t('amountUSD')}</Label>
|
||||
<div className="space-y-3">
|
||||
@@ -986,14 +1098,14 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
|
||||
|
||||
{/* Transaction History Accordion */}
|
||||
<AccordionItem value="history">
|
||||
<AccordionTrigger className="hover:no-underline">
|
||||
<AccordionTrigger className="hover:no-underline px-4 py-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<History className="h-4 w-4" />
|
||||
<History className="h-4 w-4 text-muted-foreground" />
|
||||
{t('recentTransactions')}
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent>
|
||||
<div className="pt-2">
|
||||
<AccordionContent className="px-4">
|
||||
<div className="pt-2 pb-3">
|
||||
{isLoadingPayments ? (
|
||||
<div className="p-3 border rounded-lg space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
@@ -1054,6 +1166,7 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
|
||||
onClick={() => {
|
||||
if (payment.method === 'lightning') {
|
||||
setLightningInvoice(payment.url);
|
||||
setLightningPaymentId(payment.id);
|
||||
} else {
|
||||
window.open(payment.url, '_blank');
|
||||
}
|
||||
@@ -1077,14 +1190,14 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
|
||||
|
||||
{/* Redeem Gift Card Accordion */}
|
||||
<AccordionItem value="redeem">
|
||||
<AccordionTrigger className="hover:no-underline">
|
||||
<AccordionTrigger className="hover:no-underline px-4 py-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Plus className="h-4 w-4" />
|
||||
<Plus className="h-4 w-4 text-muted-foreground" />
|
||||
{t('redeemGiftCard')}
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent>
|
||||
<div className="space-y-3 pt-2">
|
||||
<AccordionContent className="px-4">
|
||||
<div className="space-y-3 pt-2 pb-3">
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="redeem-code"
|
||||
@@ -1109,14 +1222,14 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
|
||||
|
||||
{/* Create Gift Card Accordion */}
|
||||
<AccordionItem value="create">
|
||||
<AccordionTrigger className="hover:no-underline">
|
||||
<AccordionTrigger className="hover:no-underline px-4 py-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Gift className="h-4 w-4" />
|
||||
<Gift className="h-4 w-4 text-muted-foreground" />
|
||||
{t('createGiftCard')}
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent>
|
||||
<div className="space-y-3 pt-2">
|
||||
<AccordionContent className="px-4">
|
||||
<div className="space-y-3 pt-2 pb-3">
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="giftcard-amount" className="text-xs text-muted-foreground">{t('amountUSD')}</Label>
|
||||
@@ -1172,15 +1285,15 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
|
||||
</AccordionItem>
|
||||
|
||||
{/* Your Gift Cards Accordion */}
|
||||
<AccordionItem value="list" className="border-b-0">
|
||||
<AccordionTrigger className="hover:no-underline">
|
||||
<AccordionItem value="list">
|
||||
<AccordionTrigger className="hover:no-underline px-4 py-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<CreditCard className="h-4 w-4" />
|
||||
<CreditCard className="h-4 w-4 text-muted-foreground" />
|
||||
{t('yourGiftCards')}
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="pb-0">
|
||||
<div className="pt-2 space-y-3">
|
||||
<AccordionContent className="px-4">
|
||||
<div className="pt-2 pb-3 space-y-3">
|
||||
{giftcards && giftcards.filter(gc => !gc.redeemed).length > 0 && (
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<Button
|
||||
|
||||
@@ -27,13 +27,15 @@ import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { ShakespeareAdapter, NetlifyAdapter, VercelAdapter, NsiteAdapter, DeployAdapter } from '@/lib/deploy';
|
||||
import { ShakespeareAdapter, NetlifyAdapter, VercelAdapter, NsiteAdapter, CloudflareAdapter, DenoDeployAdapter, DeployAdapter } from '@/lib/deploy';
|
||||
import { Link } from 'react-router-dom';
|
||||
import type { DeployProvider, ShakespeareDeployProvider, NetlifyProvider, VercelProvider } from '@/contexts/DeploySettingsContext';
|
||||
import type { DeployProvider, ShakespeareDeployProvider, NetlifyProvider, VercelProvider, CloudflareProvider, DenoDeployProvider } from '@/contexts/DeploySettingsContext';
|
||||
import { ShakespeareDeployForm } from '@/components/deploy/ShakespeareDeployForm';
|
||||
import { NetlifyDeployForm } from '@/components/deploy/NetlifyDeployForm';
|
||||
import { VercelDeployForm } from '@/components/deploy/VercelDeployForm';
|
||||
import { NsiteDeployForm } from '@/components/deploy/NsiteDeployForm';
|
||||
import { CloudflareDeployForm } from '@/components/deploy/CloudflareDeployForm';
|
||||
import { DenoDeployForm } from '@/components/deploy/DenoDeployForm';
|
||||
|
||||
/**
|
||||
* Helper function to get provider URL for favicon
|
||||
@@ -58,6 +60,18 @@ function getProviderUrl(provider: DeployProvider): string | null {
|
||||
}
|
||||
return 'https://vercel.com';
|
||||
|
||||
case 'cloudflare':
|
||||
if (provider.baseURL) {
|
||||
return provider.baseURL;
|
||||
}
|
||||
return 'https://cloudflare.com';
|
||||
|
||||
case 'deno':
|
||||
if (provider.baseURL) {
|
||||
return provider.baseURL;
|
||||
}
|
||||
return 'https://deno.com';
|
||||
|
||||
case 'nsite':
|
||||
return null;
|
||||
|
||||
@@ -110,6 +124,14 @@ interface VercelFormData {
|
||||
teamId: string;
|
||||
}
|
||||
|
||||
interface CloudflareFormData {
|
||||
projectName: string;
|
||||
}
|
||||
|
||||
interface DenoDeployFormData {
|
||||
projectName: string;
|
||||
}
|
||||
|
||||
export function DeployDialog({ projectId, projectName, open, onOpenChange }: DeployDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const { settings } = useDeploySettings();
|
||||
@@ -124,6 +146,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
const [isDeploying, setIsDeploying] = useState(false);
|
||||
const [deployResult, setDeployResult] = useState<{ url: string } | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isShakespeareFormValid, setIsShakespeareFormValid] = useState(true);
|
||||
|
||||
// Provider-specific form data
|
||||
const [shakespeareForm, setShakespeareForm] = useState<ShakespeareFormData>({
|
||||
@@ -140,6 +163,12 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
projectName: projectName || projectId,
|
||||
teamId: '',
|
||||
});
|
||||
const [cloudflareForm, setCloudflareForm] = useState<CloudflareFormData>({
|
||||
projectName: projectName || projectId,
|
||||
});
|
||||
const [denoDeployForm, setDenoDeployForm] = useState<DenoDeployFormData>({
|
||||
projectName: projectName || projectId,
|
||||
});
|
||||
|
||||
// Load project settings when dialog opens
|
||||
useEffect(() => {
|
||||
@@ -229,6 +258,42 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
projectName: vercelForm.projectName || undefined,
|
||||
corsProxy: vercelProvider.proxy ? config.corsProxy : undefined,
|
||||
});
|
||||
} else if (selectedProvider.type === 'cloudflare') {
|
||||
const cloudflareProvider = selectedProvider as CloudflareProvider;
|
||||
if (!cloudflareProvider.apiKey) {
|
||||
throw new Error('Cloudflare API key is required');
|
||||
}
|
||||
if (!cloudflareProvider.accountId) {
|
||||
throw new Error('Cloudflare account ID is required');
|
||||
}
|
||||
|
||||
adapter = new CloudflareAdapter({
|
||||
fs,
|
||||
apiKey: cloudflareProvider.apiKey,
|
||||
accountId: cloudflareProvider.accountId,
|
||||
baseURL: cloudflareProvider.baseURL,
|
||||
baseDomain: cloudflareProvider.baseDomain,
|
||||
projectName: cloudflareForm.projectName || undefined,
|
||||
corsProxy: cloudflareProvider.proxy ? config.corsProxy : undefined,
|
||||
});
|
||||
} else if (selectedProvider.type === 'deno') {
|
||||
const denoProvider = selectedProvider as DenoDeployProvider;
|
||||
if (!denoProvider.apiKey) {
|
||||
throw new Error('Deno Deploy access token is required');
|
||||
}
|
||||
if (!denoProvider.organizationId) {
|
||||
throw new Error('Deno Deploy organization ID is required');
|
||||
}
|
||||
|
||||
adapter = new DenoDeployAdapter({
|
||||
fs,
|
||||
apiKey: denoProvider.apiKey,
|
||||
organizationId: denoProvider.organizationId,
|
||||
baseDomain: denoProvider.baseDomain,
|
||||
baseURL: denoProvider.baseURL,
|
||||
projectName: denoDeployForm.projectName || undefined,
|
||||
corsProxy: denoProvider.proxy ? config.corsProxy : undefined,
|
||||
});
|
||||
} else {
|
||||
throw new Error('Unknown provider type');
|
||||
}
|
||||
@@ -242,6 +307,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
if (selectedProvider.type === 'shakespeare') {
|
||||
await updateProjectSettings(selectedProviderId, {
|
||||
type: 'shakespeare',
|
||||
url: result.url,
|
||||
data: {
|
||||
subdomain: shakespeareForm.subdomain || undefined,
|
||||
},
|
||||
@@ -249,6 +315,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
} else if (selectedProvider.type === 'nsite') {
|
||||
await updateProjectSettings(selectedProviderId, {
|
||||
type: 'nsite',
|
||||
url: result.url,
|
||||
data: {
|
||||
nsec: nsiteForm.nsec,
|
||||
},
|
||||
@@ -256,6 +323,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
} else if (selectedProvider.type === 'netlify') {
|
||||
await updateProjectSettings(selectedProviderId, {
|
||||
type: 'netlify',
|
||||
url: result.url,
|
||||
data: {
|
||||
siteId: result.metadata?.siteId as string | undefined,
|
||||
},
|
||||
@@ -263,11 +331,28 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
} else if (selectedProvider.type === 'vercel') {
|
||||
await updateProjectSettings(selectedProviderId, {
|
||||
type: 'vercel',
|
||||
url: result.url,
|
||||
data: {
|
||||
teamId: vercelForm.teamId || undefined,
|
||||
projectId: vercelForm.projectName || undefined,
|
||||
},
|
||||
});
|
||||
} else if (selectedProvider.type === 'cloudflare') {
|
||||
await updateProjectSettings(selectedProviderId, {
|
||||
type: 'cloudflare',
|
||||
url: result.url,
|
||||
data: {
|
||||
projectName: cloudflareForm.projectName || undefined,
|
||||
},
|
||||
});
|
||||
} else if (selectedProvider.type === 'deno') {
|
||||
await updateProjectSettings(selectedProviderId, {
|
||||
type: 'deno',
|
||||
url: result.url,
|
||||
data: {
|
||||
projectName: denoDeployForm.projectName || undefined,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
setDeployResult(result);
|
||||
@@ -287,6 +372,8 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
setNsiteForm({ nsec: '' });
|
||||
setNetlifyForm({ siteId: '', siteName: '' });
|
||||
setVercelForm({ projectName: projectName || projectId, teamId: '' });
|
||||
setCloudflareForm({ projectName: projectName || projectId });
|
||||
setDenoDeployForm({ projectName: projectName || projectId });
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
@@ -294,6 +381,10 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
setShakespeareForm({ subdomain });
|
||||
}, []);
|
||||
|
||||
const handleShakespeareValidationChange = useCallback((isValid: boolean) => {
|
||||
setIsShakespeareFormValid(isValid);
|
||||
}, []);
|
||||
|
||||
const handleNsiteNsecChange = useCallback((nsec: string) => {
|
||||
setNsiteForm({ nsec });
|
||||
}, []);
|
||||
@@ -306,17 +397,29 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
setVercelForm({ projectName, teamId });
|
||||
}, []);
|
||||
|
||||
const handleCloudflareProjectChange = useCallback((projectName: string) => {
|
||||
setCloudflareForm({ projectName });
|
||||
}, []);
|
||||
|
||||
const handleDenoDeployProjectChange = useCallback((projectName: string) => {
|
||||
setDenoDeployForm({ projectName });
|
||||
}, []);
|
||||
|
||||
const renderProviderFields = () => {
|
||||
if (!selectedProvider) return null;
|
||||
|
||||
if (selectedProvider.type === 'shakespeare') {
|
||||
const shakespeareProvider = selectedProvider as ShakespeareDeployProvider;
|
||||
const savedConfig = projectSettings.providers[selectedProviderId];
|
||||
const savedSubdomain = savedConfig?.type === 'shakespeare' ? savedConfig.data.subdomain : undefined;
|
||||
|
||||
return (
|
||||
<ShakespeareDeployForm
|
||||
host={shakespeareProvider.host}
|
||||
projectId={projectId}
|
||||
savedSubdomain={savedSubdomain}
|
||||
onSubdomainChange={handleShakespeareSubdomainChange}
|
||||
onValidationChange={handleShakespeareValidationChange}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -367,6 +470,46 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
);
|
||||
}
|
||||
|
||||
if (selectedProvider.type === 'cloudflare') {
|
||||
const cloudflareProvider = selectedProvider as CloudflareProvider;
|
||||
const savedConfig = projectSettings.providers[selectedProviderId];
|
||||
const savedProjectName = savedConfig?.type === 'cloudflare' ? savedConfig.data.projectName : undefined;
|
||||
|
||||
return (
|
||||
<CloudflareDeployForm
|
||||
apiKey={cloudflareProvider.apiKey}
|
||||
accountId={cloudflareProvider.accountId}
|
||||
baseURL={cloudflareProvider.baseURL}
|
||||
baseDomain={cloudflareProvider.baseDomain}
|
||||
projectId={projectId}
|
||||
projectName={projectName}
|
||||
savedProjectName={savedProjectName}
|
||||
onProjectChange={handleCloudflareProjectChange}
|
||||
corsProxy={cloudflareProvider.proxy ? config.corsProxy : undefined}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (selectedProvider.type === 'deno') {
|
||||
const denoProvider = selectedProvider as DenoDeployProvider;
|
||||
const savedConfig = projectSettings.providers[selectedProviderId];
|
||||
const savedProjectName = savedConfig?.type === 'deno' ? savedConfig.data.projectName : undefined;
|
||||
|
||||
return (
|
||||
<DenoDeployForm
|
||||
apiKey={denoProvider.apiKey}
|
||||
organizationId={denoProvider.organizationId}
|
||||
baseURL={denoProvider.baseURL}
|
||||
baseDomain={denoProvider.baseDomain}
|
||||
projectId={projectId}
|
||||
projectName={projectName}
|
||||
savedProjectName={savedProjectName}
|
||||
onProjectChange={handleDenoDeployProjectChange}
|
||||
corsProxy={denoProvider.proxy ? config.corsProxy : undefined}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
@@ -460,6 +603,35 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{selectedProvider && selectedProviderId && (() => {
|
||||
const savedConfig = projectSettings.providers[selectedProviderId];
|
||||
const url = savedConfig?.url;
|
||||
|
||||
if (url) {
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<Label>Last Deployment</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={url}
|
||||
readOnly
|
||||
className="flex-1 text-muted-foreground"
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => window.open(url, '_blank')}
|
||||
title="Visit last deployment"
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
})()}
|
||||
|
||||
{selectedProvider && renderProviderFields()}
|
||||
|
||||
{selectedProvider?.type === 'shakespeare' && !user && (
|
||||
@@ -495,8 +667,11 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
!selectedProvider ||
|
||||
isDeploying ||
|
||||
(selectedProvider.type === 'shakespeare' && !user) ||
|
||||
(selectedProvider.type === 'shakespeare' && !isShakespeareFormValid) ||
|
||||
(selectedProvider.type === 'nsite' && !nsiteForm.nsec) ||
|
||||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName)
|
||||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName) ||
|
||||
(selectedProvider.type === 'cloudflare' && !cloudflareForm.projectName) ||
|
||||
(selectedProvider.type === 'deno' && !denoDeployForm.projectName)
|
||||
}
|
||||
>
|
||||
{isDeploying ? (
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Search, Download, Loader2, Check, Package, LogIn } from 'lucide-react';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { useDiscoverPlugins } from '@/hooks/useDiscoverPlugins';
|
||||
import { usePlugins } from '@/hooks/usePlugins';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
import { Link } from 'react-router-dom';
|
||||
import type { NostrMetadata } from '@nostrify/nostrify';
|
||||
|
||||
interface DiscoverPluginsDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export function DiscoverPluginsDialog({ open, onOpenChange }: DiscoverPluginsDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const { user } = useCurrentUser();
|
||||
const { data: plugins, isLoading } = useDiscoverPlugins();
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
|
||||
// Filter plugins based on search query
|
||||
const filteredPlugins = plugins?.filter((plugin) => {
|
||||
const query = searchQuery.toLowerCase();
|
||||
return (
|
||||
plugin.name.toLowerCase().includes(query) ||
|
||||
plugin.description.toLowerCase().includes(query) ||
|
||||
plugin.id.toLowerCase().includes(query)
|
||||
);
|
||||
});
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-3xl max-h-[80vh] flex flex-col">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Package className="h-5 w-5 text-primary" />
|
||||
{t('discoverPlugins')}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{t('discoverPluginsDescription')}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 flex-1 min-h-0 flex flex-col">
|
||||
{/* Search Input */}
|
||||
<div className="relative flex-shrink-0">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder={t('searchPlugins')}
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Plugins List */}
|
||||
<div className="flex-1 overflow-y-auto space-y-3">
|
||||
{!user && (
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-4">
|
||||
<LogIn className="h-12 w-12 mx-auto text-muted-foreground" />
|
||||
<div className="space-y-2">
|
||||
<h3 className="font-semibold">{t('loginRequired')}</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('loginToDiscoverPlugins')}
|
||||
</p>
|
||||
</div>
|
||||
<Button asChild className="w-full">
|
||||
<Link to="/settings/nostr">
|
||||
{t('goToNostrSettings')}
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{user && isLoading && (
|
||||
<>
|
||||
{[...Array(3)].map((_, i) => (
|
||||
<Card key={i}>
|
||||
<CardContent className="p-4 space-y-3">
|
||||
<div className="flex items-start gap-3">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<Skeleton className="h-5 w-48" />
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
|
||||
{user && !isLoading && filteredPlugins?.length === 0 && (
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-4">
|
||||
<Package className="h-12 w-12 mx-auto text-muted-foreground" />
|
||||
<div className="space-y-2">
|
||||
<h3 className="font-semibold">
|
||||
{searchQuery ? t('noPluginsFound') : t('noPluginsFromNetwork')}
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{searchQuery
|
||||
? t('tryDifferentSearch')
|
||||
: t('noPluginsFromNetworkDescription')
|
||||
}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{user && !isLoading && filteredPlugins?.map((plugin) => (
|
||||
<PluginCard key={`${plugin.author}-${plugin.id}`} plugin={plugin} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
interface PluginCardProps {
|
||||
plugin: {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
cloneUrl?: string;
|
||||
webUrl?: string;
|
||||
author: string;
|
||||
};
|
||||
}
|
||||
|
||||
function PluginCard({ plugin }: PluginCardProps) {
|
||||
const { t } = useTranslation();
|
||||
const { toast } = useToast();
|
||||
const author = useAuthor(plugin.author);
|
||||
const { clonePlugin, plugins: installedPlugins } = usePlugins();
|
||||
const metadata: NostrMetadata | undefined = author.data?.metadata;
|
||||
|
||||
const isInstalled = installedPlugins.includes(plugin.id);
|
||||
const isInstalling = clonePlugin.isPending && clonePlugin.variables?.pluginName === plugin.id;
|
||||
|
||||
const handleInstall = async () => {
|
||||
if (!plugin.cloneUrl) {
|
||||
toast({
|
||||
title: t('noCloneUrl'),
|
||||
description: t('noCloneUrlDescription'),
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await clonePlugin.mutateAsync({
|
||||
gitUrl: plugin.cloneUrl,
|
||||
pluginName: plugin.id,
|
||||
});
|
||||
toast({
|
||||
title: t('pluginInstalled'),
|
||||
description: t('pluginInstalledDescription', { name: plugin.name }),
|
||||
});
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: t('pluginInstallFailed'),
|
||||
description: error instanceof Error ? error.message : String(error),
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const displayName = metadata?.name ?? genUserName(plugin.author);
|
||||
const profileImage = metadata?.picture;
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="p-4 space-y-3">
|
||||
{/* Plugin Header with Author Info */}
|
||||
<div className="flex items-start gap-3">
|
||||
<Avatar className="h-10 w-10">
|
||||
<AvatarImage src={profileImage} alt={displayName} />
|
||||
<AvatarFallback>{displayName.slice(0, 2).toUpperCase()}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<h3 className="font-semibold text-base truncate">{plugin.name}</h3>
|
||||
{isInstalled && (
|
||||
<span className="inline-flex items-center gap-1 px-2 py-0.5 text-xs font-medium bg-green-500/10 text-green-600 dark:text-green-400 rounded-full">
|
||||
<Check className="h-3 w-3" />
|
||||
{t('installed')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('by')} {displayName}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Plugin Description */}
|
||||
{plugin.description && (
|
||||
<p className="text-sm text-muted-foreground line-clamp-2">
|
||||
{plugin.description}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Action Button */}
|
||||
<Button
|
||||
onClick={handleInstall}
|
||||
disabled={isInstalled || isInstalling || !plugin.cloneUrl}
|
||||
className="w-full"
|
||||
size="sm"
|
||||
>
|
||||
{isInstalling ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
{t('installing')}
|
||||
</>
|
||||
) : isInstalled ? (
|
||||
<>
|
||||
<Check className="h-4 w-4 mr-2" />
|
||||
{t('installed')}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Download className="h-4 w-4 mr-2" />
|
||||
{t('install')}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { DuplicateProjectDialog } from './DuplicateProjectDialog';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
|
||||
// Mock the navigate function
|
||||
const mockNavigate = vi.fn();
|
||||
vi.mock('react-router-dom', async () => {
|
||||
const actual = await vi.importActual('react-router-dom');
|
||||
return {
|
||||
...actual,
|
||||
useNavigate: () => mockNavigate,
|
||||
};
|
||||
});
|
||||
|
||||
describe('DuplicateProjectDialog', () => {
|
||||
beforeEach(() => {
|
||||
mockNavigate.mockClear();
|
||||
});
|
||||
|
||||
it('renders dialog when open', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<DuplicateProjectDialog
|
||||
projectId="test-project"
|
||||
projectName="Test Project"
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByRole('dialog')).toBeInTheDocument();
|
||||
expect(screen.getByRole('heading', { name: 'Duplicate Project' })).toBeInTheDocument();
|
||||
expect(screen.getByText('Create a copy of this project with a new name')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not render dialog when closed', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<DuplicateProjectDialog
|
||||
projectId="test-project"
|
||||
projectName="Test Project"
|
||||
open={false}
|
||||
onOpenChange={() => {}}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows default project name with -copy suffix', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<DuplicateProjectDialog
|
||||
projectId="test-project"
|
||||
projectName="Test Project"
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const input = screen.getByLabelText('New Project Name');
|
||||
expect(input).toHaveValue('Test Project-copy');
|
||||
});
|
||||
|
||||
it('allows changing the project name', async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<DuplicateProjectDialog
|
||||
projectId="test-project"
|
||||
projectName="Test Project"
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const input = screen.getByLabelText('New Project Name');
|
||||
await user.clear(input);
|
||||
await user.type(input, 'My New Project');
|
||||
|
||||
expect(input).toHaveValue('My New Project');
|
||||
});
|
||||
|
||||
it('disables duplicate button when name is empty', async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<DuplicateProjectDialog
|
||||
projectId="test-project"
|
||||
projectName="Test Project"
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const input = screen.getByLabelText('New Project Name');
|
||||
const duplicateButton = screen.getByRole('button', { name: /Duplicate Project/i });
|
||||
|
||||
// Clear the input
|
||||
await user.clear(input);
|
||||
|
||||
// Button should be disabled when input is empty
|
||||
expect(duplicateButton).toBeDisabled();
|
||||
});
|
||||
|
||||
it('closes dialog when cancel button is clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onOpenChange = vi.fn();
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<DuplicateProjectDialog
|
||||
projectId="test-project"
|
||||
projectName="Test Project"
|
||||
open={true}
|
||||
onOpenChange={onOpenChange}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const cancelButton = screen.getByRole('button', { name: /Cancel/i });
|
||||
await user.click(cancelButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onOpenChange).toHaveBeenCalledWith(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
|
||||
interface DuplicateProjectDialogProps {
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export function DuplicateProjectDialog({
|
||||
projectId,
|
||||
projectName,
|
||||
open,
|
||||
onOpenChange,
|
||||
}: DuplicateProjectDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const { toast } = useToast();
|
||||
const projectsManager = useProjectsManager();
|
||||
const queryClient = useQueryClient();
|
||||
const [newName, setNewName] = useState(`${projectName}-copy`);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
const handleDuplicate = async () => {
|
||||
if (!newName.trim()) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
const duplicatedProject = await projectsManager.duplicateProject(projectId, newName);
|
||||
|
||||
// Invalidate projects query to refresh the list
|
||||
await queryClient.invalidateQueries({ queryKey: ['projects'] });
|
||||
|
||||
toast({
|
||||
title: t('projectDuplicated'),
|
||||
description: t('projectDuplicatedDescription'),
|
||||
});
|
||||
|
||||
// Close dialog
|
||||
onOpenChange(false);
|
||||
|
||||
// Navigate to the new project
|
||||
navigate(`/project/${duplicatedProject.id}`);
|
||||
} catch (error) {
|
||||
console.error('Failed to duplicate project:', error);
|
||||
toast({
|
||||
title: t('failedToDuplicateProject'),
|
||||
description: error instanceof Error ? error.message : String(error),
|
||||
variant: 'destructive',
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[425px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('duplicateProject')}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{t('duplicateProjectDescription')}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="grid gap-4 py-4">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="new-name">{t('newProjectName')}</Label>
|
||||
<Input
|
||||
id="new-name"
|
||||
value={newName}
|
||||
onChange={(e) => setNewName(e.target.value)}
|
||||
placeholder={`${projectName}-copy`}
|
||||
disabled={isLoading}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && newName.trim()) {
|
||||
handleDuplicate();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
disabled={isLoading}
|
||||
>
|
||||
{t('cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleDuplicate}
|
||||
disabled={isLoading || !newName.trim()}
|
||||
>
|
||||
{isLoading ? t('duplicatingProject') : t('duplicateProject')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -100,11 +100,15 @@ export function ErrorBoundary({
|
||||
const Sentry = getSentryInstance();
|
||||
if (Sentry) {
|
||||
Sentry.captureException(error, {
|
||||
level: 'fatal', // Mark as fatal/unhandled error (skull icon in Sentry UI)
|
||||
contexts: {
|
||||
react: {
|
||||
componentStack: info.componentStack,
|
||||
},
|
||||
},
|
||||
tags: {
|
||||
errorBoundary: 'true', // Tag to easily filter these errors
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { faviconUrl, normalizeUrl } from '@/lib/faviconUrl';
|
||||
import { ReactNode } from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { ReactNode, useMemo } from 'react';
|
||||
|
||||
interface ExternalFaviconProps {
|
||||
/** The URL to fetch the favicon for */
|
||||
@@ -25,14 +26,28 @@ export function ExternalFavicon({
|
||||
}: ExternalFaviconProps) {
|
||||
const { config } = useAppContext();
|
||||
|
||||
// Normalize the URL to ensure it has a protocol
|
||||
const normalizedUrl = normalizeUrl(url);
|
||||
|
||||
// Generate the favicon URL using the configured template
|
||||
const faviconSrc = faviconUrl(config.faviconUrl, normalizedUrl);
|
||||
const faviconSrc = useMemo(() => {
|
||||
try {
|
||||
// Normalize the URL to ensure it has a protocol
|
||||
const normalizedUrl = normalizeUrl(url);
|
||||
return faviconUrl(config.faviconUrl, normalizedUrl);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}, [url, config.faviconUrl]);
|
||||
|
||||
// If faviconSrc is not available, render the fallback directly
|
||||
if (!faviconSrc) {
|
||||
return (
|
||||
<span className={cn('inline-flex items-center justify-center', className)}>
|
||||
<span>{fallback}</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<span className={`inline-flex items-center justify-center ${className}`}>
|
||||
<span className={cn('inline-flex items-center justify-center', className)}>
|
||||
<img
|
||||
src={faviconSrc}
|
||||
alt=""
|
||||
|
||||
@@ -164,6 +164,7 @@ export function GiftCardRedeemDialog({ open, onOpenChange, baseURL, code }: Gift
|
||||
|
||||
const providerConfig = {
|
||||
id: matchingPreset.id,
|
||||
name: matchingPreset.name,
|
||||
baseURL: matchingPreset.baseURL,
|
||||
nostr: matchingPreset.nostr || undefined,
|
||||
};
|
||||
|
||||
@@ -25,6 +25,7 @@ const baseGitStatus = {
|
||||
},
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
remoteBranchExists: false,
|
||||
};
|
||||
|
||||
vi.mock('@/hooks/useGitStatus', () => ({
|
||||
@@ -82,7 +83,16 @@ describe('GitDialog', () => {
|
||||
expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed
|
||||
});
|
||||
|
||||
it('shows sync status', () => {
|
||||
it('shows sync status when branch is published', () => {
|
||||
// Mock git status with published branch
|
||||
mockUseGitStatus.mockReturnValue({
|
||||
data: {
|
||||
...baseGitStatus,
|
||||
remoteBranchExists: true,
|
||||
},
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
@@ -133,7 +143,17 @@ describe('GitDialog', () => {
|
||||
expect(pushButton.closest('button')).not.toBeDisabled();
|
||||
});
|
||||
|
||||
it('disables push button when no commits ahead', () => {
|
||||
it('disables push button when no commits ahead and branch is published', () => {
|
||||
// Mock git status with published branch and no commits ahead
|
||||
mockUseGitStatus.mockReturnValue({
|
||||
data: {
|
||||
...baseGitStatus,
|
||||
ahead: 0,
|
||||
remoteBranchExists: true,
|
||||
},
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
@@ -147,6 +167,38 @@ describe('GitDialog', () => {
|
||||
expect(pushButton.closest('button')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('enables push and disables pull when branch is not published', () => {
|
||||
// Mock git status with unpublished branch (has commits but no remote branch)
|
||||
mockUseGitStatus.mockReturnValue({
|
||||
data: {
|
||||
...baseGitStatus,
|
||||
ahead: 0,
|
||||
remoteBranchExists: false,
|
||||
totalCommits: 5,
|
||||
},
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Sync Status')).toBeInTheDocument();
|
||||
expect(screen.getByText('Branch not published')).toBeInTheDocument();
|
||||
|
||||
const pushButton = screen.getByText('Push');
|
||||
expect(pushButton).toBeInTheDocument();
|
||||
expect(pushButton.closest('button')).not.toBeDisabled();
|
||||
|
||||
const pullButton = screen.getByText('Pull');
|
||||
expect(pullButton).toBeInTheDocument();
|
||||
expect(pullButton.closest('button')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('does not show credentials warning when credentials are configured', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
|
||||
+161
-65
@@ -47,6 +47,7 @@ import {
|
||||
GitPullRequest,
|
||||
ExternalLink,
|
||||
Copy,
|
||||
RefreshCw,
|
||||
} from 'lucide-react';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import { useGitSettings } from '@/hooks/useGitSettings';
|
||||
@@ -56,6 +57,7 @@ import { useToast } from '@/hooks/useToast';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { usePullRequests } from '@/hooks/usePullRequests';
|
||||
import { useGitFetch } from '@/hooks/useGitFetch';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { findCredentialsForRepo } from '@/lib/gitCredentials';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
@@ -63,6 +65,22 @@ import { GitManagementDialog } from '@/components/git/GitManagementDialog';
|
||||
import { MergeDialog } from '@/components/git/MergeDialog';
|
||||
import { PullRequestDialog } from '@/components/git/PullRequestDialog';
|
||||
import { AnnounceRepositoryDialog, type AnnounceRepositoryResult } from '@/components/git/AnnounceRepositoryDialog';
|
||||
import { formatRelativeTime } from '@/lib/utils';
|
||||
|
||||
// Helper function to format fetch timestamp with special "fetched" prefix
|
||||
function formatFetchTime(date: Date | number): string {
|
||||
const timestamp = typeof date === 'number' ? date : date.getTime();
|
||||
const now = Date.now();
|
||||
const diffMs = now - timestamp;
|
||||
|
||||
// Less than 20 seconds - use special "fetched just now" message
|
||||
if (diffMs < 20 * 1000) {
|
||||
return 'fetched just now';
|
||||
}
|
||||
|
||||
// Otherwise use the standard relative time formatter
|
||||
return formatRelativeTime(timestamp);
|
||||
}
|
||||
|
||||
interface GitDialogProps {
|
||||
projectId: string;
|
||||
@@ -89,6 +107,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
const [isCreatingBranch, setIsCreatingBranch] = useState(false);
|
||||
const [newBranchName, setNewBranchName] = useState('');
|
||||
const [isCreateBranchDialogOpen, setIsCreateBranchDialogOpen] = useState(false);
|
||||
const [, setUpdateTrigger] = useState(0);
|
||||
|
||||
const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId);
|
||||
const { settings } = useGitSettings();
|
||||
@@ -98,9 +117,19 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
const { user } = useCurrentUser();
|
||||
const { nostr } = useNostr();
|
||||
const { data: pullRequests, isLoading: isLoadingPRs } = usePullRequests(originUrl);
|
||||
const { data: gitFetchData, isFetching: isFetchingRemote, refetch: refetchRemote } = useGitFetch(projectId);
|
||||
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
|
||||
// Update the "last fetched" timestamp display every 10 seconds
|
||||
useEffect(() => {
|
||||
const interval = setInterval(() => {
|
||||
setUpdateTrigger(prev => prev + 1);
|
||||
}, 1000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
// Initialize origin URL from git status and load nostr.repo config
|
||||
useEffect(() => {
|
||||
const loadGitConfig = async () => {
|
||||
@@ -153,7 +182,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
await git.checkout({
|
||||
dir: projectPath,
|
||||
ref: branchName,
|
||||
force: true,
|
||||
});
|
||||
|
||||
toast({
|
||||
@@ -214,13 +242,23 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
object: currentRef,
|
||||
});
|
||||
|
||||
toast({
|
||||
title: 'Branch created',
|
||||
description: `Created branch "${newBranchName}"`,
|
||||
// Automatically check out the new branch
|
||||
await git.checkout({
|
||||
dir: projectPath,
|
||||
ref: newBranchName.trim(),
|
||||
force: true,
|
||||
});
|
||||
|
||||
// Close the dialog before showing the toast
|
||||
setNewBranchName('');
|
||||
setIsCreateBranchDialogOpen(false);
|
||||
|
||||
// Show success toast indicating the branch was created and checked out
|
||||
toast({
|
||||
title: 'Branch created and checked out',
|
||||
description: `Switched to new branch "${newBranchName.trim()}"`,
|
||||
});
|
||||
|
||||
await loadBranches();
|
||||
await refetchGitStatus();
|
||||
} catch (error) {
|
||||
@@ -417,50 +455,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
throw new Error('Could not determine repository state. The repository might not have any commits or branches.');
|
||||
}
|
||||
|
||||
// Get HEAD reference
|
||||
let headRef: string | undefined;
|
||||
try {
|
||||
const currentBranch = await git.currentBranch({ dir: projectPath });
|
||||
if (currentBranch) {
|
||||
headRef = `ref: refs/heads/${currentBranch}`;
|
||||
console.log(`HEAD points to: ${headRef}`);
|
||||
} else {
|
||||
// HEAD is detached, use the commit ID directly
|
||||
const headValue = await git.resolveRef({
|
||||
dir: projectPath,
|
||||
ref: 'HEAD',
|
||||
});
|
||||
if (headValue) {
|
||||
headRef = headValue;
|
||||
console.log(`HEAD is detached at: ${headRef}`);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to resolve HEAD:', error);
|
||||
}
|
||||
|
||||
// Create repo state event (NIP-34 kind 30618)
|
||||
const stateEvent = {
|
||||
kind: 30618,
|
||||
content: '',
|
||||
tags: [
|
||||
['d', result.repoId],
|
||||
...refTags,
|
||||
...(headRef ? [['HEAD', headRef]] : []),
|
||||
],
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
};
|
||||
|
||||
console.log('Creating repository state event:', stateEvent);
|
||||
|
||||
// Sign and publish the state event
|
||||
const signedStateEvent = await user.signer.signEvent(stateEvent);
|
||||
|
||||
// State events only go to the relays specified in the repo announcement
|
||||
console.log('Publishing repository state to relays:', result.relays);
|
||||
await nostr.event(signedStateEvent, { relays: result.relays });
|
||||
|
||||
console.log('Published repository state to Nostr relays');
|
||||
console.log('Repository has refs:', refTags);
|
||||
|
||||
// Set origin remote to Nostr URL
|
||||
// Format: nostr://<npub>/<repo-id>
|
||||
@@ -493,13 +488,57 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
|
||||
console.log('Set nostr.repo config to:', result.naddr);
|
||||
|
||||
toast({
|
||||
title: 'Repository published to Nostr',
|
||||
description: 'Waiting for GRASP servers to update...',
|
||||
});
|
||||
// Wait a few seconds for GRASP servers to update
|
||||
await new Promise(resolve => setTimeout(resolve, 3000));
|
||||
|
||||
// Refresh git status to pick up the new remote
|
||||
await refetchGitStatus();
|
||||
|
||||
// Automatically push to the newly configured Nostr remote
|
||||
// Get the current branch fresh from git instead of using stale gitStatus
|
||||
console.log('Starting automatic push to Nostr...');
|
||||
|
||||
try {
|
||||
const currentBranch = await git.currentBranch({ dir: projectPath });
|
||||
console.log('Current branch:', currentBranch);
|
||||
|
||||
if (!currentBranch) {
|
||||
throw new Error('No current branch found');
|
||||
}
|
||||
|
||||
toast({
|
||||
title: 'Repository published to Nostr',
|
||||
description: 'Pushing commits to ngit servers...',
|
||||
});
|
||||
|
||||
console.log('Calling git.push with:', { dir: projectPath, remote: 'origin', ref: currentBranch });
|
||||
|
||||
await git.push({
|
||||
dir: projectPath,
|
||||
remote: 'origin',
|
||||
ref: currentBranch,
|
||||
signer: user.signer,
|
||||
});
|
||||
|
||||
console.log('Push completed successfully');
|
||||
|
||||
toast({
|
||||
title: 'Push successful',
|
||||
description: 'Repository successfully pushed to Nostr',
|
||||
});
|
||||
|
||||
// Refresh git status after push
|
||||
await refetchGitStatus();
|
||||
} catch (pushError) {
|
||||
console.error('Push error:', pushError);
|
||||
const pushErrorMessage = pushError instanceof Error ? pushError.message : 'Unknown error occurred';
|
||||
toast({
|
||||
title: 'Automatic push failed',
|
||||
description: pushErrorMessage,
|
||||
variant: 'destructive',
|
||||
duration: Infinity,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
|
||||
toast({
|
||||
@@ -532,7 +571,8 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
return;
|
||||
}
|
||||
|
||||
if (gitStatus.ahead === 0) {
|
||||
// Allow push if there are commits ahead OR if the remote branch doesn't exist (publishing new branch)
|
||||
if (gitStatus.ahead === 0 && gitStatus.remoteBranchExists) {
|
||||
toast({
|
||||
title: "Nothing to push",
|
||||
description: "No commits ahead of remote. Commit your changes first.",
|
||||
@@ -541,6 +581,16 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
return;
|
||||
}
|
||||
|
||||
// Ensure we have commits to push when publishing a new branch
|
||||
if (!gitStatus.remoteBranchExists && gitStatus.totalCommits === 0) {
|
||||
toast({
|
||||
title: "Cannot publish branch",
|
||||
description: "No commits to push. Commit your changes first.",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsPushing(true);
|
||||
|
||||
try {
|
||||
@@ -554,11 +604,32 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
signer: user?.signer, // For signing if pushing to Nostr
|
||||
});
|
||||
|
||||
// Set up upstream tracking if this is the first push for this branch
|
||||
if (!gitStatus.remoteBranchExists) {
|
||||
await git.setConfig({
|
||||
dir: projectPath,
|
||||
path: `branch.${gitStatus.currentBranch}.remote`,
|
||||
value: remote.name,
|
||||
});
|
||||
await git.setConfig({
|
||||
dir: projectPath,
|
||||
path: `branch.${gitStatus.currentBranch}.merge`,
|
||||
value: `refs/heads/${gitStatus.currentBranch}`,
|
||||
});
|
||||
}
|
||||
|
||||
toast({
|
||||
title: "Push successful",
|
||||
description: `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} pushed to ${remote.name}/${gitStatus.currentBranch}`,
|
||||
});
|
||||
// Show different messages for publishing new branches vs pushing commits
|
||||
if (gitStatus.remoteBranchExists) {
|
||||
toast({
|
||||
title: "Push successful",
|
||||
description: `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} pushed to ${remote.name}/${gitStatus.currentBranch}`,
|
||||
});
|
||||
} else {
|
||||
toast({
|
||||
title: "Branch published",
|
||||
description: `New branch published to ${remote.name}/${gitStatus.currentBranch}`,
|
||||
});
|
||||
}
|
||||
|
||||
// Refresh git status after push
|
||||
await refetchGitStatus();
|
||||
@@ -654,8 +725,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
const getFileStatusIcon = (status: string) => {
|
||||
switch (status) {
|
||||
case 'added':
|
||||
@@ -699,6 +768,11 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
return { status: 'no-remote', text: 'No remote configured', icon: AlertCircle, color: 'text-yellow-600' };
|
||||
}
|
||||
|
||||
// Check if remote branch doesn't exist
|
||||
if (!gitStatus.remoteBranchExists && gitStatus.currentBranch) {
|
||||
return { status: 'not-published', text: 'Branch not published', icon: AlertCircle, color: 'text-yellow-600' };
|
||||
}
|
||||
|
||||
if (gitStatus.ahead > 0 && gitStatus.behind > 0) {
|
||||
return { status: 'diverged', text: `${gitStatus.ahead} ahead, ${gitStatus.behind} behind`, icon: AlertCircle, color: 'text-red-600' };
|
||||
}
|
||||
@@ -1041,13 +1115,36 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
<span className={cn("text-sm font-medium", syncStatus.color)}>
|
||||
{syncStatus.text}
|
||||
</span>
|
||||
|
||||
{/* Last Fetched Info - inline with sync status */}
|
||||
{gitStatus.remotes.length > 0 && gitFetchData?.fetchedAt && (
|
||||
<>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
· {formatFetchTime(gitFetchData.fetchedAt)}
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => refetchRemote()}
|
||||
disabled={isFetchingRemote}
|
||||
className="h-5 w-5 p-0 -ml-1 hover:bg-transparent"
|
||||
title="Refresh remote status"
|
||||
>
|
||||
{isFetchingRemote ? (
|
||||
<Loader2 className="h-3 w-3 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="h-3 w-3 hover:text-foreground transition-colors" />
|
||||
)}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{gitStatus.remotes.length > 0 && (
|
||||
{originUrl.trim() && (
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
onClick={handlePull}
|
||||
disabled={isPulling || isPushing || isPushingToNostr}
|
||||
disabled={isPulling || isPushing || isPushingToNostr || !gitStatus.remoteBranchExists}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1"
|
||||
@@ -1062,7 +1159,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
|
||||
<Button
|
||||
onClick={handlePush}
|
||||
disabled={isPushing || isPulling || isPushingToNostr || gitStatus.ahead === 0}
|
||||
disabled={isPushing || isPulling || isPushingToNostr || (gitStatus.ahead === 0 && gitStatus.remoteBranchExists)}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1"
|
||||
@@ -1077,7 +1174,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
</div>
|
||||
)}
|
||||
|
||||
{gitStatus.remotes.length === 0 && user && (
|
||||
{!originUrl.trim() && user && (
|
||||
<Button
|
||||
onClick={handlePushToNostr}
|
||||
disabled={isPushingToNostr || isPushing || isPulling}
|
||||
@@ -1090,7 +1187,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
) : (
|
||||
<Zap className="h-4 w-4 mr-2" />
|
||||
)}
|
||||
{isPushingToNostr ? 'Publishing to Nostr...' : 'Push to Nostr'}
|
||||
{isPushingToNostr ? 'Loading...' : 'Push to Nostr'}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
@@ -1194,7 +1291,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
await git.checkout({
|
||||
dir: projectPath,
|
||||
ref: pr.sourceBranch,
|
||||
force: true,
|
||||
});
|
||||
await refetchGitStatus();
|
||||
toast({
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { X } from 'lucide-react';
|
||||
import { Dialog, DialogPortal, DialogOverlay } from '@/components/ui/dialog';
|
||||
import * as DialogPrimitive from '@radix-ui/react-dialog';
|
||||
import { VFSImage } from '@/components/VFSImage';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { isAbsolutePath } from '@/lib/pathUtils';
|
||||
|
||||
interface ImageLightboxProps {
|
||||
imageUrl: string | null;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function ImageLightbox({ imageUrl, onClose }: ImageLightboxProps) {
|
||||
return (
|
||||
<Dialog open={!!imageUrl} onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogPortal>
|
||||
<DialogOverlay className="bg-black/95" />
|
||||
<DialogPrimitive.Content
|
||||
className={cn(
|
||||
"fixed inset-0 z-50 flex items-center justify-center p-4 bg-transparent border-0 shadow-none",
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out",
|
||||
"data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
|
||||
"data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95"
|
||||
)}
|
||||
onEscapeKeyDown={onClose}
|
||||
>
|
||||
{imageUrl && (
|
||||
<>
|
||||
{/* Clickable background to close */}
|
||||
<div
|
||||
className="absolute inset-0 cursor-pointer z-[1]"
|
||||
onClick={onClose}
|
||||
aria-label="Close lightbox"
|
||||
/>
|
||||
|
||||
{/* Close button */}
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="absolute top-4 right-4 z-[3] p-2 rounded-full bg-black/50 hover:bg-black/70 text-white transition-colors"
|
||||
aria-label="Close"
|
||||
>
|
||||
<X className="h-6 w-6" />
|
||||
</button>
|
||||
|
||||
{/* Image */}
|
||||
<div
|
||||
className="relative z-[2] flex items-center justify-center w-full h-full pointer-events-none"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{isAbsolutePath(imageUrl) ? (
|
||||
<VFSImage
|
||||
path={imageUrl}
|
||||
alt="Expanded image"
|
||||
className="max-w-[calc(100vw-2rem)] max-h-[calc(100vh-2rem)] w-auto h-auto object-contain rounded-lg pointer-events-auto"
|
||||
/>
|
||||
) : (
|
||||
<img
|
||||
src={imageUrl}
|
||||
alt="Expanded image"
|
||||
className="max-w-[calc(100vw-2rem)] max-h-[calc(100vh-2rem)] w-auto h-auto object-contain rounded-lg pointer-events-auto"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { ModelInput } from '@/components/ModelInput';
|
||||
|
||||
interface ImageModelDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export function ImageModelDialog({ open, onOpenChange }: ImageModelDialogProps) {
|
||||
const { settings, updateSettings } = useAISettings();
|
||||
const [selectedModel, setSelectedModel] = useState(settings.imageModel || '');
|
||||
|
||||
// Update selected model when dialog opens or settings change
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setSelectedModel(settings.imageModel || '');
|
||||
}
|
||||
}, [open, settings.imageModel]);
|
||||
|
||||
const handleSave = () => {
|
||||
updateSettings({ imageModel: selectedModel || undefined });
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
const imageModelFilter = useCallback((model: { type?: 'chat' | 'image'; modalities?: string[] }) => {
|
||||
// Filter out models that are definitely NOT image models
|
||||
// If type is "chat", exclude it
|
||||
if (model.type === 'chat') {
|
||||
return false;
|
||||
}
|
||||
// If modalities exist but don't include "image", exclude it
|
||||
if (model.modalities && !model.modalities.includes('image')) {
|
||||
return false;
|
||||
}
|
||||
// Otherwise include it (type is "image", modalities includes "image", or both are undefined)
|
||||
return true;
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[500px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Configure Image Model</DialogTitle>
|
||||
<DialogDescription>
|
||||
Select an AI model to use for image generation.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="image-model">Image Model</Label>
|
||||
<ModelInput
|
||||
value={selectedModel}
|
||||
onChange={setSelectedModel}
|
||||
className="flex-1"
|
||||
modelFilter={imageModelFilter}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleSave}>
|
||||
Save
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -21,6 +21,7 @@ const { CreditsDialog } = await import('./CreditsDialog');
|
||||
|
||||
const mockProvider: AIProvider = {
|
||||
id: 'test-provider',
|
||||
name: 'Test Provider',
|
||||
baseURL: 'https://api.test.com/v1',
|
||||
apiKey: 'test-key',
|
||||
nostr: false,
|
||||
|
||||
@@ -0,0 +1,338 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Server, Trash2, Check, Plus, X } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useMCPServerStatus } from '@/hooks/useMCPServerStatus';
|
||||
import type { MCPServer } from '@/contexts/AISettingsContext';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
function MCPConnectionStatus({ server }: { server: MCPServer }) {
|
||||
const status = useMCPServerStatus(server);
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1.5 ml-auto mr-2">
|
||||
<div
|
||||
className={cn(
|
||||
'h-2 w-2 rounded-full',
|
||||
status === 'connected' && 'bg-green-500',
|
||||
status === 'offline' && 'bg-red-500',
|
||||
status === 'checking' && 'bg-yellow-500 animate-pulse'
|
||||
)}
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground capitalize">
|
||||
{status}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface HeadersEditorProps {
|
||||
headers: Record<string, string> | undefined;
|
||||
onChange: (headers: Record<string, string> | undefined) => void;
|
||||
}
|
||||
|
||||
function HeadersEditor({ headers, onChange }: HeadersEditorProps) {
|
||||
const { t } = useTranslation();
|
||||
const [newHeaderName, setNewHeaderName] = useState('');
|
||||
const [newHeaderValue, setNewHeaderValue] = useState('');
|
||||
|
||||
const headerEntries = Object.entries(headers || {});
|
||||
|
||||
const handleAddHeader = () => {
|
||||
if (!newHeaderName.trim() || !newHeaderValue.trim()) return;
|
||||
|
||||
const updatedHeaders = {
|
||||
...(headers || {}),
|
||||
[newHeaderName.trim()]: newHeaderValue.trim(),
|
||||
};
|
||||
|
||||
onChange(updatedHeaders);
|
||||
setNewHeaderName('');
|
||||
setNewHeaderValue('');
|
||||
};
|
||||
|
||||
const handleRemoveHeader = (name: string) => {
|
||||
const updatedHeaders = { ...(headers || {}) };
|
||||
delete updatedHeaders[name];
|
||||
|
||||
// If no headers left, set to undefined
|
||||
onChange(Object.keys(updatedHeaders).length > 0 ? updatedHeaders : undefined);
|
||||
};
|
||||
|
||||
const handleUpdateHeader = (oldName: string, newName: string, newValue: string) => {
|
||||
const updatedHeaders = { ...(headers || {}) };
|
||||
delete updatedHeaders[oldName];
|
||||
updatedHeaders[newName] = newValue;
|
||||
onChange(updatedHeaders);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<Label>{t('mcpServerHeaders')}</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('mcpServerHeadersDescription')}
|
||||
</p>
|
||||
|
||||
{/* Existing Headers */}
|
||||
{headerEntries.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
{headerEntries.map(([name, value]) => (
|
||||
<div key={name} className="flex gap-2">
|
||||
<Input
|
||||
value={name}
|
||||
onChange={(e) => handleUpdateHeader(name, e.target.value, value)}
|
||||
placeholder="Header name"
|
||||
className="flex-1"
|
||||
/>
|
||||
<Input
|
||||
value={value}
|
||||
onChange={(e) => handleUpdateHeader(name, name, e.target.value)}
|
||||
placeholder="Header value"
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => handleRemoveHeader(name)}
|
||||
className="shrink-0"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Add New Header */}
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={newHeaderName}
|
||||
onChange={(e) => setNewHeaderName(e.target.value)}
|
||||
placeholder="Header name (e.g., Authorization)"
|
||||
className="flex-1"
|
||||
/>
|
||||
<Input
|
||||
value={newHeaderValue}
|
||||
onChange={(e) => setNewHeaderValue(e.target.value)}
|
||||
placeholder="Header value"
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={handleAddHeader}
|
||||
disabled={!newHeaderName.trim() || !newHeaderValue.trim()}
|
||||
className="shrink-0"
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function MCPServersSection() {
|
||||
const { t } = useTranslation();
|
||||
const { settings, setMCPServer, removeMCPServer } = useAISettings();
|
||||
const { toast } = useToast();
|
||||
const [serverName, setServerName] = useState('');
|
||||
const [serverUrl, setServerUrl] = useState('');
|
||||
const [serverHeaders, setServerHeaders] = useState<Record<string, string> | undefined>(undefined);
|
||||
const [serverType] = useState<'streamable-http'>('streamable-http'); // Only streamable-http is supported
|
||||
|
||||
const mcpServers = settings.mcpServers || {};
|
||||
const serverEntries = Object.entries(mcpServers);
|
||||
|
||||
const handleAddServer = () => {
|
||||
if (!serverName.trim() || !serverUrl.trim()) return;
|
||||
|
||||
if (mcpServers[serverName.trim()]) {
|
||||
toast({
|
||||
title: t('error'),
|
||||
description: t('mcpServerAddFailed'),
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const newServer: MCPServer = {
|
||||
type: serverType,
|
||||
url: serverUrl.trim(),
|
||||
headers: serverHeaders,
|
||||
};
|
||||
|
||||
setMCPServer(serverName.trim(), newServer);
|
||||
|
||||
toast({
|
||||
title: t('mcpServerAdded'),
|
||||
description: t('mcpServerAddedDescription', { name: serverName.trim() }),
|
||||
});
|
||||
|
||||
setServerName('');
|
||||
setServerUrl('');
|
||||
setServerHeaders(undefined);
|
||||
};
|
||||
|
||||
const handleRemoveServer = (name: string) => {
|
||||
removeMCPServer(name);
|
||||
|
||||
toast({
|
||||
title: t('mcpServerDeleted'),
|
||||
description: t('mcpServerDeletedDescription', { name }),
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* MCP Servers Header */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Server className="h-5 w-5 text-primary" />
|
||||
<h3 className="text-lg font-semibold">{t('mcpServers')}</h3>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('mcpServersDescription')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Configured MCP Servers List */}
|
||||
{serverEntries.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
{serverEntries.map(([name, server]) => (
|
||||
<Accordion key={name} type="single" collapsible className="w-full">
|
||||
<AccordionItem value={name} className="border rounded-lg">
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<div className="flex items-center gap-2 w-full mr-3">
|
||||
<Server size={16} className="text-muted-foreground" />
|
||||
<span className="font-medium">{name}</span>
|
||||
<MCPConnectionStatus server={server} />
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
<div className="space-y-3">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`${name}-type`}>
|
||||
{t('mcpServerType')} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Select value={server.type} disabled>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="streamable-http">{t('mcpServerTypeStreamableHttp')}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`${name}-url`}>
|
||||
{t('mcpServerUrl')} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id={`${name}-url`}
|
||||
value={server.url}
|
||||
onChange={(e) => setMCPServer(name, { ...server, url: e.target.value })}
|
||||
placeholder="https://example.com/mcp"
|
||||
/>
|
||||
</div>
|
||||
<HeadersEditor
|
||||
headers={server.headers}
|
||||
onChange={(headers) => setMCPServer(name, { ...server, headers })}
|
||||
/>
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={() => handleRemoveServer(name)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
{t('delete')}
|
||||
</Button>
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Add New MCP Server */}
|
||||
<Accordion type="single" collapsible className="w-full">
|
||||
<AccordionItem value="add-server">
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<div className="flex items-center gap-2">
|
||||
<Plus className="h-4 w-4" />
|
||||
<span className="text-sm font-medium">{t('addMcpServer')}</span>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('mcpServerDescription')}
|
||||
</p>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="new-server-name">
|
||||
{t('mcpServerName')} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="new-server-name"
|
||||
placeholder="e.g., my-mcp-server"
|
||||
value={serverName}
|
||||
onChange={(e) => setServerName(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="new-server-type">
|
||||
{t('mcpServerType')} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Select value={serverType} disabled>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="streamable-http">{t('mcpServerTypeStreamableHttp')}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Only Streamable HTTP transport is currently supported
|
||||
</p>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="new-server-url">
|
||||
{t('mcpServerUrl')} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="new-server-url"
|
||||
placeholder="https://example.com/mcp"
|
||||
value={serverUrl}
|
||||
onChange={(e) => setServerUrl(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<HeadersEditor
|
||||
headers={serverHeaders}
|
||||
onChange={setServerHeaders}
|
||||
/>
|
||||
<Button
|
||||
onClick={handleAddServer}
|
||||
disabled={!serverName.trim() || !serverUrl.trim() || !!mcpServers[serverName.trim()]}
|
||||
className="gap-2 w-full"
|
||||
>
|
||||
<Check className="h-4 w-4" />
|
||||
{t('add')}
|
||||
</Button>
|
||||
{mcpServers[serverName.trim()] && (
|
||||
<p className="text-sm text-destructive">
|
||||
A server with this name already exists
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { ModelInput } from './ModelInput';
|
||||
|
||||
// Mock the hooks
|
||||
vi.mock('@/hooks/useAISettings', () => ({
|
||||
useAISettings: () => ({
|
||||
settings: {
|
||||
providers: [
|
||||
{ id: 'test-provider', name: 'Test Provider', baseURL: 'https://api.test.com' }
|
||||
]
|
||||
}
|
||||
})
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useProviderModels', () => ({
|
||||
useProviderModels: () => ({
|
||||
models: [
|
||||
{
|
||||
id: 'text-model',
|
||||
name: 'Text Model',
|
||||
provider: 'test-provider',
|
||||
fullId: 'test-provider/text-model',
|
||||
inputModalities: ['text'],
|
||||
outputModalities: ['text']
|
||||
},
|
||||
{
|
||||
id: 'image-model',
|
||||
name: 'Image Model',
|
||||
provider: 'test-provider',
|
||||
fullId: 'test-provider/image-model',
|
||||
inputModalities: ['text'],
|
||||
outputModalities: ['image']
|
||||
},
|
||||
{
|
||||
id: 'multimodal-model',
|
||||
name: 'Multimodal Model',
|
||||
provider: 'test-provider',
|
||||
fullId: 'test-provider/multimodal-model',
|
||||
inputModalities: ['text', 'image'],
|
||||
outputModalities: ['text', 'image']
|
||||
},
|
||||
{
|
||||
id: 'no-modalities-model',
|
||||
name: 'No Modalities Model',
|
||||
provider: 'test-provider',
|
||||
fullId: 'test-provider/no-modalities-model'
|
||||
}
|
||||
],
|
||||
isLoading: false,
|
||||
error: null,
|
||||
refetch: vi.fn()
|
||||
})
|
||||
}));
|
||||
|
||||
describe('ModelInput', () => {
|
||||
it('renders without crashing', () => {
|
||||
const onChange = vi.fn();
|
||||
render(
|
||||
<TestApp>
|
||||
<ModelInput value="" onChange={onChange} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByRole('combobox')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('accepts modelFilter prop', () => {
|
||||
const onChange = vi.fn();
|
||||
const modelFilter = (model: { modalities?: string[] }) => model.modalities?.includes('image') ?? false;
|
||||
render(
|
||||
<TestApp>
|
||||
<ModelInput
|
||||
value=""
|
||||
onChange={onChange}
|
||||
modelFilter={modelFilter}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByRole('combobox')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,185 @@
|
||||
import { useState, useMemo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Bot, ChevronDown } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator } from '@/components/ui/command';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useProviderModels } from '@/hooks/useProviderModels';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface ProviderModel {
|
||||
id: string;
|
||||
type?: "chat" | "image";
|
||||
name?: string;
|
||||
provider: string;
|
||||
fullId: string;
|
||||
description?: string;
|
||||
contextLength?: number;
|
||||
pricing?: {
|
||||
prompt: unknown;
|
||||
completion: unknown;
|
||||
};
|
||||
modalities?: string[];
|
||||
}
|
||||
|
||||
interface ModelInputProps {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
className?: string;
|
||||
placeholder?: string;
|
||||
modelFilter?: (model: ProviderModel) => boolean;
|
||||
}
|
||||
|
||||
export function ModelInput({
|
||||
value,
|
||||
onChange,
|
||||
className,
|
||||
placeholder,
|
||||
modelFilter,
|
||||
}: ModelInputProps) {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
const { settings } = useAISettings();
|
||||
const { models } = useProviderModels();
|
||||
|
||||
const defaultPlaceholder = 'Select a model...';
|
||||
|
||||
// Filter models using the provided filter function
|
||||
const filteredModels = useMemo(() => {
|
||||
if (modelFilter) {
|
||||
return models.filter(modelFilter);
|
||||
}
|
||||
return models;
|
||||
}, [models, modelFilter]);
|
||||
|
||||
// Group models by provider
|
||||
const modelsByProvider = useMemo(() => {
|
||||
const groups: Record<string, typeof filteredModels> = {};
|
||||
for (const model of filteredModels) {
|
||||
if (!groups[model.provider]) {
|
||||
groups[model.provider] = [];
|
||||
}
|
||||
groups[model.provider].push(model);
|
||||
}
|
||||
return groups;
|
||||
}, [filteredModels]);
|
||||
|
||||
// Get provider display name and baseURL for a given provider ID
|
||||
const getProviderInfo = useMemo(() => {
|
||||
return (providerId: string) => {
|
||||
const provider = settings.providers.find(p => p.id === providerId);
|
||||
return {
|
||||
displayName: provider ? provider.name : providerId,
|
||||
baseURL: provider?.baseURL,
|
||||
};
|
||||
};
|
||||
}, [settings.providers]);
|
||||
|
||||
// Get display info for the selected model
|
||||
const selectedModelDisplay = useMemo(() => {
|
||||
if (!value) return null;
|
||||
|
||||
const providerId = value.split('/')[0];
|
||||
const modelId = value.split('/').slice(1).join('/') || value;
|
||||
const providerInfo = getProviderInfo(providerId);
|
||||
const modelData = filteredModels.find(m => m.fullId === value);
|
||||
const displayName = modelData?.name || modelId;
|
||||
|
||||
return {
|
||||
displayName,
|
||||
baseURL: providerInfo.baseURL,
|
||||
};
|
||||
}, [value, getProviderInfo, filteredModels]);
|
||||
|
||||
const handleSelect = (selectedValue: string) => {
|
||||
onChange(selectedValue);
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
role="combobox"
|
||||
aria-expanded={open}
|
||||
className={cn(
|
||||
"w-full justify-between font-normal h-10",
|
||||
!value && "text-muted-foreground",
|
||||
className
|
||||
)}
|
||||
>
|
||||
{selectedModelDisplay ? (
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
{selectedModelDisplay.baseURL ? (
|
||||
<ExternalFavicon
|
||||
url={selectedModelDisplay.baseURL}
|
||||
size={16}
|
||||
fallback={<Bot size={16} />}
|
||||
className="flex-shrink-0"
|
||||
/>
|
||||
) : (
|
||||
<Bot size={16} className="flex-shrink-0" />
|
||||
)}
|
||||
<span className="truncate">
|
||||
{selectedModelDisplay.displayName}
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<span className="truncate">
|
||||
{placeholder || defaultPlaceholder}
|
||||
</span>
|
||||
)}
|
||||
<ChevronDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-[400px] p-0" align="start">
|
||||
<Command>
|
||||
<CommandInput placeholder={t('searchModels')} className="h-9" />
|
||||
<CommandList>
|
||||
<CommandEmpty>
|
||||
<div className="py-6 text-center text-sm text-muted-foreground">
|
||||
<p>{t('noModelsFound')}</p>
|
||||
</div>
|
||||
</CommandEmpty>
|
||||
|
||||
{/* Provider models */}
|
||||
{Object.entries(modelsByProvider).map(([providerId, providerModels], index) => {
|
||||
const providerInfo = getProviderInfo(providerId);
|
||||
|
||||
return (
|
||||
<div key={providerId}>
|
||||
{index > 0 && <CommandSeparator />}
|
||||
<CommandGroup heading={providerInfo.displayName}>
|
||||
{providerModels.map((model) => (
|
||||
<CommandItem
|
||||
key={model.fullId}
|
||||
value={model.fullId}
|
||||
onSelect={() => handleSelect(model.fullId)}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
{providerInfo.baseURL ? (
|
||||
<ExternalFavicon
|
||||
url={providerInfo.baseURL}
|
||||
size={16}
|
||||
fallback={<Bot size={16} />}
|
||||
className="mr-2 flex-shrink-0"
|
||||
/>
|
||||
) : (
|
||||
<Bot size={16} className="mr-2 flex-shrink-0" />
|
||||
)}
|
||||
<span className="truncate flex-1">{model.name || model.id}</span>
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
@@ -42,14 +42,15 @@ describe('ModelSelector', () => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: { providers: [], recentlyUsedModels: [] },
|
||||
settings: { providers: [], recentlyUsedModels: [], mcpServers: {} },
|
||||
addRecentlyUsedModel: mockAddRecentlyUsedModel,
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
});
|
||||
|
||||
mockUseProviderModels.mockReturnValue({
|
||||
@@ -80,13 +81,22 @@ describe('ModelSelector', () => {
|
||||
});
|
||||
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: { providers: [], recentlyUsedModels },
|
||||
settings: {
|
||||
providers: [
|
||||
{ id: 'provider1', name: 'Provider 1', baseURL: 'https://api.provider1.com' },
|
||||
{ id: 'provider2', name: 'Provider 2', baseURL: 'https://api.provider2.com' },
|
||||
],
|
||||
recentlyUsedModels,
|
||||
mcpServers: {},
|
||||
},
|
||||
addRecentlyUsedModel: mockAddRecentlyUsedModel,
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
|
||||
});
|
||||
|
||||
@@ -102,7 +112,7 @@ describe('ModelSelector', () => {
|
||||
|
||||
// Wait for the dropdown to open
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('provider2')).toBeInTheDocument();
|
||||
expect(screen.getByText('Provider 2')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Recently used section should NOT be visible
|
||||
@@ -111,8 +121,8 @@ describe('ModelSelector', () => {
|
||||
// provider1 should be hidden since all its models are in recently used
|
||||
expect(screen.queryByText('provider1')).not.toBeInTheDocument();
|
||||
|
||||
// provider2 should still show with model3
|
||||
expect(screen.getByText('provider2/model3')).toBeInTheDocument();
|
||||
// provider2 should still show with model3 (just the model ID, not the full ID)
|
||||
expect(screen.getByText('model3')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows recently used section when less than 5 models but some recently used are not available', async () => {
|
||||
@@ -133,13 +143,23 @@ describe('ModelSelector', () => {
|
||||
});
|
||||
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: { providers: [], recentlyUsedModels },
|
||||
settings: {
|
||||
providers: [
|
||||
{ id: 'provider1', name: 'Provider 1', baseURL: 'https://api.provider1.com' },
|
||||
{ id: 'provider2', name: 'Provider 2', baseURL: 'https://api.provider2.com' },
|
||||
{ id: 'provider3', name: 'Provider 3', baseURL: 'https://api.provider3.com' },
|
||||
],
|
||||
recentlyUsedModels,
|
||||
mcpServers: {},
|
||||
},
|
||||
addRecentlyUsedModel: mockAddRecentlyUsedModel,
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
|
||||
});
|
||||
|
||||
@@ -155,7 +175,7 @@ describe('ModelSelector', () => {
|
||||
|
||||
// Wait for the dropdown to open
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('provider1')).toBeInTheDocument();
|
||||
expect(screen.getByText('Provider 1')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Recently used section SHOULD be visible
|
||||
@@ -182,13 +202,23 @@ describe('ModelSelector', () => {
|
||||
});
|
||||
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: { providers: [], recentlyUsedModels },
|
||||
settings: {
|
||||
providers: [
|
||||
{ id: 'provider1', name: 'Provider 1', baseURL: 'https://api.provider1.com' },
|
||||
{ id: 'provider2', name: 'Provider 2', baseURL: 'https://api.provider2.com' },
|
||||
{ id: 'provider3', name: 'Provider 3', baseURL: 'https://api.provider3.com' },
|
||||
],
|
||||
recentlyUsedModels,
|
||||
mcpServers: {},
|
||||
},
|
||||
addRecentlyUsedModel: mockAddRecentlyUsedModel,
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
|
||||
});
|
||||
|
||||
@@ -204,7 +234,7 @@ describe('ModelSelector', () => {
|
||||
|
||||
// Wait for the dropdown to open
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('provider2')).toBeInTheDocument();
|
||||
expect(screen.getByText('Provider 2')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Recently used section SHOULD be visible
|
||||
@@ -213,10 +243,10 @@ describe('ModelSelector', () => {
|
||||
// provider1 should be hidden since all its models are in recently used
|
||||
expect(screen.queryByText('provider1')).not.toBeInTheDocument();
|
||||
|
||||
// provider2 and provider3 should still show
|
||||
expect(screen.getByText('provider2/model3')).toBeInTheDocument();
|
||||
expect(screen.getByText('provider2/model4')).toBeInTheDocument();
|
||||
expect(screen.getByText('provider3/model5')).toBeInTheDocument();
|
||||
// provider2 and provider3 should still show (just the model IDs, not full IDs)
|
||||
expect(screen.getByText('model3')).toBeInTheDocument();
|
||||
expect(screen.getByText('model4')).toBeInTheDocument();
|
||||
expect(screen.getByText('model5')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides recently used section when no recently used models exist', async () => {
|
||||
@@ -233,13 +263,15 @@ describe('ModelSelector', () => {
|
||||
});
|
||||
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: { providers: [], recentlyUsedModels: [] }, // No recently used models
|
||||
settings: { providers: [], recentlyUsedModels: [], mcpServers: {} }, // No recently used models
|
||||
addRecentlyUsedModel: mockAddRecentlyUsedModel,
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
|
||||
});
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState, useMemo, useEffect, memo } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings, TriangleAlert } from 'lucide-react';
|
||||
import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings, TriangleAlert, Bot } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
@@ -12,6 +12,7 @@ import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useProviderModels } from '@/hooks/useProviderModels';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { ModelPricing } from '@/components/ModelPricing';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface ModelSelectorProps {
|
||||
@@ -44,10 +45,15 @@ export const ModelSelector = memo(function ModelSelector({
|
||||
const [isCustomInput, setIsCustomInput] = useState(false);
|
||||
const [customValue, setCustomValue] = useState('');
|
||||
const { settings, addRecentlyUsedModel, isConfigured } = useAISettings();
|
||||
const { models, isLoading, error, refetch } = useProviderModels();
|
||||
const { models: allModels, isLoading, error, refetch } = useProviderModels();
|
||||
const navigate = useNavigate();
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
// Filter models to only include chat models (type is undefined or "chat")
|
||||
const models = useMemo(() => {
|
||||
return allModels.filter(model => model.type === undefined || model.type === 'chat');
|
||||
}, [allModels]);
|
||||
|
||||
const defaultPlaceholder = t('selectOrEnterModel');
|
||||
|
||||
const recentlyUsedModels = useMemo(() => settings.recentlyUsedModels || [], [settings.recentlyUsedModels]);
|
||||
@@ -55,23 +61,6 @@ export const ModelSelector = memo(function ModelSelector({
|
||||
// Create a Set of recently used model IDs for efficient lookup
|
||||
const recentlyUsedSet = useMemo(() => new Set(recentlyUsedModels), [recentlyUsedModels]);
|
||||
|
||||
// Group models by provider, excluding models that are in the recently used section
|
||||
const modelsByProvider = useMemo(() => {
|
||||
const groups: Record<string, typeof models> = {};
|
||||
for (const model of models) {
|
||||
// Skip models that are already shown in recently used
|
||||
if (recentlyUsedSet.has(model.fullId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!groups[model.provider]) {
|
||||
groups[model.provider] = [];
|
||||
}
|
||||
groups[model.provider].push(model);
|
||||
}
|
||||
return groups;
|
||||
}, [models, recentlyUsedSet]);
|
||||
|
||||
// Determine if we should show the "Recently Used" section
|
||||
const shouldShowRecentlyUsed = useMemo(() => {
|
||||
// If no recently used models, don't show the section
|
||||
@@ -95,6 +84,51 @@ export const ModelSelector = memo(function ModelSelector({
|
||||
return !allRecentlyUsedAreAvailable;
|
||||
}, [recentlyUsedModels, models]);
|
||||
|
||||
// Group models by provider, excluding models that are in the recently used section
|
||||
// (only exclude them if the recently used section is actually being shown)
|
||||
const modelsByProvider = useMemo(() => {
|
||||
const groups: Record<string, typeof models> = {};
|
||||
for (const model of models) {
|
||||
// Only skip models that are in recently used if we're showing the recently used section
|
||||
if (shouldShowRecentlyUsed && recentlyUsedSet.has(model.fullId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!groups[model.provider]) {
|
||||
groups[model.provider] = [];
|
||||
}
|
||||
groups[model.provider].push(model);
|
||||
}
|
||||
return groups;
|
||||
}, [models, recentlyUsedSet, shouldShowRecentlyUsed]);
|
||||
|
||||
// Get provider display name and baseURL for a given provider ID
|
||||
const getProviderInfo = useMemo(() => {
|
||||
return (providerId: string) => {
|
||||
const provider = settings.providers.find(p => p.id === providerId);
|
||||
return {
|
||||
displayName: provider ? provider.name : providerId,
|
||||
baseURL: provider?.baseURL,
|
||||
};
|
||||
};
|
||||
}, [settings.providers]);
|
||||
|
||||
// Get display info for the selected model
|
||||
const selectedModelDisplay = useMemo(() => {
|
||||
if (!value) return null;
|
||||
|
||||
const providerId = value.split('/')[0];
|
||||
const modelId = value.split('/').slice(1).join('/') || value;
|
||||
const providerInfo = getProviderInfo(providerId);
|
||||
const modelData = models.find(m => m.fullId === value);
|
||||
const displayName = modelData?.name || modelId;
|
||||
|
||||
return {
|
||||
displayName,
|
||||
baseURL: providerInfo.baseURL,
|
||||
};
|
||||
}, [value, getProviderInfo, models]);
|
||||
|
||||
// Check if the current model is free
|
||||
const isCurrentModelFree = useMemo(() => {
|
||||
if (!value) return false;
|
||||
@@ -278,13 +312,31 @@ export const ModelSelector = memo(function ModelSelector({
|
||||
role="combobox"
|
||||
aria-expanded={open}
|
||||
className={cn(
|
||||
"h-8 p-0 gap-0.5 text-xs border-0 bg-transparent hover:bg-transparent hover:text-foreground focus-visible:ring-0 focus-visible:ring-offset-0 text-muted-foreground text-right min-w-0 max-w-[280px]"
|
||||
"h-8 p-0 gap-1 text-xs border-0 bg-transparent hover:bg-transparent hover:text-foreground focus-visible:ring-0 focus-visible:ring-offset-0 text-muted-foreground text-right min-w-0 max-w-[280px]"
|
||||
)}
|
||||
disabled={disabled}
|
||||
>
|
||||
<span className="truncate">
|
||||
{value || placeholder || defaultPlaceholder}
|
||||
</span>
|
||||
{selectedModelDisplay ? (
|
||||
<>
|
||||
{selectedModelDisplay.baseURL ? (
|
||||
<ExternalFavicon
|
||||
url={selectedModelDisplay.baseURL}
|
||||
size={16}
|
||||
fallback={<Bot size={16} />}
|
||||
className="flex-shrink-0"
|
||||
/>
|
||||
) : (
|
||||
<Bot size={16} className="flex-shrink-0" />
|
||||
)}
|
||||
<span className="truncate">
|
||||
{selectedModelDisplay.displayName}
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<span className="truncate">
|
||||
{placeholder || defaultPlaceholder}
|
||||
</span>
|
||||
)}
|
||||
<ChevronDown className="size-3 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
@@ -305,6 +357,11 @@ export const ModelSelector = memo(function ModelSelector({
|
||||
<CommandGroup heading={t('recentlyUsed')}>
|
||||
{recentlyUsedModels.map((modelId) => {
|
||||
const modelData = models.find(m => m.fullId === modelId);
|
||||
const providerId = modelId.split('/')[0];
|
||||
const providerInfo = getProviderInfo(providerId);
|
||||
const displayModelId = modelId.split('/').slice(1).join('/') || modelId;
|
||||
const displayName = modelData?.name || displayModelId;
|
||||
|
||||
return (
|
||||
<CommandItem
|
||||
key={modelId}
|
||||
@@ -318,7 +375,17 @@ export const ModelSelector = memo(function ModelSelector({
|
||||
value === modelId ? "opacity-100" : "opacity-0"
|
||||
)}
|
||||
/>
|
||||
<span className="truncate flex-1">{modelId}</span>
|
||||
{providerInfo.baseURL ? (
|
||||
<ExternalFavicon
|
||||
url={providerInfo.baseURL}
|
||||
size={16}
|
||||
fallback={<Bot size={16} />}
|
||||
className="mr-2 flex-shrink-0"
|
||||
/>
|
||||
) : (
|
||||
<Bot size={16} className="mr-2 flex-shrink-0" />
|
||||
)}
|
||||
<span className="truncate flex-1">{displayName}</span>
|
||||
{modelData?.pricing && (
|
||||
<ModelPricing pricing={modelData.pricing} className="ml-2" />
|
||||
)}
|
||||
@@ -367,32 +434,46 @@ export const ModelSelector = memo(function ModelSelector({
|
||||
)}
|
||||
|
||||
{/* Provider models */}
|
||||
{!isLoading && Object.entries(modelsByProvider).map(([provider, providerModels]) => (
|
||||
<div key={provider}>
|
||||
<CommandSeparator />
|
||||
<CommandGroup heading={provider}>
|
||||
{providerModels.map((model) => (
|
||||
<CommandItem
|
||||
key={model.fullId}
|
||||
value={model.fullId}
|
||||
onSelect={() => handleSelect(model.fullId)}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<Check
|
||||
className={cn(
|
||||
"mr-2 h-4 w-4",
|
||||
value === model.fullId ? "opacity-100" : "opacity-0"
|
||||
{!isLoading && Object.entries(modelsByProvider).map(([providerId, providerModels]) => {
|
||||
const providerInfo = getProviderInfo(providerId);
|
||||
|
||||
return (
|
||||
<div key={providerId}>
|
||||
<CommandSeparator />
|
||||
<CommandGroup heading={providerInfo.displayName}>
|
||||
{providerModels.map((model) => (
|
||||
<CommandItem
|
||||
key={model.fullId}
|
||||
value={model.fullId}
|
||||
onSelect={() => handleSelect(model.fullId)}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<Check
|
||||
className={cn(
|
||||
"mr-2 h-4 w-4",
|
||||
value === model.fullId ? "opacity-100" : "opacity-0"
|
||||
)}
|
||||
/>
|
||||
{providerInfo.baseURL ? (
|
||||
<ExternalFavicon
|
||||
url={providerInfo.baseURL}
|
||||
size={16}
|
||||
fallback={<Bot size={16} />}
|
||||
className="mr-2 flex-shrink-0"
|
||||
/>
|
||||
) : (
|
||||
<Bot size={16} className="mr-2 flex-shrink-0" />
|
||||
)}
|
||||
/>
|
||||
<span className="truncate flex-1">{model.fullId}</span>
|
||||
{model.pricing && (
|
||||
<ModelPricing pricing={model.pricing} className="ml-2" />
|
||||
)}
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</div>
|
||||
))}
|
||||
<span className="truncate flex-1">{model.name || model.id}</span>
|
||||
{model.pricing && (
|
||||
<ModelPricing pricing={model.pricing} className="ml-2" />
|
||||
)}
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Custom model option and manage providers - moved to bottom */}
|
||||
<CommandSeparator />
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useEffect } from 'react';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useContacts } from '@/hooks/useContacts';
|
||||
|
||||
/**
|
||||
* NostrSync - Syncs user's Nostr data
|
||||
@@ -15,6 +16,9 @@ export function NostrSync() {
|
||||
const { user } = useCurrentUser();
|
||||
const { config, updateConfig } = useAppContext();
|
||||
|
||||
// Prewarm user's follow list
|
||||
useContacts(user?.pubkey);
|
||||
|
||||
useEffect(() => {
|
||||
if (!user) return;
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ const mockUseAICredits = vi.mocked(useAICredits);
|
||||
describe('OnboardingCreditsBadge', () => {
|
||||
const mockProvider = {
|
||||
id: 'shakespeare',
|
||||
name: 'Shakespeare',
|
||||
baseURL: 'https://ai.shakespeare.diy/v1',
|
||||
nostr: true,
|
||||
};
|
||||
|
||||
@@ -23,6 +23,7 @@ import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { LoginArea } from '@/components/auth/LoginArea';
|
||||
import { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
interface OnboardingDialogProps {
|
||||
open: boolean;
|
||||
@@ -57,15 +58,21 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
selectedProvider && selectedProvider.nostr && user
|
||||
? {
|
||||
id: selectedProvider.id,
|
||||
name: selectedProvider.name,
|
||||
baseURL: selectedProvider.baseURL,
|
||||
nostr: selectedProvider.nostr,
|
||||
}
|
||||
: { id: '', baseURL: '', nostr: undefined }
|
||||
: { id: '', name: '', baseURL: '', nostr: undefined }
|
||||
);
|
||||
|
||||
// Filter models to only show selected provider models
|
||||
// Also filter to only show text models (modalities absent or includes "text")
|
||||
const providerModels = selectedProvider
|
||||
? models.filter(model => model.provider === selectedProvider.id)
|
||||
? models.filter(model =>
|
||||
model.provider === selectedProvider.id &&
|
||||
model.type !== 'image' &&
|
||||
(!model.modalities || model.modalities.includes('text'))
|
||||
)
|
||||
: [];
|
||||
|
||||
// Filter models by search query
|
||||
@@ -122,8 +129,9 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
}
|
||||
|
||||
// Add selected provider to their config
|
||||
const providerConfig = {
|
||||
const providerConfig: AIProvider = {
|
||||
id: selectedProvider.id,
|
||||
name: selectedProvider.name,
|
||||
baseURL: selectedProvider.baseURL,
|
||||
nostr: selectedProvider.nostr || undefined,
|
||||
apiKey: requiresApiKey ? providerApiKey.trim() : undefined,
|
||||
@@ -151,8 +159,9 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
}
|
||||
|
||||
// Add selected provider to their config
|
||||
const providerConfig = {
|
||||
const providerConfig: AIProvider = {
|
||||
id: selectedProvider.id,
|
||||
name: selectedProvider.name,
|
||||
baseURL: selectedProvider.baseURL,
|
||||
nostr: selectedProvider.nostr || undefined,
|
||||
};
|
||||
@@ -726,6 +735,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
}}
|
||||
provider={{
|
||||
id: selectedProvider.id,
|
||||
name: selectedProvider.name,
|
||||
baseURL: selectedProvider.baseURL,
|
||||
nostr: selectedProvider.nostr || undefined,
|
||||
}}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useRegisterSW } from 'virtual:pwa-register/react';
|
||||
import { Sparkles } from 'lucide-react';
|
||||
import { Sparkles, X } from 'lucide-react';
|
||||
|
||||
/**
|
||||
* Component that prompts users to update when a new service worker is available
|
||||
@@ -52,22 +52,38 @@ export function PWAUpdatePrompt() {
|
||||
updateServiceWorker(true);
|
||||
};
|
||||
|
||||
const handleDismiss = (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
setShowPrompt(false);
|
||||
};
|
||||
|
||||
if (!showPrompt) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed bottom-4 left-1/2 -translate-x-1/2 md:top-4 md:right-4 md:bottom-auto md:left-auto md:translate-x-0 z-50 animate-in slide-in-from-bottom-4 md:slide-in-from-top-4 duration-500 max-w-full">
|
||||
<button
|
||||
onClick={handleUpdate}
|
||||
disabled={isUpdating}
|
||||
className="group relative flex items-center gap-2 px-4 py-2.5 bg-gradient-to-r from-amber-100 to-yellow-100 dark:from-amber-900 dark:to-yellow-900 border border-amber-300 dark:border-amber-700 rounded-full shadow-lg hover:shadow-xl transition-all duration-300 hover:scale-105 active:scale-95 disabled:cursor-not-allowed disabled:hover:scale-100 max-w-full truncate"
|
||||
>
|
||||
<Sparkles className={`h-4 w-4 text-amber-600 dark:text-amber-400 ${isUpdating ? 'animate-spin' : 'group-hover:rotate-12 transition-transform duration-300'}`} />
|
||||
<span className="text-sm font-medium whitespace-nowrap max-w-full truncate text-amber-900 dark:text-amber-100">
|
||||
{isUpdating ? 'Updating...' : 'Update available — Click to refresh'}
|
||||
</span>
|
||||
</button>
|
||||
<div className="relative group">
|
||||
<button
|
||||
onClick={handleUpdate}
|
||||
disabled={isUpdating}
|
||||
className={`relative flex items-center gap-2 px-4 py-2.5 ${!isUpdating ? 'pr-10' : ''} bg-gradient-to-r from-amber-100 to-yellow-100 dark:from-amber-900 dark:to-yellow-900 border border-amber-300 dark:border-amber-700 rounded-full shadow-lg hover:shadow-xl transition-all duration-300 hover:scale-105 active:scale-95 disabled:cursor-not-allowed disabled:hover:scale-100 max-w-full truncate`}
|
||||
>
|
||||
<Sparkles className={`h-4 w-4 text-amber-600 dark:text-amber-400 ${isUpdating ? 'animate-spin' : 'group-hover:rotate-12 transition-transform duration-300'}`} />
|
||||
<span className="text-sm font-medium whitespace-nowrap max-w-full truncate text-amber-900 dark:text-amber-100">
|
||||
{isUpdating ? 'Updating...' : 'Update available — Click to refresh'}
|
||||
</span>
|
||||
</button>
|
||||
{!isUpdating && (
|
||||
<button
|
||||
onClick={handleDismiss}
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 p-1 rounded-full hover:bg-amber-200 dark:hover:bg-amber-800 transition-colors duration-200"
|
||||
aria-label="Dismiss update notification"
|
||||
>
|
||||
<X className="h-4 w-4 text-amber-700 dark:text-amber-300" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,20 +1,21 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Puzzle, Plus, Trash2, RefreshCw, Loader2, Check } from 'lucide-react';
|
||||
import { Puzzle, Plus, Trash2, RefreshCw, Loader2, Check, Compass } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { usePlugins } from '@/hooks/usePlugins';
|
||||
import { usePluginGitInfo } from '@/hooks/usePluginGitInfo';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { DiscoverPluginsDialog } from '@/components/DiscoverPluginsDialog';
|
||||
|
||||
export function PluginsSection() {
|
||||
const { t } = useTranslation();
|
||||
const { toast } = useToast();
|
||||
const { plugins, skills, clonePlugin, syncPlugin, deletePlugin, getPluginGitInfo } = usePlugins();
|
||||
const { plugins, skills, clonePlugin, syncPlugin, deletePlugin } = usePlugins();
|
||||
const [gitUrl, setGitUrl] = useState('');
|
||||
const [showDiscoverDialog, setShowDiscoverDialog] = useState(false);
|
||||
|
||||
const handleAddPlugin = async () => {
|
||||
if (!gitUrl.trim()) return;
|
||||
@@ -78,14 +79,22 @@ export function PluginsSection() {
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Divider */}
|
||||
<Separator className="my-6" />
|
||||
|
||||
{/* Plugins Header */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Puzzle className="h-5 w-5 text-primary" />
|
||||
<h3 className="text-lg font-semibold">{t('plugins')}</h3>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Puzzle className="h-5 w-5 text-primary" />
|
||||
<h3 className="text-lg font-semibold">{t('plugins')}</h3>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setShowDiscoverDialog(true)}
|
||||
className="gap-2"
|
||||
>
|
||||
<Compass className="h-4 w-4" />
|
||||
{t('discoverPlugins')}
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('pluginsDescription')}
|
||||
@@ -93,7 +102,7 @@ export function PluginsSection() {
|
||||
</div>
|
||||
|
||||
{/* Configured Plugins List */}
|
||||
{plugins.length > 0 ? (
|
||||
{plugins.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
{plugins.map((pluginName) => {
|
||||
const pluginSkills = skillsByPlugin[pluginName] || [];
|
||||
@@ -108,21 +117,14 @@ export function PluginsSection() {
|
||||
isDeleting={isDeleting}
|
||||
onSync={handleSyncPlugin}
|
||||
onDelete={handleDeletePlugin}
|
||||
getPluginGitInfo={getPluginGitInfo}
|
||||
/>;
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<Alert>
|
||||
<AlertDescription className="text-sm">
|
||||
{t('noPluginsConfigured')}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Add Plugin Section */}
|
||||
<Accordion type="single" collapsible className="w-full">
|
||||
<AccordionItem value="add-plugin" className="border rounded-lg">
|
||||
<AccordionItem value="add-plugin">
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<div className="flex items-center gap-2">
|
||||
<Plus className="h-4 w-4" />
|
||||
@@ -132,7 +134,9 @@ export function PluginsSection() {
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
<div className="space-y-3">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="plugin-git-url">{t('gitRepositoryUrl')}</Label>
|
||||
<Label htmlFor="plugin-git-url">
|
||||
{t('gitRepositoryUrl')} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="plugin-git-url"
|
||||
placeholder="https://github.com/user/plugin.git"
|
||||
@@ -169,6 +173,12 @@ export function PluginsSection() {
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
|
||||
{/* Discover Plugins Dialog */}
|
||||
<DiscoverPluginsDialog
|
||||
open={showDiscoverDialog}
|
||||
onOpenChange={setShowDiscoverDialog}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -180,19 +190,18 @@ interface PluginItemProps {
|
||||
isDeleting: boolean;
|
||||
onSync: (pluginName: string) => void;
|
||||
onDelete: (pluginName: string) => void;
|
||||
getPluginGitInfo: (pluginName: string) => { data: { commitHash: string; commitDate: Date; commitMessage: string } | null | undefined; isLoading: boolean };
|
||||
}
|
||||
|
||||
function PluginItem({ pluginName, pluginSkills, isSyncing, isDeleting, onSync, onDelete, getPluginGitInfo }: PluginItemProps) {
|
||||
function PluginItem({ pluginName, pluginSkills, isSyncing, isDeleting, onSync, onDelete }: PluginItemProps) {
|
||||
const { t } = useTranslation();
|
||||
const { data: gitInfo } = getPluginGitInfo(pluginName);
|
||||
const { data: gitInfo } = usePluginGitInfo(pluginName);
|
||||
|
||||
return (
|
||||
<Accordion type="single" collapsible className="w-full">
|
||||
<AccordionItem value={pluginName} className="border rounded-lg">
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<div className="flex items-center gap-2">
|
||||
<Puzzle className="h-4 w-4 text-primary" />
|
||||
<Puzzle className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="font-medium">{pluginName}</span>
|
||||
{pluginSkills.length > 0 && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
@@ -225,14 +234,6 @@ function PluginItem({ pluginName, pluginSkills, isSyncing, isDeleting, onSync, o
|
||||
</div>
|
||||
)}
|
||||
|
||||
{pluginSkills.length === 0 && (
|
||||
<Alert>
|
||||
<AlertDescription className="text-xs">
|
||||
{t('noSkillsFound')}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Plugin Actions and Git Info */}
|
||||
<div className="space-y-2 pt-2">
|
||||
{gitInfo && (
|
||||
|
||||
@@ -33,9 +33,14 @@ import {
|
||||
Loader2,
|
||||
Trash2,
|
||||
Save,
|
||||
DollarSign,
|
||||
ExternalLink,
|
||||
FileCode,
|
||||
} from 'lucide-react';
|
||||
import JSZip from 'jszip';
|
||||
import { Separator } from './ui/separator';
|
||||
import { DotAI } from '@/lib/DotAI';
|
||||
import { LabelSelector } from '@/components/labels/LabelSelector';
|
||||
|
||||
interface ProjectDetailsDialogProps {
|
||||
project: Project;
|
||||
@@ -49,6 +54,8 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
const [isRenaming, setIsRenaming] = useState(false);
|
||||
const [newProjectName, setNewProjectName] = useState(project.id);
|
||||
const [totalCost, setTotalCost] = useState<number | null>(null);
|
||||
const [templateInfo, setTemplateInfo] = useState<{ name: string; description: string; url: string } | null>(null);
|
||||
const { toast } = useToast();
|
||||
const { fs } = useFS();
|
||||
const { projectsPath } = useFSPaths();
|
||||
@@ -62,6 +69,31 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
|
||||
setIsRenaming(false);
|
||||
}, [project.id]);
|
||||
|
||||
// Load total project cost and template info
|
||||
useEffect(() => {
|
||||
const loadProjectData = async () => {
|
||||
try {
|
||||
const dotAI = new DotAI(fs, `${projectsPath}/${project.id}`);
|
||||
|
||||
// Load cost
|
||||
const cost = await dotAI.readCost();
|
||||
setTotalCost(cost);
|
||||
|
||||
// Load template info
|
||||
const template = await dotAI.readTemplate();
|
||||
setTemplateInfo(template);
|
||||
} catch (error) {
|
||||
console.warn('Failed to load project data:', error);
|
||||
setTotalCost(null);
|
||||
setTemplateInfo(null);
|
||||
}
|
||||
};
|
||||
|
||||
if (open) {
|
||||
loadProjectData();
|
||||
}
|
||||
}, [fs, projectsPath, project.id, open]);
|
||||
|
||||
const formatDistanceToNow = (date: Date) => {
|
||||
const now = new Date();
|
||||
const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);
|
||||
@@ -213,7 +245,7 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
|
||||
<DialogContent className="max-w-md" onOpenAutoFocus={(e) => e.preventDefault()}>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Folder className="h-5 w-5" />
|
||||
<Folder className="h-5 w-5 text-primary" />
|
||||
{project.name}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
@@ -226,6 +258,32 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
|
||||
<span>{formatDistanceToNow(project.lastModified)}</span>
|
||||
</div>
|
||||
|
||||
{/* Total Cost */}
|
||||
{totalCost !== null && totalCost > 0 && (
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<DollarSign className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-muted-foreground">Total Cost:</span>
|
||||
<span className="font-mono">${totalCost.toFixed(2)}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Template Info */}
|
||||
{templateInfo && (
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<FileCode className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-muted-foreground">Template:</span>
|
||||
<a
|
||||
href={templateInfo.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center gap-1 text-primary hover:underline"
|
||||
>
|
||||
{templateInfo.name}
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Project Name */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="project-name">Project Name</Label>
|
||||
@@ -260,6 +318,9 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Labels */}
|
||||
<LabelSelector projectId={project.id} />
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Export Project Button */}
|
||||
|
||||
@@ -1,27 +1,40 @@
|
||||
import React, { useEffect } from 'react';
|
||||
import React, { useEffect, useState, useMemo } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle } from 'lucide-react';
|
||||
import { Plus, Folder, GitBranch, Loader2, ChevronDown, ChevronRight, Star, Columns2, X, Settings, HelpCircle, Search, Tag, Folders } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
|
||||
import { useProjects } from '@/hooks/useProjects';
|
||||
import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { useLabels } from '@/hooks/useLabels';
|
||||
import { getLabelColor } from '@/lib/labels';
|
||||
import { useProjectLabels } from '@/hooks/useProjectLabels';
|
||||
import type { Project } from '@/lib/ProjectsManager';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
||||
import { LabelsManageDialog } from '@/components/labels/LabelsManageDialog';
|
||||
|
||||
interface ProjectItemProps {
|
||||
project: Project;
|
||||
isSelected: boolean;
|
||||
onSelect: (project: Project) => void;
|
||||
isFavorite?: boolean;
|
||||
labelColor?: string;
|
||||
}
|
||||
|
||||
const ProjectItem: React.FC<ProjectItemProps> = ({ project, isSelected, onSelect, isFavorite }) => {
|
||||
const ProjectItem: React.FC<ProjectItemProps> = ({
|
||||
project,
|
||||
isSelected,
|
||||
onSelect,
|
||||
isFavorite,
|
||||
labelColor,
|
||||
}) => {
|
||||
const navigate = useNavigate();
|
||||
const { hasRunningSessions } = useProjectSessionStatus(project.id);
|
||||
|
||||
@@ -30,6 +43,15 @@ const ProjectItem: React.FC<ProjectItemProps> = ({ project, isSelected, onSelect
|
||||
navigate(`/project/${project.id}`);
|
||||
};
|
||||
|
||||
// Determine folder icon color - always show colored icons when label exists
|
||||
const getFolderColorClass = () => {
|
||||
if (labelColor) {
|
||||
const colorConfig = getLabelColor(labelColor as Parameters<typeof getLabelColor>[0]);
|
||||
return colorConfig.text;
|
||||
}
|
||||
return 'text-primary';
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
@@ -47,7 +69,7 @@ const ProjectItem: React.FC<ProjectItemProps> = ({ project, isSelected, onSelect
|
||||
{hasRunningSessions ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-blue-600 dark:text-blue-400" />
|
||||
) : (
|
||||
<Folder className="h-4 w-4 text-primary" />
|
||||
<Folder className={cn("h-4 w-4", getFolderColorClass())} />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex justify-between gap-2 flex-1 min-w-0">
|
||||
@@ -59,10 +81,8 @@ const ProjectItem: React.FC<ProjectItemProps> = ({ project, isSelected, onSelect
|
||||
|
||||
{/* Star indicator - only shown when favorited */}
|
||||
{isFavorite && (
|
||||
<div className="flex-shrink-0 relative -mr-1 pointer-events-none">
|
||||
<div className="flex items-center justify-center">
|
||||
<Star className="h-4 w-4 text-yellow-500 fill-current" />
|
||||
</div>
|
||||
<div className="flex-shrink-0 relative -mr-1 pointer-events-none flex items-center justify-center">
|
||||
<Star className="h-4 w-4 text-yellow-500 fill-current" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -74,6 +94,78 @@ const ProjectItem: React.FC<ProjectItemProps> = ({ project, isSelected, onSelect
|
||||
|
||||
ProjectItem.displayName = 'ProjectItem';
|
||||
|
||||
/** Label group header component */
|
||||
interface LabelGroupHeaderProps {
|
||||
labelName: string;
|
||||
labelColor: string;
|
||||
isCollapsed: boolean;
|
||||
onToggle: () => void;
|
||||
projectCount?: number;
|
||||
}
|
||||
|
||||
const LabelGroupHeader: React.FC<LabelGroupHeaderProps> = ({
|
||||
labelName,
|
||||
labelColor,
|
||||
isCollapsed,
|
||||
onToggle,
|
||||
projectCount = 0,
|
||||
}) => {
|
||||
const colorConfig = getLabelColor(labelColor as Parameters<typeof getLabelColor>[0]);
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={onToggle}
|
||||
className="w-full flex items-center gap-2 py-1.5 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<Tag className={cn("h-3.5 w-3.5", colorConfig.text)} />
|
||||
<span className="flex-1 text-left truncate">{labelName}</span>
|
||||
{isCollapsed && projectCount > 0 && (
|
||||
<span className="text-xs text-muted-foreground/70">
|
||||
{projectCount}
|
||||
</span>
|
||||
)}
|
||||
<ChevronRight className={cn(
|
||||
"h-3.5 w-3.5 transition-transform duration-200",
|
||||
!isCollapsed && "rotate-90"
|
||||
)} />
|
||||
</button>
|
||||
);
|
||||
};
|
||||
|
||||
/** Other projects group header component */
|
||||
interface OtherProjectsGroupHeaderProps {
|
||||
isCollapsed: boolean;
|
||||
onToggle: () => void;
|
||||
projectCount?: number;
|
||||
}
|
||||
|
||||
const OtherProjectsGroupHeader: React.FC<OtherProjectsGroupHeaderProps> = ({
|
||||
isCollapsed,
|
||||
onToggle,
|
||||
projectCount = 0,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={onToggle}
|
||||
className="w-full flex items-center gap-2 py-1.5 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<Folders className="h-3.5 w-3.5 text-primary" />
|
||||
<span className="flex-1 text-left truncate">{t('otherProjects')}</span>
|
||||
{isCollapsed && projectCount > 0 && (
|
||||
<span className="text-xs text-muted-foreground/70">
|
||||
{projectCount}
|
||||
</span>
|
||||
)}
|
||||
<ChevronRight className={cn(
|
||||
"h-3.5 w-3.5 transition-transform duration-200",
|
||||
!isCollapsed && "rotate-90"
|
||||
)} />
|
||||
</button>
|
||||
);
|
||||
};
|
||||
|
||||
interface ProjectSidebarProps {
|
||||
selectedProject: Project | null;
|
||||
onSelectProject: (project: Project | null) => void;
|
||||
@@ -93,10 +185,94 @@ export function ProjectSidebar({
|
||||
const queryClient = useQueryClient();
|
||||
const { data: projects = [], isLoading, error } = useProjects();
|
||||
const [favorites] = useLocalStorage<string[]>('project-favorites', []);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [otherProjectsCollapsed, setOtherProjectsCollapsed] = useLocalStorage<boolean>('other-projects-collapsed', false);
|
||||
const [labelsDialogOpen, setLabelsDialogOpen] = useState(false);
|
||||
const { labels, toggleLabelCollapsed } = useLabels();
|
||||
const { getProjectLabels, hasAnyLabels } = useProjectLabels();
|
||||
|
||||
const isMobile = useIsMobile();
|
||||
const navigate = useNavigate();
|
||||
|
||||
// Always show grouped view when labels exist and projects have labels
|
||||
const showGroupedView = labels.length > 0 && hasAnyLabels();
|
||||
|
||||
// Fast in-memory search filtering
|
||||
const filteredProjects = useMemo(() => {
|
||||
if (!searchQuery.trim()) {
|
||||
return projects;
|
||||
}
|
||||
|
||||
const query = searchQuery.toLowerCase();
|
||||
return projects.filter(project =>
|
||||
project.id.toLowerCase().includes(query) ||
|
||||
project.name.toLowerCase().includes(query)
|
||||
);
|
||||
}, [projects, searchQuery]);
|
||||
|
||||
// Group projects by label for grouped view
|
||||
const groupedProjects = useMemo(() => {
|
||||
if (!showGroupedView) return null;
|
||||
|
||||
const groups: Map<string, Project[]> = new Map();
|
||||
const unlabeled: Project[] = [];
|
||||
|
||||
// Initialize groups for each label in order
|
||||
for (const label of labels) {
|
||||
groups.set(label.id, []);
|
||||
}
|
||||
|
||||
// Sort projects into groups
|
||||
for (const project of filteredProjects) {
|
||||
const projectLabelIds = getProjectLabels(project.id);
|
||||
if (projectLabelIds.length === 0) {
|
||||
unlabeled.push(project);
|
||||
} else {
|
||||
// Add project to each label group it belongs to
|
||||
let addedToAnyGroup = false;
|
||||
for (const labelId of projectLabelIds) {
|
||||
const group = groups.get(labelId);
|
||||
if (group) {
|
||||
group.push(project);
|
||||
addedToAnyGroup = true;
|
||||
}
|
||||
}
|
||||
// If all labels were deleted, add to unlabeled
|
||||
if (!addedToAnyGroup) {
|
||||
unlabeled.push(project);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Sort each group: favorites first, then by lastModified
|
||||
const sortGroup = (projectList: Project[]) => {
|
||||
return projectList.sort((a, b) => {
|
||||
const aIsFavorite = favorites.includes(a.id);
|
||||
const bIsFavorite = favorites.includes(b.id);
|
||||
if (aIsFavorite && !bIsFavorite) return -1;
|
||||
if (!aIsFavorite && bIsFavorite) return 1;
|
||||
return b.lastModified.getTime() - a.lastModified.getTime();
|
||||
});
|
||||
};
|
||||
|
||||
for (const [labelId, projectList] of groups) {
|
||||
groups.set(labelId, sortGroup(projectList));
|
||||
}
|
||||
|
||||
return {
|
||||
groups,
|
||||
unlabeled: sortGroup(unlabeled),
|
||||
};
|
||||
}, [showGroupedView, labels, filteredProjects, getProjectLabels, favorites]);
|
||||
|
||||
// Get the first label color for a project (for colored icon display)
|
||||
const getProjectLabelColor = (projectId: string): string | undefined => {
|
||||
const projectLabelIds = getProjectLabels(projectId);
|
||||
if (projectLabelIds.length === 0) return undefined;
|
||||
const label = labels.find(l => l.id === projectLabelIds[0]);
|
||||
return label?.color;
|
||||
};
|
||||
|
||||
// Custom navigate function that closes sidebar on mobile
|
||||
const navigateAndClose = (path: string) => {
|
||||
navigate(path);
|
||||
@@ -166,12 +342,12 @@ export function ProjectSidebar({
|
||||
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<div className="p-2">
|
||||
<div className="mb-2">
|
||||
<div className="mb-2 space-y-3">
|
||||
<div className="relative rounded-md bg-gradient-to-r from-primary to-accent hover:from-primary/90 hover:to-accent/90 transition-all duration-200">
|
||||
<div className="flex">
|
||||
<button
|
||||
onClick={handleNewProject}
|
||||
className="flex-1 flex items-center justify-center px-3 py-2 text-sm font-medium text-primary-foreground rounded-l-md hover:bg-white/10 transition-colors"
|
||||
className="flex-1 flex items-center justify-center px-3 py-2.5 text-sm font-medium text-primary-foreground rounded-l-md hover:bg-white/10 transition-colors"
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
{t('newProject')}
|
||||
@@ -179,7 +355,7 @@ export function ProjectSidebar({
|
||||
<div className="w-px bg-white/20" />
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className="px-2 py-2 text-primary-foreground hover:bg-white/10 rounded-r-md transition-colors">
|
||||
<button className="px-3 py-2.5 text-primary-foreground hover:bg-white/10 rounded-r-md transition-colors">
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
@@ -191,10 +367,31 @@ export function ProjectSidebar({
|
||||
<GitBranch className="h-4 w-4" />
|
||||
{t('importRepository')}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => setLabelsDialogOpen(true)}
|
||||
className="flex items-center gap-2 w-full"
|
||||
>
|
||||
<Tag className="h-4 w-4" />
|
||||
{t('manageLabels')}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Search Input */}
|
||||
{projects.length > 0 && (
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none" />
|
||||
<Input
|
||||
type="text"
|
||||
placeholder={t('searchProjects')}
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="pl-9 h-9 text-sm bg-sidebar-accent/50 border-sidebar-border focus-visible:ring-primary/50"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
@@ -214,15 +411,99 @@ export function ProjectSidebar({
|
||||
<p className="text-sm">{t('noProjectsYet')}</p>
|
||||
<p className="text-xs">{t('createFirstProject')}</p>
|
||||
</div>
|
||||
) : (
|
||||
) : filteredProjects.length === 0 ? (
|
||||
<div className="text-center p-6 text-muted-foreground">
|
||||
<Search className="h-8 w-8 mx-auto mb-2 opacity-50" />
|
||||
<p className="text-sm">{t('noProjectsFound')}</p>
|
||||
<p className="text-xs">{t('tryDifferentSearch')}</p>
|
||||
</div>
|
||||
) : showGroupedView && groupedProjects ? (
|
||||
// Grouped view by labels
|
||||
<div className="space-y-1">
|
||||
{projects.map((project) => (
|
||||
{/* Render each label group */}
|
||||
{labels.map((label) => {
|
||||
const groupProjects = groupedProjects.groups.get(label.id) || [];
|
||||
if (groupProjects.length === 0) return null;
|
||||
|
||||
return (
|
||||
<Collapsible
|
||||
key={label.id}
|
||||
open={!label.collapsed}
|
||||
onOpenChange={() => toggleLabelCollapsed(label.id)}
|
||||
>
|
||||
<CollapsibleTrigger asChild>
|
||||
<div>
|
||||
<LabelGroupHeader
|
||||
labelName={label.name}
|
||||
labelColor={label.color}
|
||||
isCollapsed={!!label.collapsed}
|
||||
onToggle={() => toggleLabelCollapsed(label.id)}
|
||||
projectCount={groupProjects.length}
|
||||
/>
|
||||
</div>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
<div className="space-y-0.5">
|
||||
{groupProjects.map((project) => (
|
||||
<ProjectItem
|
||||
key={project.id}
|
||||
project={project}
|
||||
isSelected={selectedProject?.id === project.id}
|
||||
onSelect={onSelectProject}
|
||||
isFavorite={favorites.includes(project.id)}
|
||||
labelColor={label.color}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Other projects (unlabeled) */}
|
||||
{groupedProjects.unlabeled.length > 0 && (
|
||||
<div className="mt-2">
|
||||
<Collapsible
|
||||
open={!otherProjectsCollapsed}
|
||||
onOpenChange={() => setOtherProjectsCollapsed(!otherProjectsCollapsed)}
|
||||
>
|
||||
<CollapsibleTrigger asChild>
|
||||
<div>
|
||||
<OtherProjectsGroupHeader
|
||||
isCollapsed={otherProjectsCollapsed}
|
||||
onToggle={() => setOtherProjectsCollapsed(!otherProjectsCollapsed)}
|
||||
projectCount={groupedProjects.unlabeled.length}
|
||||
/>
|
||||
</div>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
<div className="space-y-0.5">
|
||||
{groupedProjects.unlabeled.map((project) => (
|
||||
<ProjectItem
|
||||
key={project.id}
|
||||
project={project}
|
||||
isSelected={selectedProject?.id === project.id}
|
||||
onSelect={onSelectProject}
|
||||
isFavorite={favorites.includes(project.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
// Flat view (default)
|
||||
<div className="space-y-1">
|
||||
{filteredProjects.map((project) => (
|
||||
<ProjectItem
|
||||
key={project.id}
|
||||
project={project}
|
||||
isSelected={selectedProject?.id === project.id}
|
||||
onSelect={onSelectProject}
|
||||
isFavorite={favorites.includes(project.id)}
|
||||
labelColor={getProjectLabelColor(project.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -253,6 +534,12 @@ export function ProjectSidebar({
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Labels Management Dialog */}
|
||||
<LabelsManageDialog
|
||||
open={labelsDialogOpen}
|
||||
onOpenChange={setLabelsDialogOpen}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { FileCode2, Trash2, Plus, GripVertical, RotateCcw } from 'lucide-react';
|
||||
import {
|
||||
DndContext,
|
||||
closestCenter,
|
||||
KeyboardSensor,
|
||||
PointerSensor,
|
||||
useSensor,
|
||||
useSensors,
|
||||
type DragEndEvent,
|
||||
} from '@dnd-kit/core';
|
||||
import {
|
||||
arrayMove,
|
||||
SortableContext,
|
||||
sortableKeyboardCoordinates,
|
||||
verticalListSortingStrategy,
|
||||
} from '@dnd-kit/sortable';
|
||||
import {
|
||||
useSortable,
|
||||
} from '@dnd-kit/sortable';
|
||||
import { CSS } from '@dnd-kit/utilities';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
|
||||
interface ProjectTemplate {
|
||||
name: string;
|
||||
description: string;
|
||||
url: string;
|
||||
}
|
||||
|
||||
interface SortableTemplateItemProps {
|
||||
template: ProjectTemplate;
|
||||
index: number;
|
||||
onRemove: (index: number) => void;
|
||||
onUpdate: (index: number, template: ProjectTemplate) => void;
|
||||
showDragHandle: boolean;
|
||||
isOnlyTemplate: boolean;
|
||||
}
|
||||
|
||||
function SortableTemplateItem({
|
||||
template,
|
||||
index,
|
||||
onRemove,
|
||||
onUpdate,
|
||||
showDragHandle,
|
||||
isOnlyTemplate,
|
||||
}: SortableTemplateItemProps) {
|
||||
const { t } = useTranslation();
|
||||
const {
|
||||
attributes,
|
||||
listeners,
|
||||
setNodeRef,
|
||||
transform,
|
||||
transition,
|
||||
isDragging,
|
||||
} = useSortable({ id: `template-${index}` });
|
||||
|
||||
const style = {
|
||||
transform: CSS.Transform.toString(transform),
|
||||
transition,
|
||||
opacity: isDragging ? 0.5 : 1,
|
||||
};
|
||||
|
||||
return (
|
||||
<AccordionItem
|
||||
ref={setNodeRef}
|
||||
style={style}
|
||||
value={`template-${index}`}
|
||||
className="border rounded-lg"
|
||||
>
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<div className="flex items-center gap-2 w-full mr-3">
|
||||
{showDragHandle && (
|
||||
<div
|
||||
{...attributes}
|
||||
{...listeners}
|
||||
className="cursor-grab active:cursor-grabbing p-1 -ml-1 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<GripVertical className="h-4 w-4" />
|
||||
</div>
|
||||
)}
|
||||
<FileCode2 size={16} className="text-muted-foreground" />
|
||||
<span className="font-medium">{template.name}</span>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
<div className="space-y-3">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`template-name-${index}`}>
|
||||
{t('templateName')} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id={`template-name-${index}`}
|
||||
placeholder="MKStack"
|
||||
value={template.name}
|
||||
onChange={(e) => onUpdate(index, { ...template, name: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`template-description-${index}`}>
|
||||
{t('templateDescription')} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Textarea
|
||||
id={`template-description-${index}`}
|
||||
placeholder="Build Nostr clients with React."
|
||||
value={template.description}
|
||||
onChange={(e) => onUpdate(index, { ...template, description: e.target.value })}
|
||||
className="min-h-[80px]"
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`template-url-${index}`}>
|
||||
{t('templateGitUrl')} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id={`template-url-${index}`}
|
||||
type="url"
|
||||
placeholder="https://gitlab.com/soapbox-pub/mkstack.git"
|
||||
value={template.url}
|
||||
onChange={(e) => onUpdate(index, { ...template, url: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={() => onRemove(index)}
|
||||
disabled={isOnlyTemplate}
|
||||
title={isOnlyTemplate ? t('atLeastOneTemplateRequired') : t('delete')}
|
||||
>
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
{t('delete')}
|
||||
</Button>
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
);
|
||||
}
|
||||
|
||||
export function ProjectTemplatesSection() {
|
||||
const { t } = useTranslation();
|
||||
const { config, defaultConfig, updateConfig } = useAppContext();
|
||||
const { toast } = useToast();
|
||||
const [newTemplateName, setNewTemplateName] = useState('');
|
||||
const [newTemplateDescription, setNewTemplateDescription] = useState('');
|
||||
const [newTemplateUrl, setNewTemplateUrl] = useState('');
|
||||
|
||||
const templates = config.templates || [];
|
||||
const defaultTemplates = defaultConfig.templates || [];
|
||||
|
||||
const sensors = useSensors(
|
||||
useSensor(PointerSensor),
|
||||
useSensor(KeyboardSensor, {
|
||||
coordinateGetter: sortableKeyboardCoordinates,
|
||||
})
|
||||
);
|
||||
|
||||
// Check if current templates match the default configuration
|
||||
const templatesMatchDefault = JSON.stringify(templates) === JSON.stringify(defaultTemplates);
|
||||
|
||||
const handleAddTemplate = () => {
|
||||
if (!newTemplateName.trim() || !newTemplateDescription.trim() || !newTemplateUrl.trim()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const newTemplate: ProjectTemplate = {
|
||||
name: newTemplateName.trim(),
|
||||
description: newTemplateDescription.trim(),
|
||||
url: newTemplateUrl.trim(),
|
||||
};
|
||||
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
templates: [...(current.templates || []), newTemplate],
|
||||
}));
|
||||
|
||||
toast({
|
||||
title: t('templateAdded'),
|
||||
description: t('templateAddedDescription', { name: newTemplateName.trim() }),
|
||||
});
|
||||
|
||||
setNewTemplateName('');
|
||||
setNewTemplateDescription('');
|
||||
setNewTemplateUrl('');
|
||||
};
|
||||
|
||||
const handleRemoveTemplate = (index: number) => {
|
||||
const templateName = templates[index]?.name || 'template';
|
||||
const newTemplates = templates.filter((_, i) => i !== index);
|
||||
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
templates: newTemplates,
|
||||
}));
|
||||
|
||||
toast({
|
||||
title: t('templateDeleted'),
|
||||
description: t('templateDeletedDescription', { name: templateName }),
|
||||
});
|
||||
};
|
||||
|
||||
const handleUpdateTemplate = (index: number, updatedTemplate: ProjectTemplate) => {
|
||||
const newTemplates = [...templates];
|
||||
newTemplates[index] = updatedTemplate;
|
||||
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
templates: newTemplates,
|
||||
}));
|
||||
};
|
||||
|
||||
const handleDragEnd = (event: DragEndEvent) => {
|
||||
const { active, over } = event;
|
||||
|
||||
if (active.id !== over?.id) {
|
||||
const oldIndex = parseInt(active.id.toString().replace('template-', ''));
|
||||
const newIndex = parseInt(over?.id.toString().replace('template-', '') || '0');
|
||||
|
||||
if (!isNaN(oldIndex) && !isNaN(newIndex) && oldIndex !== newIndex) {
|
||||
const newTemplates = arrayMove(templates, oldIndex, newIndex);
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
templates: newTemplates,
|
||||
}));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleResetToDefaults = () => {
|
||||
// Remove the templates from local config so defaults take precedence
|
||||
updateConfig((current) => {
|
||||
const { templates: _, ...rest } = current;
|
||||
return rest;
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Project Templates Header */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<FileCode2 className="h-5 w-5 text-primary" />
|
||||
<h3 className="text-lg font-semibold">{t('projectTemplates')}</h3>
|
||||
{!templatesMatchDefault && (
|
||||
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
|
||||
)}
|
||||
{!templatesMatchDefault && (
|
||||
<button
|
||||
onClick={handleResetToDefaults}
|
||||
title={t('restoreToDefault')}
|
||||
className="ml-auto p-1 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<RotateCcw className="h-4 w-4" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('projectTemplatesDescription')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Configured Templates List */}
|
||||
{templates.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
collisionDetection={closestCenter}
|
||||
onDragEnd={handleDragEnd}
|
||||
>
|
||||
<SortableContext
|
||||
items={templates.map((_, index) => `template-${index}`)}
|
||||
strategy={verticalListSortingStrategy}
|
||||
>
|
||||
<Accordion type="multiple" className="w-full space-y-2">
|
||||
{templates.map((template, index) => (
|
||||
<SortableTemplateItem
|
||||
key={index}
|
||||
template={template}
|
||||
index={index}
|
||||
onRemove={handleRemoveTemplate}
|
||||
onUpdate={handleUpdateTemplate}
|
||||
showDragHandle={templates.length > 1}
|
||||
isOnlyTemplate={templates.length === 1}
|
||||
/>
|
||||
))}
|
||||
</Accordion>
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Add New Template */}
|
||||
<Accordion type="single" collapsible className="w-full">
|
||||
<AccordionItem value="add-template">
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<div className="flex items-center gap-2">
|
||||
<Plus className="h-4 w-4" />
|
||||
<span className="text-sm font-medium">{t('addProjectTemplate')}</span>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
<div className="space-y-3">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="new-template-name">
|
||||
{t('templateName')} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="new-template-name"
|
||||
placeholder="MKStack"
|
||||
value={newTemplateName}
|
||||
onChange={(e) => setNewTemplateName(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="new-template-description">
|
||||
{t('templateDescription')} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Textarea
|
||||
id="new-template-description"
|
||||
placeholder="Build Nostr clients with React."
|
||||
value={newTemplateDescription}
|
||||
onChange={(e) => setNewTemplateDescription(e.target.value)}
|
||||
className="min-h-[80px]"
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="new-template-url">
|
||||
{t('templateGitUrl')} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="new-template-url"
|
||||
type="url"
|
||||
placeholder="https://gitlab.com/soapbox-pub/mkstack.git"
|
||||
value={newTemplateUrl}
|
||||
onChange={(e) => setNewTemplateUrl(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
onClick={handleAddTemplate}
|
||||
disabled={!newTemplateName.trim() || !newTemplateDescription.trim() || !newTemplateUrl.trim()}
|
||||
className="gap-2 w-full"
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
{t('add')}
|
||||
</Button>
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+93
-32
@@ -1,4 +1,4 @@
|
||||
import { APIError } from 'openai';
|
||||
import { APIConnectionError, APIError } from 'openai';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { X } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -11,6 +11,8 @@ import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
|
||||
import { useState } from 'react';
|
||||
import { MalformedToolCallError } from '@/lib/errors/MalformedToolCallError';
|
||||
import { EmptyMessageError } from '@/lib/errors/EmptyMessageError';
|
||||
import { AIProvider } from '@/contexts/AISettingsContext';
|
||||
import { useOffline } from '@/hooks/useOffline';
|
||||
|
||||
export interface QuillyProps {
|
||||
error: Error;
|
||||
@@ -30,23 +32,21 @@ interface ErrorBody {
|
||||
}>;
|
||||
}
|
||||
|
||||
export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTryAgain, onRequestConsoleErrorHelp, providerModel }: QuillyProps) {
|
||||
interface QuillyContentProps {
|
||||
error: Error;
|
||||
onDismiss: () => void;
|
||||
onNewChat: () => void;
|
||||
onOpenModelSelector: () => void;
|
||||
onTryAgain?: () => void;
|
||||
onRequestConsoleErrorHelp?: (error: ProjectPreviewConsoleError) => void;
|
||||
provider: AIProvider | undefined;
|
||||
}
|
||||
|
||||
function QuillyContent({ error, onDismiss, onNewChat, onOpenModelSelector, onTryAgain, onRequestConsoleErrorHelp, provider }: QuillyContentProps) {
|
||||
const navigate = useNavigate();
|
||||
const { settings } = useAISettings();
|
||||
const { isOffline } = useOffline();
|
||||
|
||||
// Handle empty provider model gracefully
|
||||
let provider;
|
||||
try {
|
||||
provider = parseProviderModel(providerModel, settings.providers).provider;
|
||||
} catch {
|
||||
// If no valid provider model, use a default or undefined
|
||||
provider = undefined;
|
||||
}
|
||||
|
||||
const credits = useAICredits(provider || { id: '', name: '', apiKey: '', nostr: false });
|
||||
const [showCreditsDialog, setShowCreditsDialog] = useState(false);
|
||||
|
||||
const renderBody = (error: Error | APIError | MalformedToolCallError | ProjectPreviewConsoleError): ErrorBody => {
|
||||
const renderBody = (error: Error | APIError | MalformedToolCallError | ProjectPreviewConsoleError): ErrorBody & { showCreditsButton?: boolean } => {
|
||||
// Handle Project Preview Console Errors
|
||||
if (error instanceof ProjectPreviewConsoleError) {
|
||||
return {
|
||||
@@ -69,7 +69,7 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
|
||||
onClick: onOpenModelSelector,
|
||||
}],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (error instanceof EmptyMessageError) {
|
||||
return {
|
||||
@@ -101,13 +101,12 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
|
||||
};
|
||||
|
||||
case error.code === 'insufficient_quota': {
|
||||
if (credits.data) {
|
||||
// Only show credits dialog if we have a provider with nostr enabled
|
||||
if (provider?.nostr) {
|
||||
return {
|
||||
message: `Your account has $${credits.data.amount.toFixed(2)} credits. Please add credits to keep creating.`,
|
||||
actions: [{
|
||||
label: 'Add credits',
|
||||
onClick: () => setShowCreditsDialog(true),
|
||||
}],
|
||||
message: 'Your account is low on credits. Please add credits to keep creating.',
|
||||
showCreditsButton: true,
|
||||
actions: [],
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
@@ -186,25 +185,40 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
|
||||
message: 'The AI service is temporarily unavailable. Please try again in a moment.',
|
||||
actions: [],
|
||||
};
|
||||
|
||||
default:
|
||||
return {
|
||||
message: `AI service error: ${error.message}`,
|
||||
actions: [],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (error instanceof APIConnectionError) {
|
||||
return {
|
||||
message: isOffline
|
||||
? 'It appears you are offline. Have you tried connecting to the internet?'
|
||||
: 'There was a network problem between your device and the AI service.',
|
||||
actions: onTryAgain ? [{
|
||||
label: 'Try again',
|
||||
onClick: () => {
|
||||
onTryAgain();
|
||||
onDismiss();
|
||||
},
|
||||
}] : [],
|
||||
};
|
||||
}
|
||||
|
||||
// Default fallback
|
||||
return {
|
||||
message: error.message
|
||||
? `AI service error: ${error.message}`
|
||||
: 'Sorry, I encountered an unexpected error. Please try again.',
|
||||
actions: [],
|
||||
actions: onTryAgain ? [{
|
||||
label: 'Try again',
|
||||
onClick: () => {
|
||||
onTryAgain();
|
||||
onDismiss();
|
||||
},
|
||||
}] : [],
|
||||
};
|
||||
};
|
||||
|
||||
const { message, actions = [] } = renderBody(error);
|
||||
const { message, actions = [], showCreditsButton } = renderBody(error);
|
||||
|
||||
return (
|
||||
<div className="py-2 px-3 bg-primary/5 border border-primary/20 rounded-lg">
|
||||
@@ -217,6 +231,12 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
|
||||
</h4>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{message}
|
||||
{showCreditsButton && provider && (
|
||||
<>
|
||||
{' '}
|
||||
<QuillyCreditsButton provider={provider} />
|
||||
</>
|
||||
)}
|
||||
{actions.length > 0 && (
|
||||
<>
|
||||
{' '}
|
||||
@@ -242,12 +262,53 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface QuillyCreditsButtonProps {
|
||||
provider: AIProvider;
|
||||
}
|
||||
|
||||
function QuillyCreditsButton({ provider }: QuillyCreditsButtonProps) {
|
||||
const [showCreditsDialog, setShowCreditsDialog] = useState(false);
|
||||
const credits = useAICredits(provider);
|
||||
|
||||
return (
|
||||
<>
|
||||
<button className="text-primary underline" onClick={() => setShowCreditsDialog(true)}>
|
||||
{credits.data ? `Add credits (${credits.data.amount.toFixed(2)} remaining)` : 'Add credits'}
|
||||
</button>
|
||||
<CreditsDialog
|
||||
open={showCreditsDialog}
|
||||
onOpenChange={setShowCreditsDialog}
|
||||
provider={provider}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTryAgain, onRequestConsoleErrorHelp, providerModel }: QuillyProps) {
|
||||
const { settings } = useAISettings();
|
||||
|
||||
// Handle empty provider model gracefully
|
||||
let provider: AIProvider | undefined;
|
||||
try {
|
||||
provider = parseProviderModel(providerModel, settings.providers).provider;
|
||||
} catch {
|
||||
// If no valid provider model, use a default or undefined
|
||||
provider = undefined;
|
||||
}
|
||||
|
||||
return (
|
||||
<QuillyContent
|
||||
error={error}
|
||||
onDismiss={onDismiss}
|
||||
onNewChat={onNewChat}
|
||||
onOpenModelSelector={onOpenModelSelector}
|
||||
onTryAgain={onTryAgain}
|
||||
onRequestConsoleErrorHelp={onRequestConsoleErrorHelp}
|
||||
provider={provider}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import React from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { GitBranch } from 'lucide-react';
|
||||
import type { Repository } from '@/hooks/useUserRepositories';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar';
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
interface RepositoryCardProps {
|
||||
repo: Repository;
|
||||
}
|
||||
|
||||
export function RepositoryCard({ repo }: RepositoryCardProps) {
|
||||
const { data: authorData } = useAuthor(repo.pubkey);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const displayName = authorData?.metadata?.name || genUserName(repo.pubkey);
|
||||
const profileImage = authorData?.metadata?.picture;
|
||||
|
||||
// Construct Nostr clone URL
|
||||
const nostrCloneUrl = `nostr://${nip19.npubEncode(repo.pubkey)}/${repo.repoId}`;
|
||||
|
||||
const handleClone = () => {
|
||||
// Navigate to clone page with Nostr URL parameter
|
||||
navigate(`/clone?url=${encodeURIComponent(nostrCloneUrl)}`);
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className="h-full flex flex-col hover:shadow-lg transition-shadow cursor-pointer" onClick={handleClone}>
|
||||
<CardContent className="p-6 flex flex-col flex-1">
|
||||
{/* Header with name and author */}
|
||||
<div className="mb-4">
|
||||
<h3 className="font-semibold text-lg leading-tight mb-2 truncate">
|
||||
{repo.name}
|
||||
</h3>
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Avatar className="h-4 w-4">
|
||||
{profileImage && (
|
||||
<AvatarImage src={profileImage} alt={displayName} />
|
||||
)}
|
||||
<AvatarFallback className="text-[8px]">
|
||||
{displayName.slice(0, 2).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className="truncate">{displayName}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
{repo.description && (
|
||||
<p className="text-sm text-muted-foreground line-clamp-2 mb-4">
|
||||
{repo.description}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Tags */}
|
||||
{repo.repoTags.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1 mb-4">
|
||||
{repo.repoTags.slice(0, 3).map((tag, index) => (
|
||||
<Badge key={index} variant="secondary" className="text-xs">
|
||||
{tag}
|
||||
</Badge>
|
||||
))}
|
||||
{repo.repoTags.length > 3 && (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
+{repo.repoTags.length - 3}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Personal fork badge */}
|
||||
{repo.isPersonalFork && (
|
||||
<div className="mb-4">
|
||||
<Badge variant="outline" className="text-xs">
|
||||
Personal Fork
|
||||
</Badge>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Actions */}
|
||||
<div className="mt-auto">
|
||||
<Button
|
||||
size="sm"
|
||||
className="w-full"
|
||||
onClick={handleClone}
|
||||
>
|
||||
<GitBranch className="h-4 w-4 mr-2" />
|
||||
Clone
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -27,7 +27,7 @@ describe('SentryProvider', () => {
|
||||
relays: [{ url: 'wss://relay.test', read: true, write: true }],
|
||||
updatedAt: 0,
|
||||
},
|
||||
projectTemplate: 'https://test.git',
|
||||
templates: [{ name: 'Test', description: 'Test template', url: 'https://test.git' }],
|
||||
esmUrl: 'https://esm.test',
|
||||
corsProxy: 'https://proxy.test/{href}',
|
||||
faviconUrl: 'https://favicon.test/{href}',
|
||||
@@ -39,10 +39,11 @@ describe('SentryProvider', () => {
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
fsPathPlugins: '/plugins',
|
||||
fsPathTemplates: '/templates',
|
||||
};
|
||||
|
||||
render(
|
||||
<AppContext.Provider value={{ config, updateConfig: mockUpdateConfig }}>
|
||||
<AppContext.Provider value={{ config, defaultConfig: config, updateConfig: mockUpdateConfig }}>
|
||||
<SentryProvider>
|
||||
<div>Test</div>
|
||||
</SentryProvider>
|
||||
@@ -63,7 +64,7 @@ describe('SentryProvider', () => {
|
||||
relays: [{ url: 'wss://relay.test', read: true, write: true }],
|
||||
updatedAt: 0,
|
||||
},
|
||||
projectTemplate: 'https://test.git',
|
||||
templates: [{ name: 'Test', description: 'Test template', url: 'https://test.git' }],
|
||||
esmUrl: 'https://esm.test',
|
||||
corsProxy: 'https://proxy.test/{href}',
|
||||
faviconUrl: 'https://favicon.test/{href}',
|
||||
@@ -75,10 +76,11 @@ describe('SentryProvider', () => {
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
fsPathPlugins: '/plugins',
|
||||
fsPathTemplates: '/templates',
|
||||
};
|
||||
|
||||
render(
|
||||
<AppContext.Provider value={{ config, updateConfig: mockUpdateConfig }}>
|
||||
<AppContext.Provider value={{ config, defaultConfig: config, updateConfig: mockUpdateConfig }}>
|
||||
<SentryProvider>
|
||||
<div>Test</div>
|
||||
</SentryProvider>
|
||||
@@ -100,7 +102,7 @@ describe('SentryProvider', () => {
|
||||
relays: [{ url: 'wss://relay.test', read: true, write: true }],
|
||||
updatedAt: 0,
|
||||
},
|
||||
projectTemplate: 'https://test.git',
|
||||
templates: [{ name: 'Test', description: 'Test template', url: 'https://test.git' }],
|
||||
esmUrl: 'https://esm.test',
|
||||
corsProxy: 'https://proxy.test/{href}',
|
||||
faviconUrl: 'https://favicon.test/{href}',
|
||||
@@ -112,10 +114,11 @@ describe('SentryProvider', () => {
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
fsPathPlugins: '/plugins',
|
||||
fsPathTemplates: '/templates',
|
||||
};
|
||||
|
||||
render(
|
||||
<AppContext.Provider value={{ config, updateConfig: mockUpdateConfig }}>
|
||||
<AppContext.Provider value={{ config, defaultConfig: config, updateConfig: mockUpdateConfig }}>
|
||||
<SentryProvider>
|
||||
<div>Test</div>
|
||||
</SentryProvider>
|
||||
@@ -140,7 +143,7 @@ describe('SentryProvider', () => {
|
||||
relays: [{ url: 'wss://relay.test', read: true, write: true }],
|
||||
updatedAt: 0,
|
||||
},
|
||||
projectTemplate: 'https://test.git',
|
||||
templates: [{ name: 'Test', description: 'Test template', url: 'https://test.git' }],
|
||||
esmUrl: 'https://esm.test',
|
||||
corsProxy: 'https://proxy.test/{href}',
|
||||
faviconUrl: 'https://favicon.test/{href}',
|
||||
@@ -152,10 +155,11 @@ describe('SentryProvider', () => {
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
fsPathPlugins: '/plugins',
|
||||
fsPathTemplates: '/templates',
|
||||
};
|
||||
|
||||
render(
|
||||
<AppContext.Provider value={{ config, updateConfig: mockUpdateConfig }}>
|
||||
<AppContext.Provider value={{ config, defaultConfig: config, updateConfig: mockUpdateConfig }}>
|
||||
<SentryProvider>
|
||||
<div>Test</div>
|
||||
</SentryProvider>
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { ReactNode, useMemo, useEffect } from 'react';
|
||||
import { ReactNode, useEffect, useRef } from 'react';
|
||||
import { SessionManagerContext } from '@/contexts/SessionManagerContext';
|
||||
import { SessionManager } from '@/lib/SessionManager';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useProviderModels } from '@/hooks/useProviderModels';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
|
||||
interface SessionManagerProviderProps {
|
||||
children: ReactNode;
|
||||
@@ -17,30 +17,80 @@ interface SessionManagerProviderProps {
|
||||
*/
|
||||
export function SessionManagerProvider({ children }: SessionManagerProviderProps) {
|
||||
const { fs } = useFS();
|
||||
const { projectsPath, pluginsPath } = useFSPaths();
|
||||
const { settings } = useAISettings();
|
||||
const { models } = useProviderModels();
|
||||
const { user, metadata } = useCurrentUser();
|
||||
const { config } = useAppContext();
|
||||
const { config, defaultConfig } = useAppContext();
|
||||
const { nostr } = useNostr();
|
||||
|
||||
const sessionManager = useMemo(() => {
|
||||
const getProviderModels = () => models;
|
||||
const getCurrentUser = () => ({ user, metadata });
|
||||
return new SessionManager(fs, settings, getProviderModels, getCurrentUser, config.corsProxy, projectsPath, pluginsPath);
|
||||
}, [fs, settings, models, user, metadata, config.corsProxy, projectsPath, pluginsPath]);
|
||||
// Create SessionManager instance only once
|
||||
const sessionManager = useRef<SessionManager | undefined>(undefined);
|
||||
|
||||
// Use refs so SessionManager always has the latest data
|
||||
const configRef = useRef(config);
|
||||
const defaultConfigRef = useRef(defaultConfig);
|
||||
const settingsRef = useRef(settings);
|
||||
const modelsRef = useRef(models);
|
||||
const userRef = useRef(user);
|
||||
const metadataRef = useRef(metadata);
|
||||
|
||||
// Update refs when values change
|
||||
useEffect(() => {
|
||||
configRef.current = config;
|
||||
}, [config]);
|
||||
|
||||
useEffect(() => {
|
||||
defaultConfigRef.current = defaultConfig;
|
||||
}, [defaultConfig]);
|
||||
|
||||
useEffect(() => {
|
||||
settingsRef.current = settings;
|
||||
}, [settings]);
|
||||
|
||||
useEffect(() => {
|
||||
modelsRef.current = models;
|
||||
}, [models]);
|
||||
|
||||
useEffect(() => {
|
||||
userRef.current = user;
|
||||
}, [user]);
|
||||
|
||||
useEffect(() => {
|
||||
metadataRef.current = metadata;
|
||||
}, [metadata]);
|
||||
|
||||
// Initialize SessionManager only once
|
||||
if (!sessionManager.current) {
|
||||
// Callbacks access refs to get latest values
|
||||
const getProviderModels = () => modelsRef.current;
|
||||
const getCurrentUser = () => ({ user: userRef.current, metadata: metadataRef.current });
|
||||
const getConfig = () => configRef.current;
|
||||
const getDefaultConfig = () => defaultConfigRef.current;
|
||||
const getSettings = () => settingsRef.current;
|
||||
|
||||
sessionManager.current = new SessionManager(
|
||||
fs,
|
||||
nostr,
|
||||
getSettings,
|
||||
getConfig,
|
||||
getDefaultConfig,
|
||||
getProviderModels,
|
||||
getCurrentUser,
|
||||
);
|
||||
}
|
||||
|
||||
// Cleanup on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
// Fire and forget cleanup - we don't need to await in useEffect cleanup
|
||||
sessionManager.cleanup().catch(error => {
|
||||
sessionManager.current?.cleanup().catch(error => {
|
||||
console.warn('Failed to cleanup session manager:', error);
|
||||
});
|
||||
};
|
||||
}, [sessionManager]);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<SessionManagerContext.Provider value={sessionManager}>
|
||||
<SessionManagerContext.Provider value={sessionManager.current}>
|
||||
{children}
|
||||
</SessionManagerContext.Provider>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { ChevronRight } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface SettingsItemProps {
|
||||
icon: React.ComponentType<{ className?: string }>;
|
||||
title: string;
|
||||
onClick: () => void;
|
||||
isActive?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function SettingsItem({
|
||||
icon: Icon,
|
||||
title,
|
||||
onClick,
|
||||
isActive = false,
|
||||
className,
|
||||
}: SettingsItemProps) {
|
||||
return (
|
||||
<button
|
||||
onClick={onClick}
|
||||
className={cn(
|
||||
'group w-full text-left p-2 rounded-lg transition-all duration-200 border',
|
||||
{
|
||||
'bg-primary/10 border-primary/20 shadow-sm': isActive,
|
||||
'border-transparent hover:bg-muted/60 hover:shadow-sm': !isActive,
|
||||
},
|
||||
className
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2.5">
|
||||
<div className="rounded-md transition-all duration-200">
|
||||
<Icon className={cn('h-4 w-4 flex-shrink-0 transition-colors duration-200', {
|
||||
'text-primary': isActive,
|
||||
'text-muted-foreground group-hover:text-foreground': !isActive,
|
||||
})} />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className={cn('text-sm font-medium transition-colors duration-200', {
|
||||
'text-primary': isActive,
|
||||
'text-foreground': !isActive,
|
||||
})}>
|
||||
{title}
|
||||
</div>
|
||||
</div>
|
||||
<ChevronRight className={cn(
|
||||
'h-4 w-4 flex-shrink-0 transition-all duration-200',
|
||||
'opacity-0 -translate-x-1 group-hover:opacity-100 group-hover:translate-x-0',
|
||||
{
|
||||
'text-primary opacity-60': isActive,
|
||||
'text-muted-foreground': !isActive,
|
||||
}
|
||||
)} />
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { ChevronRight } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface SettingsItemMobileProps {
|
||||
icon: React.ComponentType<{ className?: string }>;
|
||||
title: string;
|
||||
onClick: () => void;
|
||||
isFirst?: boolean;
|
||||
isLast?: boolean;
|
||||
}
|
||||
|
||||
export function SettingsItemMobile({
|
||||
icon: Icon,
|
||||
title,
|
||||
onClick,
|
||||
isFirst = false,
|
||||
isLast = false,
|
||||
}: SettingsItemMobileProps) {
|
||||
return (
|
||||
<button
|
||||
onClick={onClick}
|
||||
className={cn(
|
||||
'w-full text-left px-4 py-3.5 bg-card text-card-foreground transition-colors active:bg-muted/50',
|
||||
'flex items-center gap-3',
|
||||
'border-b border-border last:border-b-0',
|
||||
{
|
||||
'rounded-t-xl': isFirst,
|
||||
'rounded-b-xl': isLast,
|
||||
}
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center justify-center w-7 h-7 rounded-lg bg-primary/10">
|
||||
<Icon className="h-4 w-4 text-primary flex-shrink-0" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-base">
|
||||
{title}
|
||||
</div>
|
||||
</div>
|
||||
<ChevronRight className="h-5 w-5 text-muted-foreground/50 flex-shrink-0" />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -8,8 +8,8 @@ import { ProjectSidebar } from '@/components/ProjectSidebar';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { type Project } from '@/lib/ProjectsManager';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { getSettingsItems } from '@/lib/settingsItems';
|
||||
import { getSettingsCategories } from '@/lib/settingsItems';
|
||||
import { SettingsItem } from '@/components/SettingsItem';
|
||||
|
||||
export function SettingsLayout() {
|
||||
const { t } = useTranslation();
|
||||
@@ -60,9 +60,11 @@ export function SettingsLayout() {
|
||||
};
|
||||
|
||||
// Get current settings page
|
||||
const settingsItems = getSettingsItems(t);
|
||||
const settingsCategories = getSettingsCategories(t);
|
||||
const currentPath = location.pathname;
|
||||
const currentSettingsId = settingsItems.find(item => item.href === currentPath)?.id;
|
||||
const currentSettingsId = settingsCategories
|
||||
.flatMap(category => category.items)
|
||||
.find(item => item.href === currentPath)?.id;
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
@@ -89,7 +91,7 @@ export function SettingsLayout() {
|
||||
className="absolute inset-0"
|
||||
onClick={() => setIsSidebarVisible(false)}
|
||||
/>
|
||||
<div className="relative left-0 top-0 h-full w-80 max-w-[80vw] bg-background border-r shadow-lg z-10">
|
||||
<div className="relative left-0 top-0 h-full w-72 max-w-[80vw] bg-background border-r shadow-lg z-10">
|
||||
<ProjectSidebar
|
||||
selectedProject={null}
|
||||
onSelectProject={(project) => {
|
||||
@@ -112,7 +114,7 @@ export function SettingsLayout() {
|
||||
<div className="h-screen flex bg-background overflow-hidden">
|
||||
{/* Left Column - Projects Sidebar (optionally hidden) */}
|
||||
{isSidebarVisible && (
|
||||
<div className="w-80 border-r bg-sidebar flex-shrink-0">
|
||||
<div className="w-72 border-r bg-sidebar flex-shrink-0">
|
||||
<ProjectSidebar
|
||||
selectedProject={null}
|
||||
onSelectProject={handleProjectSelect}
|
||||
@@ -123,7 +125,7 @@ export function SettingsLayout() {
|
||||
)}
|
||||
|
||||
{/* Middle Column - Settings Navigation */}
|
||||
<div className="w-96 border-r bg-background flex flex-col flex-shrink-0">
|
||||
<div className="w-72 border-r bg-background flex flex-col flex-shrink-0">
|
||||
{/* Header with toggle button */}
|
||||
<div className="h-12 px-4 py-2 border-b flex-shrink-0">
|
||||
<div className="flex items-center gap-3">
|
||||
@@ -146,36 +148,29 @@ export function SettingsLayout() {
|
||||
|
||||
{/* Settings Navigation - Scrollable */}
|
||||
<ScrollArea className="flex-1">
|
||||
<div className="p-4">
|
||||
<div className="space-y-2">
|
||||
{settingsItems.map((item) => {
|
||||
const Icon = item.icon;
|
||||
const isActive = currentSettingsId === item.id;
|
||||
<div className="p-4 space-y-6">
|
||||
{settingsCategories.map((category) => (
|
||||
<div key={category.id}>
|
||||
<h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2 px-2">
|
||||
{category.title}
|
||||
</h3>
|
||||
<div className="space-y-1">
|
||||
{category.items.map((item) => {
|
||||
const isActive = currentSettingsId === item.id;
|
||||
|
||||
return (
|
||||
<button
|
||||
key={item.id}
|
||||
onClick={() => navigate(item.href)}
|
||||
className={cn('w-full text-left p-3 rounded-lg transition-colors border border-transparent', {
|
||||
'bg-primary/10 border border-primary/20': isActive,
|
||||
'hover:bg-muted/50': !isActive,
|
||||
})}
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
<Icon className={`h-5 w-5 mt-0.5 ${isActive ? 'text-primary' : 'text-muted-foreground'}`} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className={`font-medium ${isActive ? 'text-primary' : 'text-foreground'}`}>
|
||||
{item.title}
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground mt-0.5">
|
||||
{item.description}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
return (
|
||||
<SettingsItem
|
||||
key={item.id}
|
||||
icon={item.icon}
|
||||
title={item.title}
|
||||
onClick={() => navigate(item.href)}
|
||||
isActive={isActive}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { OnboardingDialog } from '@/components/OnboardingDialog';
|
||||
import { Loader2, ChevronDown } from 'lucide-react';
|
||||
import { ChevronDown } from 'lucide-react';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
@@ -14,7 +14,9 @@ import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useAIChat } from '@/hooks/useAIChat';
|
||||
import { useProviderModels } from '@/hooks/useProviderModels';
|
||||
import { useSessionManager } from '@/hooks/useSessionManager';
|
||||
import { useMCPTools } from '@/hooks/useMCPTools';
|
||||
import { AIMessageItem } from '@/components/AIMessageItem';
|
||||
import { ToolCallDisplay } from '@/components/ToolCallDisplay';
|
||||
import { TextEditorViewTool } from '@/lib/tools/TextEditorViewTool';
|
||||
import { TextEditorWriteTool } from '@/lib/tools/TextEditorWriteTool';
|
||||
import { TextEditorStrReplaceTool } from '@/lib/tools/TextEditorStrReplaceTool';
|
||||
@@ -32,18 +34,24 @@ import { NostrReadNipsIndexTool } from '@/lib/tools/NostrReadNipsIndexTool';
|
||||
import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool';
|
||||
import { NostrPublishEventsTool } from '@/lib/tools/NostrPublishEventsTool';
|
||||
import { ShellTool } from '@/lib/tools/ShellTool';
|
||||
import { TypecheckTool } from '@/lib/tools/TypecheckTool';
|
||||
import { ReadConsoleMessagesTool } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||
import { SkillTool } from '@/lib/tools/SkillTool';
|
||||
import { GenerateImageTool } from '@/lib/tools/GenerateImageTool';
|
||||
import { ViewAvailableModelsTool } from '@/lib/tools/ViewAvailableModelsTool';
|
||||
import { ConfigureImageGenerationTool } from '@/lib/tools/ConfigureImageGenerationTool';
|
||||
import { createMCPTools } from '@/lib/tools/MCPTool';
|
||||
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
|
||||
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
|
||||
import { Tool } from '@/lib/tools/Tool';
|
||||
import OpenAI from 'openai';
|
||||
import { saveFileToTmp } from '@/lib/fileUtils';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { Quilly } from '@/components/Quilly';
|
||||
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
||||
import { ChatInput } from '@/components/Shakespeare/ChatInput';
|
||||
import { buildMessageContent } from '@/lib/buildMessageContent';
|
||||
import { DotAI } from '@/lib/DotAI';
|
||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
import { AIMessage } from '@/lib/SessionManager';
|
||||
|
||||
// Clean interfaces now handled by proper hooks
|
||||
|
||||
@@ -86,6 +94,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
const [showOnboarding, setShowOnboarding] = useState(false);
|
||||
const [isStuck, setIsStuck] = useState(false);
|
||||
const [aiError, setAIError] = useState<Error | null>(null);
|
||||
const [templateInfo, setTemplateInfo] = useState<{ name: string; description: string; url: string } | null>(null);
|
||||
const [showTemplateInfo, setShowTemplateInfo] = useState(false);
|
||||
|
||||
// Determine which error to show - console error takes priority over AI errors
|
||||
const displayError = consoleError || aiError;
|
||||
@@ -93,7 +103,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
// Use external state if provided, otherwise default to false
|
||||
const isBuildLoading = externalIsBuildLoading || false;
|
||||
const scrollAreaRef = useRef<HTMLDivElement>(null);
|
||||
const { isConfigured, settings, addRecentlyUsedModel } = useAISettings();
|
||||
const aiSettings = useAISettings();
|
||||
const { isConfigured, settings, addRecentlyUsedModel } = aiSettings;
|
||||
const [providerModel, setProviderModel] = useState(() => {
|
||||
// Initialize with first recently used model if available, otherwise empty
|
||||
return settings.recentlyUsedModels?.[0] || '';
|
||||
@@ -148,8 +159,12 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
sessionManager.emit('fileChanged', projectId, filePath);
|
||||
}, [sessionManager, projectId]);
|
||||
|
||||
const customTools = useMemo(() => {
|
||||
const baseTools = {
|
||||
// Fetch MCP tools
|
||||
const { tools: mcpOpenAITools, clients: mcpClients } = useMCPTools();
|
||||
|
||||
// Separate built-in tools from MCP tools for clarity
|
||||
const builtInTools = useMemo(() => {
|
||||
const tools: Record<string, Tool<unknown>> = {
|
||||
git_commit: new GitCommitTool(fs, cwd, git),
|
||||
text_editor_view: new TextEditorViewTool(fs, cwd, { projectsPath }),
|
||||
text_editor_write: new TextEditorWriteTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }),
|
||||
@@ -157,7 +172,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
npm_add_package: new NpmAddPackageTool(fs, cwd),
|
||||
npm_remove_package: new NpmRemovePackageTool(fs, cwd),
|
||||
build_project: new BuildProjectTool(fs, cwd, esmUrlRef.current),
|
||||
typecheck: new TypecheckTool(fs, cwd),
|
||||
nostr_read_nip: new NostrReadNipTool(),
|
||||
nostr_fetch_event: new NostrFetchEventTool(),
|
||||
nostr_read_kind: new NostrReadKindTool(),
|
||||
@@ -166,30 +180,90 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
nostr_read_nips_index: new NostrReadNipsIndexTool(),
|
||||
nostr_generate_kind: new NostrGenerateKindTool(),
|
||||
nostr_publish_events: new NostrPublishEventsTool(),
|
||||
shell: new ShellTool(fs, cwd, git, projectsPath, user?.signer),
|
||||
shell: new ShellTool(fs, cwd, git, config.corsProxy, user?.signer),
|
||||
read_console_messages: new ReadConsoleMessagesTool(),
|
||||
skill: new SkillTool(fs, pluginsPath),
|
||||
skill: new SkillTool(fs, pluginsPath, cwd),
|
||||
};
|
||||
|
||||
// Add deploy tool only if user is logged in
|
||||
if (user && user.signer) {
|
||||
return {
|
||||
...baseTools,
|
||||
deploy_project: new DeployProjectTool(fs, cwd, user.signer, projectId),
|
||||
};
|
||||
tools.deploy_project = new DeployProjectTool(fs, cwd, user.signer, projectId);
|
||||
}
|
||||
|
||||
return baseTools;
|
||||
}, [fs, git, cwd, user, projectId, projectsPath, tmpPath, pluginsPath, handleFileChanged]);
|
||||
// Add generate_image tool if imageModel is configured
|
||||
if (settings.imageModel) {
|
||||
try {
|
||||
const { provider, model } = parseProviderModel(settings.imageModel, settings.providers);
|
||||
|
||||
// Convert tools to OpenAI format
|
||||
// Find the model data to determine the generation mode
|
||||
const providerModel = models.find(m => m.fullId === settings.imageModel);
|
||||
|
||||
// Determine mode: 'chat' if model supports image output modality, otherwise 'image'
|
||||
let mode: 'chat' | 'image' = 'image';
|
||||
|
||||
if (providerModel?.type) {
|
||||
switch (providerModel.type) {
|
||||
case 'chat':
|
||||
mode = 'chat';
|
||||
break;
|
||||
case 'image':
|
||||
mode = 'image';
|
||||
break;
|
||||
}
|
||||
} else if (providerModel?.modalities?.includes('image')) {
|
||||
mode = 'chat';
|
||||
}
|
||||
|
||||
tools.generate_image = new GenerateImageTool(
|
||||
fs,
|
||||
tmpPath,
|
||||
provider,
|
||||
model,
|
||||
mode,
|
||||
user,
|
||||
config.corsProxy
|
||||
);
|
||||
} catch (error) {
|
||||
console.warn('Failed to parse imageModel:', error);
|
||||
}
|
||||
} else {
|
||||
// If imageModel is not configured, provide tools to help configure it
|
||||
tools.view_available_models = new ViewAvailableModelsTool(
|
||||
models,
|
||||
settings.imageModel
|
||||
);
|
||||
tools.configure_image_generation = new ConfigureImageGenerationTool(
|
||||
aiSettings,
|
||||
models
|
||||
);
|
||||
}
|
||||
|
||||
return tools;
|
||||
}, [fs, git, cwd, user, projectId, projectsPath, tmpPath, pluginsPath, config.corsProxy, settings, aiSettings, models, handleFileChanged]);
|
||||
|
||||
// MCP tools wrapped for execution
|
||||
const mcpToolWrappers = useMemo(() => createMCPTools(mcpClients), [mcpClients]);
|
||||
|
||||
// Combined tool executors (for SessionManager to call)
|
||||
const customTools = useMemo(() => ({
|
||||
...builtInTools,
|
||||
...mcpToolWrappers,
|
||||
}), [builtInTools, mcpToolWrappers]);
|
||||
|
||||
// Convert tools to OpenAI format for AI provider
|
||||
const tools = useMemo(() => {
|
||||
const result: Record<string, OpenAI.Chat.Completions.ChatCompletionTool> = {};
|
||||
for (const [name, tool] of Object.entries(customTools)) {
|
||||
|
||||
// Convert built-in tools to OpenAI format
|
||||
for (const [name, tool] of Object.entries(builtInTools)) {
|
||||
result[name] = toolToOpenAI(name, tool as Tool<unknown>);
|
||||
}
|
||||
|
||||
// Add MCP tools (already in OpenAI format from useMCPTools)
|
||||
Object.assign(result, mcpOpenAITools);
|
||||
|
||||
return result;
|
||||
}, [customTools]);
|
||||
}, [builtInTools, mcpOpenAITools]);
|
||||
|
||||
// Keep-alive functionality to prevent tab throttling during AI processing
|
||||
const { updateMetadata } = useKeepAlive({
|
||||
@@ -234,6 +308,52 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
onAIError,
|
||||
});
|
||||
|
||||
// Check if we should show the template info banner
|
||||
useEffect(() => {
|
||||
const checkTemplateInfo = async () => {
|
||||
try {
|
||||
// Only check if we have at least 1 message
|
||||
if (messages.length === 0) {
|
||||
setShowTemplateInfo(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const projectCwd = `${projectsPath}/${projectId}`;
|
||||
const dotAI = new DotAI(fs, projectCwd);
|
||||
|
||||
// Check if template.json exists
|
||||
const template = await dotAI.readTemplate();
|
||||
if (!template) {
|
||||
setShowTemplateInfo(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if exactly 1 history file exists
|
||||
const historyDirExists = await dotAI.historyDirExists();
|
||||
if (!historyDirExists) {
|
||||
setShowTemplateInfo(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const historyDir = `${projectCwd}/.git/ai/history`;
|
||||
const files = await fs.readdir(historyDir);
|
||||
const historyFiles = files.filter(file => file.endsWith('.jsonl'));
|
||||
|
||||
if (historyFiles.length === 1) {
|
||||
setTemplateInfo(template);
|
||||
setShowTemplateInfo(true);
|
||||
} else {
|
||||
setShowTemplateInfo(false);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to check template info:', error);
|
||||
setShowTemplateInfo(false);
|
||||
}
|
||||
};
|
||||
|
||||
checkTemplateInfo();
|
||||
}, [fs, projectsPath, projectId, messages.length]);
|
||||
|
||||
// Handle console error help requests
|
||||
const handleConsoleErrorHelp = useCallback(async () => {
|
||||
const tool = new ReadConsoleMessagesTool();
|
||||
@@ -254,9 +374,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
]
|
||||
});
|
||||
|
||||
const result = await tool.execute({ filter: 'error' });
|
||||
|
||||
await addMessage({
|
||||
role: 'tool',
|
||||
content: await tool.execute({ filter: 'error' }),
|
||||
content: result.content,
|
||||
tool_call_id: toolCallId,
|
||||
});
|
||||
|
||||
@@ -438,45 +560,18 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
|
||||
const modelToUse = providerModel.trim();
|
||||
|
||||
// Build message content as text parts
|
||||
const contentParts: Array<OpenAI.Chat.Completions.ChatCompletionContentPartText> = [];
|
||||
|
||||
// Add user input as text part if present
|
||||
if (input.trim()) {
|
||||
contentParts.push({
|
||||
type: 'text',
|
||||
text: input.trim()
|
||||
});
|
||||
}
|
||||
|
||||
// Process attached files and add as separate text parts
|
||||
if (attachedFiles.length > 0) {
|
||||
const filePromises = attachedFiles.map(async (file) => {
|
||||
try {
|
||||
const savedPath = await saveFileToTmp(fs, file, tmpPath);
|
||||
return `Added file: ${savedPath}`;
|
||||
} catch (error) {
|
||||
console.error('Failed to save file:', error);
|
||||
return `Failed to save file: ${file.name}`;
|
||||
}
|
||||
});
|
||||
|
||||
const fileResults = await Promise.all(filePromises);
|
||||
|
||||
// Add each file as a separate text part
|
||||
fileResults.forEach(fileResult => {
|
||||
contentParts.push({
|
||||
type: 'text',
|
||||
text: fileResult
|
||||
});
|
||||
});
|
||||
}
|
||||
// Build message content from input and attached files
|
||||
// Images are converted to base64-encoded data URLs
|
||||
const messageContent = await buildMessageContent(
|
||||
input,
|
||||
attachedFiles,
|
||||
fs,
|
||||
tmpPath
|
||||
);
|
||||
|
||||
// Add model to recently used when sending a message
|
||||
addRecentlyUsedModel(modelToUse);
|
||||
|
||||
// Send as text parts if we have multiple parts, otherwise send as string for simplicity
|
||||
const messageContent = contentParts.length === 1 ? contentParts[0].text : contentParts;
|
||||
await sendMessage(messageContent, modelToUse);
|
||||
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath]);
|
||||
|
||||
@@ -506,11 +601,111 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
}), [internalStartNewSession]);
|
||||
|
||||
/** Render streaming message, loading skeleton, or tool loading state */
|
||||
const renderStreamingMessage = () => {
|
||||
if (streamingMessage) {
|
||||
const streamingToolCall = streamingMessage.tool_calls?.[0];
|
||||
return (
|
||||
<>
|
||||
{/* Show streaming message if text is streaming */}
|
||||
{(streamingMessage.content || streamingMessage.reasoning_content) && (
|
||||
<AIMessageItem
|
||||
key="streaming-message"
|
||||
message={streamingMessage}
|
||||
isCurrentlyLoading={isLoading}
|
||||
/>
|
||||
)}
|
||||
{/* Show tool call in "calling" state if streaming tool call is in progress */}
|
||||
{(streamingToolCall?.type === 'function') ? (
|
||||
<ToolCallDisplay
|
||||
key="tool-calls-loading"
|
||||
toolName={streamingToolCall.function.name}
|
||||
toolArgs={(() => {
|
||||
try {
|
||||
return JSON.parse(streamingToolCall.function.arguments);
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
})()}
|
||||
state="calling"
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
{/* Show loading skeleton if AI appears stuck generating tools */}
|
||||
{isStuck && (
|
||||
<div key="stuck-loading-skeleton" className="flex">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm space-y-2">
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const lastMessage = messages[messages.length - 1] as AIMessage | undefined;
|
||||
const lastToolCall = lastMessage?.role === 'assistant' ? lastMessage?.tool_calls?.[0] : undefined;
|
||||
|
||||
// Show tool call in "waiting" state if last tool call is still executing
|
||||
if (lastToolCall?.type === 'function') {
|
||||
return (
|
||||
<ToolCallDisplay
|
||||
key="tool-running-loading"
|
||||
toolName={lastToolCall.function.name}
|
||||
toolArgs={(() => {
|
||||
try {
|
||||
return JSON.parse(lastToolCall.function.arguments);
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
})()}
|
||||
state="waiting"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Fallback skeleton if AI is loading
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div key="streaming-loading" className="flex">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm space-y-2">
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col relative">
|
||||
|
||||
<div className="flex-1 overflow-y-scroll overflow-x-hidden" ref={scrollAreaRef}>
|
||||
<div className="p-4 space-y-4">
|
||||
{/* Template info banner - shown when conditions are met */}
|
||||
{showTemplateInfo && templateInfo && (
|
||||
<div className="flex items-center gap-3 text-xs text-muted-foreground uppercase tracking-wide">
|
||||
<div className="flex-1 h-px bg-border" />
|
||||
<span>
|
||||
Vibing with{' '}
|
||||
<a
|
||||
href={templateInfo.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="hover:text-foreground transition-colors"
|
||||
>
|
||||
{templateInfo.name}
|
||||
</a>
|
||||
</span>
|
||||
<div className="flex-1 h-px bg-border" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Empty state when no messages and not loading */}
|
||||
{messages.length === 0 && !streamingMessage && !isLoading && (
|
||||
<div className="flex-1 flex items-center justify-center min-h-[400px]">
|
||||
@@ -558,47 +753,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
/>
|
||||
);
|
||||
})}
|
||||
{streamingMessage && (
|
||||
streamingMessage.content || streamingMessage.reasoning_content ? (
|
||||
<>
|
||||
<AIMessageItem
|
||||
key="streaming-message"
|
||||
message={streamingMessage}
|
||||
isCurrentlyLoading={isLoading}
|
||||
/>
|
||||
{/* Show loading skeleton if AI appears stuck generating tools */}
|
||||
{isStuck && (
|
||||
<div key="stuck-loading-skeleton" className="flex">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm space-y-2">
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
!(streamingMessage?.tool_calls?.[0]?.type === 'function') && (
|
||||
<div key="streaming-loading" className="flex">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm space-y-2">
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
)
|
||||
)}
|
||||
{streamingMessage?.tool_calls?.[0]?.type === 'function' && (
|
||||
<div key="tool-calls-loading" className="-mt-2">
|
||||
<div className="flex items-center gap-2 px-2 py-1 text-xs text-muted-foreground">
|
||||
<Loader2 className="h-3 w-3 animate-spin flex-shrink-0" />
|
||||
<span className="font-medium">
|
||||
{t('running')} {streamingMessage.tool_calls?.[0]?.function?.name || 'tool'}...
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{renderStreamingMessage()}
|
||||
|
||||
{/* Error Alert (Console or AI) - Don't show while assistant is loading */}
|
||||
{displayError && !isLoading && (
|
||||
|
||||
@@ -3,9 +3,10 @@ import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Save, Loader2 } from 'lucide-react';
|
||||
import { Save, Loader2, ImageOff } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import { isMediaFile } from '@/lib/fileUtils';
|
||||
|
||||
interface FileEditorProps {
|
||||
filePath: string;
|
||||
@@ -93,6 +94,7 @@ export function FileEditor({ filePath, content, onSave, isLoading, projectId }:
|
||||
// Get git status for the current file
|
||||
const currentFileGitStatus = getFileGitStatus(filePath);
|
||||
const gitStatusClasses = getGitStatusClasses(currentFileGitStatus);
|
||||
const isMedia = isMediaFile(filePath);
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col">
|
||||
@@ -100,32 +102,36 @@ export function FileEditor({ filePath, content, onSave, isLoading, projectId }:
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className={cn("text-sm sm:text-base truncate flex-1 mr-2", gitStatusClasses)}>{filePath}</CardTitle>
|
||||
<div className="flex items-center space-x-1 sm:space-x-2">
|
||||
{hasChanges && (
|
||||
{hasChanges && !isMedia && (
|
||||
<span className="text-xs sm:text-sm text-muted-foreground hidden sm:inline">{t('unsavedChanges')}</span>
|
||||
)}
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
disabled={!hasChanges || isSaving || isLoading}
|
||||
size="sm"
|
||||
className="focus-ring"
|
||||
>
|
||||
{isSaving ? (
|
||||
<>
|
||||
<Loader2 className="mr-1 sm:mr-2 h-4 w-4 animate-spin" />
|
||||
<span className="hidden sm:inline">{t('saving')}</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Save className="sm:mr-2 h-4 w-4" />
|
||||
<span className="hidden sm:inline">{t('save')}</span>
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
{!isMedia && (
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
disabled={!hasChanges || isSaving || isLoading}
|
||||
size="sm"
|
||||
className="focus-ring"
|
||||
>
|
||||
{isSaving ? (
|
||||
<>
|
||||
<Loader2 className="mr-1 sm:mr-2 h-4 w-4 animate-spin" />
|
||||
<span className="hidden sm:inline">{t('saving')}</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Save className="sm:mr-2 h-4 w-4" />
|
||||
<span className="hidden sm:inline">{t('save')}</span>
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground mt-1">
|
||||
{t('languageLabel')}: {getLanguageFromPath(filePath)}
|
||||
</div>
|
||||
{!isMedia && (
|
||||
<div className="text-xs text-muted-foreground mt-1">
|
||||
{t('languageLabel')}: {getLanguageFromPath(filePath)}
|
||||
</div>
|
||||
)}
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="flex-1 p-0">
|
||||
@@ -133,6 +139,10 @@ export function FileEditor({ filePath, content, onSave, isLoading, projectId }:
|
||||
<div className="flex items-center justify-center h-full">
|
||||
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
|
||||
</div>
|
||||
) : isMedia ? (
|
||||
<div className="flex flex-col items-center justify-center h-full p-8 text-center">
|
||||
<ImageOff className="h-16 w-16 text-muted-foreground" />
|
||||
</div>
|
||||
) : (
|
||||
<Textarea
|
||||
value={editedContent}
|
||||
|
||||
@@ -32,6 +32,7 @@ import { DeployDialog } from '@/components/DeployDialog';
|
||||
import { Terminal as TerminalComponent } from '@/components/Terminal';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { isMediaFile } from '@/lib/fileUtils';
|
||||
|
||||
interface PreviewPaneProps {
|
||||
projectId: string;
|
||||
@@ -130,6 +131,13 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
}, [isBuildLoading, isPreviewable, handleBuildProject, shouldBuild]);
|
||||
|
||||
const loadFileContent = useCallback(async (filePath: string) => {
|
||||
// Skip loading media files - they can't be edited as text
|
||||
if (isMediaFile(filePath)) {
|
||||
setFileContent('');
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const content = await projectsManager.readFile(projectId, filePath);
|
||||
@@ -700,11 +708,12 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
<div className="flex-1">
|
||||
{hasBuiltProject ? (
|
||||
<iframe
|
||||
key={projectId}
|
||||
ref={iframeRef}
|
||||
src={`https://${projectId}.${previewDomain}/`}
|
||||
className="w-full h-full border-0"
|
||||
title="Project Preview"
|
||||
sandbox="allow-scripts allow-same-origin"
|
||||
sandbox="allow-scripts allow-same-origin allow-forms"
|
||||
/>
|
||||
) : (
|
||||
<div className="h-full flex items-center justify-center bg-muted">
|
||||
@@ -793,7 +802,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
</h3>
|
||||
</div>
|
||||
<div className="flex-1 min-h-0">
|
||||
<TerminalComponent projectId={projectId} />
|
||||
<TerminalComponent cwd={`${projectsPath}/${projectId}`} />
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
@@ -887,7 +896,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
<div className="flex-1 flex min-h-0">
|
||||
{desktopCodeView === 'terminal' ? (
|
||||
<div className="flex-1">
|
||||
<TerminalComponent projectId={projectId} />
|
||||
<TerminalComponent cwd={`${projectsPath}/${projectId}`} />
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
|
||||
+11
-13
@@ -5,13 +5,13 @@ import { Copy } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { ShellTool } from '@/lib/tools/ShellTool';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { ansiToHtml, containsAnsiCodes } from '@/lib/ansiToHtml';
|
||||
|
||||
interface TerminalProps {
|
||||
projectId: string;
|
||||
cwd: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ interface TerminalLine {
|
||||
timestamp: Date;
|
||||
}
|
||||
|
||||
export function Terminal({ projectId, className }: TerminalProps) {
|
||||
export function Terminal({ cwd, className }: TerminalProps) {
|
||||
const [lines, setLines] = useState<TerminalLine[]>([]);
|
||||
const [currentInput, setCurrentInput] = useState('');
|
||||
const [isExecuting, setIsExecuting] = useState(false);
|
||||
@@ -34,13 +34,13 @@ export function Terminal({ projectId, className }: TerminalProps) {
|
||||
const shellToolRef = useRef<ShellTool | null>(null);
|
||||
|
||||
const { fs } = useFS();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { git } = useGit();
|
||||
const { user } = useCurrentUser();
|
||||
const { config } = useAppContext();
|
||||
|
||||
// Initialize ShellTool
|
||||
useEffect(() => {
|
||||
shellToolRef.current = new ShellTool(fs, `${projectsPath}/${projectId}`, git, projectsPath, user?.signer);
|
||||
shellToolRef.current = new ShellTool(fs, cwd, git, config.corsProxy, user?.signer);
|
||||
|
||||
// Add welcome message
|
||||
setLines([{
|
||||
@@ -49,7 +49,7 @@ export function Terminal({ projectId, className }: TerminalProps) {
|
||||
content: `Welcome to Shakespeare Terminal\nType 'help' to see available commands.`,
|
||||
timestamp: new Date()
|
||||
}]);
|
||||
}, [projectId, fs, git, projectsPath, user?.signer]);
|
||||
}, [cwd, fs, git, config.corsProxy, user?.signer]);
|
||||
|
||||
// Auto-scroll to bottom when new lines are added or execution state changes
|
||||
useEffect(() => {
|
||||
@@ -106,10 +106,8 @@ export function Terminal({ projectId, className }: TerminalProps) {
|
||||
|
||||
// Check if running in Electron - use real shell
|
||||
if (window.electron?.shell) {
|
||||
// Use the full path (with ~ if present) - Electron will expand it
|
||||
const fullCwd = `${projectsPath}/${projectId}`;
|
||||
|
||||
const result = await window.electron.shell.exec(command, fullCwd);
|
||||
// Use the provided cwd (Electron will expand ~ if present)
|
||||
const result = await window.electron.shell.exec(command, cwd);
|
||||
|
||||
// Format output
|
||||
let output = '';
|
||||
@@ -147,8 +145,8 @@ export function Terminal({ projectId, className }: TerminalProps) {
|
||||
const result = await shellToolRef.current.execute({ command });
|
||||
|
||||
// Add output
|
||||
if (result && result.trim()) {
|
||||
addLine('output', result);
|
||||
if (result.content && result.content.trim()) {
|
||||
addLine('output', result.content);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -157,7 +155,7 @@ export function Terminal({ projectId, className }: TerminalProps) {
|
||||
} finally {
|
||||
setIsExecuting(false);
|
||||
}
|
||||
}, [addLine, commandHistory, projectId, projectsPath]);
|
||||
}, [addLine, commandHistory, cwd]);
|
||||
|
||||
const handleSubmit = useCallback((e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
@@ -6,7 +6,7 @@ import { Terminal } from './Terminal';
|
||||
export function TerminalTest() {
|
||||
return (
|
||||
<div className="h-[500px] w-full">
|
||||
<Terminal projectId="test" />
|
||||
<Terminal cwd="/projects/test" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,498 @@
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
Wrench,
|
||||
Eye,
|
||||
FileText,
|
||||
Edit,
|
||||
Package,
|
||||
PackageMinus,
|
||||
GitCommit,
|
||||
BookOpen,
|
||||
Download,
|
||||
Hash,
|
||||
Tag,
|
||||
Network,
|
||||
List,
|
||||
Plus,
|
||||
Terminal,
|
||||
Globe,
|
||||
Loader2,
|
||||
Logs,
|
||||
Send,
|
||||
Puzzle,
|
||||
Image,
|
||||
AlertCircle,
|
||||
LucideIcon,
|
||||
Settings,
|
||||
TriangleAlert,
|
||||
X,
|
||||
} from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { VFSImage } from '@/components/VFSImage';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { ImageModelDialog } from '@/components/ImageModelDialog';
|
||||
import { ImageLightbox } from '@/components/ImageLightbox';
|
||||
|
||||
interface ToolInfo {
|
||||
icon: LucideIcon;
|
||||
title: string;
|
||||
callingTitle?: string; // Title to show while calling (e.g., "Editing {path}")
|
||||
errorTitle?: string; // Title to show when error occurs (e.g., "Failed to edit {path}")
|
||||
}
|
||||
|
||||
interface ToolCallDisplayProps {
|
||||
toolName: string;
|
||||
toolArgs: Record<string, unknown>;
|
||||
state: 'calling' | 'waiting' | 'completed';
|
||||
result?: string; // The tool result content (only for completed state)
|
||||
}
|
||||
|
||||
// Component to show image generation errors inline
|
||||
function ImageGenerationError() {
|
||||
const [showImageModelDialog, setShowImageModelDialog] = useState(false);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="mt-1 max-w-xs">
|
||||
<Alert variant="default" className="border-primary/20 bg-primary/5">
|
||||
<AlertCircle className="h-4 w-4 text-primary" />
|
||||
<AlertDescription className="text-sm">
|
||||
<span className="text-foreground">
|
||||
Image generation failed. This could be due to an issue with the selected image model or the AI provider.{' '}
|
||||
</span>
|
||||
<button
|
||||
className="text-primary underline hover:no-underline font-medium"
|
||||
onClick={() => setShowImageModelDialog(true)}
|
||||
>
|
||||
Change image model
|
||||
</button>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
</div>
|
||||
<ImageModelDialog
|
||||
open={showImageModelDialog}
|
||||
onOpenChange={setShowImageModelDialog}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get tool information including icon, title, and calling title
|
||||
*/
|
||||
function getToolInfo(toolName: string, args: Record<string, unknown>): ToolInfo {
|
||||
switch (toolName) {
|
||||
case 'shell':
|
||||
return {
|
||||
icon: Terminal,
|
||||
title: args.command ? String(args.command) : 'Shell Command',
|
||||
callingTitle: args.command ? String(args.command) : 'Running Shell Command',
|
||||
errorTitle: args.command ? `Failed: ${String(args.command)}` : 'Shell Command Failed',
|
||||
};
|
||||
|
||||
case 'text_editor_view': {
|
||||
const path = args.path ? String(args.path) : 'File';
|
||||
const hasLineRange = args.start_line || args.end_line;
|
||||
const lineInfo = hasLineRange
|
||||
? ` (lines ${args.start_line || 1}-${args.end_line || 'end'})`
|
||||
: '';
|
||||
return {
|
||||
icon: Eye,
|
||||
title: `Viewed ${path}${lineInfo}`,
|
||||
callingTitle: `Viewing ${path}${lineInfo}`,
|
||||
errorTitle: `Failed to view ${path}${lineInfo}`,
|
||||
};
|
||||
}
|
||||
|
||||
case 'text_editor_write':
|
||||
return {
|
||||
icon: FileText,
|
||||
title: args.path ? `Wrote ${args.path}` : 'Wrote File',
|
||||
callingTitle: args.path ? `Writing ${args.path}` : 'Writing File',
|
||||
errorTitle: args.path ? `Failed to write ${args.path}` : 'Failed to Write File',
|
||||
};
|
||||
|
||||
case 'text_editor_str_replace':
|
||||
return {
|
||||
icon: Edit,
|
||||
title: args.path ? `Edited ${args.path}` : 'Edited File',
|
||||
callingTitle: args.path ? `Editing ${args.path}` : 'Editing File',
|
||||
errorTitle: args.path ? `Failed to edit ${args.path}` : 'Failed to Edit File',
|
||||
};
|
||||
|
||||
case 'npm_add_package': {
|
||||
const name = args.name ? String(args.name) : 'Package';
|
||||
const devSuffix = args.dev ? ' (dev)' : '';
|
||||
return {
|
||||
icon: Package,
|
||||
title: `Installed ${name}${devSuffix}`,
|
||||
callingTitle: `Installing ${name}${devSuffix}`,
|
||||
errorTitle: `Failed to install ${name}${devSuffix}`,
|
||||
};
|
||||
}
|
||||
|
||||
case 'npm_remove_package':
|
||||
return {
|
||||
icon: PackageMinus,
|
||||
title: args.name ? `Removed ${args.name}` : 'Removed Package',
|
||||
callingTitle: args.name ? `Removing ${args.name}` : 'Removing Package',
|
||||
errorTitle: args.name ? `Failed to remove ${args.name}` : 'Failed to Remove Package',
|
||||
};
|
||||
|
||||
case 'git_commit':
|
||||
return {
|
||||
icon: GitCommit,
|
||||
title: args.message ? `Committed: ${args.message}` : 'Committed Changes',
|
||||
callingTitle: args.message ? `Committing: ${args.message}` : 'Committing Changes',
|
||||
errorTitle: 'Failed to Commit Changes',
|
||||
};
|
||||
|
||||
case 'build_project':
|
||||
return {
|
||||
icon: Package,
|
||||
title: 'Built Project',
|
||||
callingTitle: 'Building Project',
|
||||
errorTitle: 'Failed to Build Project',
|
||||
};
|
||||
|
||||
case 'nostr_read_nip':
|
||||
return {
|
||||
icon: BookOpen,
|
||||
title: args.nip ? `Read NIP-${args.nip}` : 'Read NIP',
|
||||
callingTitle: args.nip ? `Reading NIP-${args.nip}` : 'Reading NIP',
|
||||
errorTitle: args.nip ? `Failed to read NIP-${args.nip}` : 'Failed to Read NIP',
|
||||
};
|
||||
|
||||
case 'nostr_fetch_event':
|
||||
return {
|
||||
icon: Download,
|
||||
title: args.identifier ? `Fetched ${String(args.identifier).slice(0, 16)}...` : 'Fetched Event',
|
||||
callingTitle: args.identifier ? `Fetching ${String(args.identifier).slice(0, 16)}...` : 'Fetching Event',
|
||||
errorTitle: args.identifier ? `Failed to fetch ${String(args.identifier).slice(0, 16)}...` : 'Failed to Fetch Event',
|
||||
};
|
||||
|
||||
case 'nostr_read_kind':
|
||||
return {
|
||||
icon: Hash,
|
||||
title: args.kind !== undefined ? `Read Kind ${args.kind}` : 'Read Kind',
|
||||
callingTitle: args.kind !== undefined ? `Reading Kind ${args.kind}` : 'Reading Kind',
|
||||
errorTitle: args.kind !== undefined ? `Failed to read Kind ${args.kind}` : 'Failed to Read Kind',
|
||||
};
|
||||
|
||||
case 'nostr_read_tag':
|
||||
return {
|
||||
icon: Tag,
|
||||
title: args.tag ? `Read Tag "${args.tag}"` : 'Read Tag',
|
||||
callingTitle: args.tag ? `Reading Tag "${args.tag}"` : 'Reading Tag',
|
||||
errorTitle: args.tag ? `Failed to read Tag "${args.tag}"` : 'Failed to Read Tag',
|
||||
};
|
||||
|
||||
case 'nostr_read_protocol':
|
||||
return {
|
||||
icon: Network,
|
||||
title: args.doc ? `Read Protocol: ${args.doc}` : 'Read Protocol',
|
||||
callingTitle: args.doc ? `Reading Protocol: ${args.doc}` : 'Reading Protocol',
|
||||
errorTitle: args.doc ? `Failed to read Protocol: ${args.doc}` : 'Failed to Read Protocol',
|
||||
};
|
||||
|
||||
case 'nostr_read_nips_index':
|
||||
return {
|
||||
icon: List,
|
||||
title: 'Read NIPs Index',
|
||||
callingTitle: 'Reading NIPs Index',
|
||||
errorTitle: 'Failed to Read NIPs Index',
|
||||
};
|
||||
|
||||
case 'nostr_generate_kind':
|
||||
return {
|
||||
icon: Plus,
|
||||
title: args.range ? `Generated ${args.range} kind` : 'Generated Kind',
|
||||
callingTitle: args.range ? `Generating ${args.range} kind` : 'Generating Kind',
|
||||
errorTitle: args.range ? `Failed to generate ${args.range} kind` : 'Failed to Generate Kind',
|
||||
};
|
||||
|
||||
case 'nostr_publish_events': {
|
||||
const eventCount = Array.isArray(args.events) ? args.events.length : 0;
|
||||
return {
|
||||
icon: Send,
|
||||
title: eventCount > 1 ? `Published ${eventCount} Nostr events` : 'Published Nostr event',
|
||||
callingTitle: eventCount > 1 ? `Publishing ${eventCount} Nostr events` : 'Publishing Nostr event',
|
||||
errorTitle: eventCount > 1 ? `Failed to publish ${eventCount} Nostr events` : 'Failed to Publish Nostr Event',
|
||||
};
|
||||
}
|
||||
|
||||
case 'deploy_project':
|
||||
return {
|
||||
icon: Globe,
|
||||
title: args.deployServer ? `Deployed to ${args.deployServer}` : 'Deployed Project',
|
||||
callingTitle: args.deployServer ? `Deploying to ${args.deployServer}` : 'Deploying Project',
|
||||
errorTitle: args.deployServer ? `Failed to deploy to ${args.deployServer}` : 'Failed to Deploy Project',
|
||||
};
|
||||
|
||||
case 'read_console_messages':
|
||||
return {
|
||||
icon: Logs,
|
||||
title: 'Read Console',
|
||||
callingTitle: 'Reading Console',
|
||||
errorTitle: 'Failed to Read Console',
|
||||
};
|
||||
|
||||
case 'skill':
|
||||
return {
|
||||
icon: Puzzle,
|
||||
title: args.name ? `Skill: ${args.name}` : 'Skill',
|
||||
callingTitle: args.name ? `Running Skill: ${args.name}` : 'Running Skill',
|
||||
errorTitle: args.name ? `Skill Failed: ${args.name}` : 'Skill Failed',
|
||||
};
|
||||
|
||||
case 'generate_image':
|
||||
return {
|
||||
icon: Image,
|
||||
title: args.prompt ? String(args.prompt) : 'Generated Image',
|
||||
callingTitle: args.prompt ? String(args.prompt) : 'Generating Image',
|
||||
errorTitle: 'Failed to Generate Image',
|
||||
};
|
||||
|
||||
case 'view_available_models':
|
||||
return {
|
||||
icon: Eye,
|
||||
title: 'Viewed Available Models',
|
||||
callingTitle: 'Viewing Available Models',
|
||||
errorTitle: 'Failed to View Available Models',
|
||||
};
|
||||
|
||||
case 'configure_image_generation':
|
||||
return {
|
||||
icon: Settings,
|
||||
title: args.model ? `Configured image model: ${args.model}` : 'Configured Image Generation',
|
||||
callingTitle: args.model ? `Configuring image model: ${args.model}` : 'Configuring Image Generation',
|
||||
errorTitle: args.model ? `Failed to configure image model: ${args.model}` : 'Failed to Configure Image Generation',
|
||||
};
|
||||
|
||||
default: {
|
||||
const formattedName = toolName.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
|
||||
return {
|
||||
icon: Wrench,
|
||||
title: formattedName,
|
||||
callingTitle: formattedName,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse tool error from result string
|
||||
* Format: "Error with tool {toolName}: {errorMsg}"
|
||||
* Returns null if not an error or if format doesn't match exactly
|
||||
*/
|
||||
function parseToolError(result: string | undefined, expectedToolName: string): string | null {
|
||||
if (!result) return null;
|
||||
|
||||
// Strict parsing - exact format required
|
||||
const prefix = `Error with tool ${expectedToolName}: `;
|
||||
if (!result.startsWith(prefix)) return null;
|
||||
|
||||
// Extract error message after the prefix
|
||||
return result.substring(prefix.length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unified component for displaying tool calls in all states
|
||||
*/
|
||||
export function ToolCallDisplay({ toolName, toolArgs, state, result }: ToolCallDisplayProps) {
|
||||
const [isExpanded, setIsExpanded] = useState(false);
|
||||
const [expandedImageUrl, setExpandedImageUrl] = useState<string | null>(null);
|
||||
const [imageLoadError, setImageLoadError] = useState(false);
|
||||
|
||||
const toolInfo = getToolInfo(toolName, toolArgs);
|
||||
const IconComponent = toolInfo.icon;
|
||||
|
||||
// Check if this is an error result
|
||||
const errorMessage = state === 'completed' ? parseToolError(result, toolName) : null;
|
||||
const hasError = errorMessage !== null;
|
||||
|
||||
// Determine which title to show based on state
|
||||
let displayTitle: string;
|
||||
if (hasError && toolInfo.errorTitle) {
|
||||
displayTitle = toolInfo.errorTitle;
|
||||
} else if (state === 'completed') {
|
||||
displayTitle = toolInfo.title;
|
||||
} else {
|
||||
displayTitle = toolInfo.callingTitle || toolInfo.title;
|
||||
}
|
||||
|
||||
// Only allow clicking when completed
|
||||
const isClickable = state === 'completed';
|
||||
|
||||
// Render special content for specific tools when expanded
|
||||
const renderExpandedContent = () => {
|
||||
if (!result || !isExpanded) return null;
|
||||
|
||||
// Show error message if present and expanded
|
||||
if (hasError) {
|
||||
return (
|
||||
<div className="mt-1 p-3 bg-destructive/5 rounded border border-destructive/20 text-xs">
|
||||
<div className="flex gap-2">
|
||||
<TriangleAlert className="h-4 w-4 text-destructive flex-shrink-0 mt-0.5" />
|
||||
<div className="whitespace-pre-wrap break-words text-foreground">
|
||||
{errorMessage}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (toolName === 'text_editor_write' && typeof toolArgs.file_text === 'string') {
|
||||
return (
|
||||
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
|
||||
<div className="whitespace-pre-wrap break-words font-mono">
|
||||
{toolArgs.file_text}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (toolName === 'text_editor_str_replace' && typeof toolArgs.old_str === 'string' && typeof toolArgs.new_str === 'string') {
|
||||
const oldLines = String(toolArgs.old_str).split('\n');
|
||||
const newLines = String(toolArgs.new_str).split('\n');
|
||||
|
||||
return (
|
||||
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs font-mono">
|
||||
<div className="space-y-1">
|
||||
{/* Old content (removed) */}
|
||||
<div className="space-y-0">
|
||||
{oldLines.map((line, index) => (
|
||||
<div key={`old-${index}`} className="flex">
|
||||
<span className="text-red-500 select-none mr-2">-</span>
|
||||
<span className="bg-red-50 dark:bg-red-950/30 text-red-700 dark:text-red-300 flex-1 whitespace-pre-wrap break-words">
|
||||
{line}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* New content (added) */}
|
||||
<div className="space-y-0">
|
||||
{newLines.map((line, index) => (
|
||||
<div key={`new-${index}`} className="flex">
|
||||
<span className="text-green-500 select-none mr-2">+</span>
|
||||
<span className="bg-green-50 dark:bg-green-950/30 text-green-700 dark:text-green-300 flex-1 whitespace-pre-wrap break-words">
|
||||
{line}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (toolName === 'generate_image') {
|
||||
// For generate_image, when expanded show the full prompt
|
||||
return (
|
||||
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
|
||||
<div>{typeof toolArgs.prompt === 'string' ? toolArgs.prompt : 'No prompt provided'}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Default rendering for other tools
|
||||
return (
|
||||
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
|
||||
<div className="whitespace-pre-wrap break-words font-mono">
|
||||
{result}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// Special rendering for generate_image - always show image below the tool
|
||||
const renderImageBelowTool = () => {
|
||||
if (hasError) return null;
|
||||
if (toolName !== 'generate_image') return null;
|
||||
|
||||
// Show placeholder while generating (calling or waiting states)
|
||||
if (state === 'calling' || state === 'waiting') {
|
||||
return (
|
||||
<div className="mt-1 p-3 bg-muted/30 rounded border max-w-xs">
|
||||
<div className="relative w-full aspect-square">
|
||||
<div className="w-full h-full rounded bg-muted/50" />
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<Loader2 className="h-12 w-12 text-muted-foreground/30 animate-spin" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// For completed state, we need the result
|
||||
if (!result) return null;
|
||||
|
||||
// Parse "Generated image: <path>" from result
|
||||
// Path can be VFS style (/tmp/...) or OS path (C:/Users/.../Temp/... on Windows)
|
||||
const match = result.match(/Generated image:\s*([^\s\n]+)/);
|
||||
if (match) {
|
||||
const imagePath = match[1];
|
||||
// Handle both forward and back slashes for getting filename
|
||||
const filename = imagePath.split(/[/\\]/).pop() || imagePath;
|
||||
|
||||
// Hide the image section if there was a load error
|
||||
if (imageLoadError) return null;
|
||||
|
||||
return (
|
||||
<div className="mt-1 p-3 bg-muted/30 rounded border max-w-xs">
|
||||
<div
|
||||
className="cursor-pointer hover:opacity-90 transition-opacity"
|
||||
onClick={() => setExpandedImageUrl(imagePath)}
|
||||
>
|
||||
<VFSImage
|
||||
path={imagePath}
|
||||
alt={filename}
|
||||
className="max-w-full h-auto rounded"
|
||||
onError={() => setImageLoadError(true)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
} else {
|
||||
// Image generation failed - show error in place
|
||||
return <ImageGenerationError />;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="-mt-2">
|
||||
<button
|
||||
onClick={() => isClickable && setIsExpanded(!isExpanded)}
|
||||
disabled={!isClickable}
|
||||
className={cn(
|
||||
"w-full flex items-center gap-2 px-2 py-1 text-xs",
|
||||
isClickable && "hover:bg-muted/30 rounded transition-colors duration-200",
|
||||
!isClickable && "cursor-default"
|
||||
)}
|
||||
>
|
||||
{state === 'calling' || state === 'waiting' ? (
|
||||
<Loader2 className="h-3 w-3 text-muted-foreground flex-shrink-0 animate-spin" />
|
||||
) : hasError ? (
|
||||
<X className="h-3 w-3 text-muted-foreground flex-shrink-0" />
|
||||
) : (
|
||||
<IconComponent className="h-3 w-3 text-muted-foreground flex-shrink-0" />
|
||||
)}
|
||||
<span className="text-muted-foreground font-medium truncate flex-1 text-left">
|
||||
{displayTitle}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{renderExpandedContent()}
|
||||
{renderImageBelowTool()}
|
||||
</div>
|
||||
|
||||
{/* Image expansion lightbox */}
|
||||
<ImageLightbox
|
||||
imageUrl={expandedImageUrl}
|
||||
onClose={() => setExpandedImageUrl(null)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { useEffect, useState } from 'react';
|
||||
import { useLocation, useNavigate } from 'react-router-dom';
|
||||
import { AddProviderDialog } from '@/components/AddProviderDialog';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
|
||||
|
||||
/**
|
||||
* Component that handles URL fragments for adding AI providers
|
||||
@@ -30,9 +31,15 @@ export function URLFragmentHandler() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Get name from URL params or derive from presets or id
|
||||
const nameParam = params.get('name');
|
||||
const preset = AI_PROVIDER_PRESETS.find(p => p.id === id);
|
||||
const name = nameParam || preset?.name || id;
|
||||
|
||||
// Build the provider object
|
||||
const provider: AIProvider = {
|
||||
id,
|
||||
name,
|
||||
baseURL,
|
||||
};
|
||||
|
||||
|
||||
@@ -16,8 +16,11 @@ describe('UserMessage', () => {
|
||||
|
||||
render(<UserMessage content={content} />);
|
||||
|
||||
// When using string content, it should still work but won't separate file attachments
|
||||
expect(screen.getByText(content)).toBeInTheDocument();
|
||||
// When using string content, it should parse and separate file attachments
|
||||
expect(screen.getByText('Here is my file:')).toBeInTheDocument();
|
||||
expect(screen.getByText('test.txt')).toBeInTheDocument();
|
||||
// Full path should not be displayed
|
||||
expect(screen.queryByText('/tmp/test.txt')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders file attachment badges for single file with text parts', () => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { FileText, File } from 'lucide-react';
|
||||
import { Paperclip } from 'lucide-react';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import type OpenAI from 'openai';
|
||||
|
||||
@@ -18,21 +18,60 @@ export function UserMessage({ content }: UserMessageProps) {
|
||||
: content.filter(part => part.type === 'text') as Array<{ type: 'text'; text: string }>;
|
||||
|
||||
// Regular expression to match "Added file: /tmp/<filename>" patterns
|
||||
const filePattern = /^Added file: (\/tmp\/[^\s\n]+)$/;
|
||||
// Matches the pattern anywhere in the text
|
||||
const filePattern = /Added file:\s*(\/tmp\/[^\s\n]+)/g;
|
||||
|
||||
// Process each content part and categorize as text or file
|
||||
const processedParts: Array<{ type: 'text' | 'file'; content: string; filepath?: string }> = [];
|
||||
|
||||
contentParts.forEach(part => {
|
||||
const text = part.text.trim();
|
||||
const match = text.match(filePattern);
|
||||
|
||||
// Find all file patterns in this text part
|
||||
const fileMatches: Array<{ filepath: string; index: number; length: number }> = [];
|
||||
let match;
|
||||
filePattern.lastIndex = 0; // Reset regex
|
||||
|
||||
while ((match = filePattern.exec(text)) !== null) {
|
||||
fileMatches.push({
|
||||
filepath: match[1], // "/tmp/filename.txt"
|
||||
index: match.index,
|
||||
length: match[0].length
|
||||
});
|
||||
}
|
||||
|
||||
if (match) {
|
||||
// This is a file attachment
|
||||
const filepath = match[1]; // "/tmp/filename.txt"
|
||||
processedParts.push({ type: 'file', content: text, filepath });
|
||||
if (fileMatches.length > 0) {
|
||||
// Split text around file patterns and process each segment
|
||||
let lastIndex = 0;
|
||||
|
||||
fileMatches.forEach((fileMatch) => {
|
||||
// Add text before the file pattern
|
||||
if (fileMatch.index > lastIndex) {
|
||||
const textBefore = text.substring(lastIndex, fileMatch.index).trim();
|
||||
if (textBefore) {
|
||||
processedParts.push({ type: 'text', content: textBefore });
|
||||
}
|
||||
}
|
||||
|
||||
// Add the file attachment badge (without showing "Added file:" text)
|
||||
processedParts.push({
|
||||
type: 'file',
|
||||
content: '', // Empty - badge will show filename only
|
||||
filepath: fileMatch.filepath
|
||||
});
|
||||
|
||||
lastIndex = fileMatch.index + fileMatch.length;
|
||||
});
|
||||
|
||||
// Add remaining text after the last file pattern
|
||||
if (lastIndex < text.length) {
|
||||
const textAfter = text.substring(lastIndex).trim();
|
||||
if (textAfter) {
|
||||
processedParts.push({ type: 'text', content: textAfter });
|
||||
}
|
||||
}
|
||||
} else if (text) {
|
||||
// This is regular text content
|
||||
// No file patterns found, treat as regular text
|
||||
processedParts.push({ type: 'text', content: text });
|
||||
}
|
||||
});
|
||||
@@ -42,19 +81,6 @@ export function UserMessage({ content }: UserMessageProps) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const getFileIcon = (filename: string) => {
|
||||
const extension = filename.split('.').pop()?.toLowerCase();
|
||||
|
||||
// Return FileText icon for text-like files, File icon for others
|
||||
const textExtensions = ['txt', 'md', 'json', 'js', 'ts', 'jsx', 'tsx', 'css', 'html', 'xml', 'yml', 'yaml'];
|
||||
|
||||
if (extension && textExtensions.includes(extension)) {
|
||||
return <FileText className="h-3 w-3" />;
|
||||
}
|
||||
|
||||
return <File className="h-3 w-3" />;
|
||||
};
|
||||
|
||||
const getFileName = (filepath: string) => {
|
||||
return filepath.split('/').pop() || filepath;
|
||||
};
|
||||
@@ -63,18 +89,25 @@ export function UserMessage({ content }: UserMessageProps) {
|
||||
<div className="space-y-2">
|
||||
{processedParts.map((part, index) => {
|
||||
if (part.type === 'text') {
|
||||
// Only render text if it has content
|
||||
if (!part.content.trim()) return null;
|
||||
return (
|
||||
<div key={index} className="whitespace-pre-wrap">
|
||||
{part.content}
|
||||
</div>
|
||||
);
|
||||
} else {
|
||||
// Render file attachment badge (no "Added file:" text)
|
||||
const filename = getFileName(part.filepath!);
|
||||
return (
|
||||
<div key={index} className="flex items-center gap-2">
|
||||
<Badge variant="secondary" className="flex items-center gap-1.5 px-2 py-1">
|
||||
{getFileIcon(filename)}
|
||||
<span className="text-xs font-medium">{filename}</span>
|
||||
<div key={index} className="flex items-center gap-2 max-w-full min-w-0">
|
||||
<Badge variant="secondary" className="inline-flex items-center gap-1.5 px-2 py-1 max-w-full">
|
||||
<span className="flex-shrink-0">
|
||||
<Paperclip className="h-3 w-3" />
|
||||
</span>
|
||||
<span className="text-xs font-medium truncate min-w-0" title={filename}>
|
||||
{filename}
|
||||
</span>
|
||||
</Badge>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { AlertCircle } from 'lucide-react';
|
||||
|
||||
interface VFSImageProps {
|
||||
path: string;
|
||||
alt: string;
|
||||
className?: string;
|
||||
onClick?: () => void;
|
||||
onError?: (error: string) => void;
|
||||
}
|
||||
|
||||
export function VFSImage({ path, alt, className, onClick, onError }: VFSImageProps) {
|
||||
const { fs } = useFS();
|
||||
const [dataUri, setDataUri] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
let isMounted = true;
|
||||
|
||||
async function loadImage() {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
// Read the file from VFS
|
||||
const imageData = await fs.readFile(path);
|
||||
|
||||
if (!isMounted) return;
|
||||
|
||||
// Determine MIME type from file extension
|
||||
const extension = path.split('.').pop()?.toLowerCase() || '';
|
||||
const mimeTypes: Record<string, string> = {
|
||||
'png': 'image/png',
|
||||
'jpg': 'image/jpeg',
|
||||
'jpeg': 'image/jpeg',
|
||||
'gif': 'image/gif',
|
||||
'webp': 'image/webp',
|
||||
'svg': 'image/svg+xml',
|
||||
'bmp': 'image/bmp',
|
||||
};
|
||||
const mimeType = mimeTypes[extension] || 'image/png';
|
||||
|
||||
// Convert bytes to base64
|
||||
const base64 = btoa(
|
||||
Array.from(imageData)
|
||||
.map(byte => String.fromCharCode(byte))
|
||||
.join('')
|
||||
);
|
||||
|
||||
// Create data URI
|
||||
const uri = `data:${mimeType};base64,${base64}`;
|
||||
|
||||
if (isMounted) {
|
||||
setDataUri(uri);
|
||||
setIsLoading(false);
|
||||
}
|
||||
} catch (err) {
|
||||
if (isMounted) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to load image';
|
||||
setError(errorMessage);
|
||||
setIsLoading(false);
|
||||
onError?.(errorMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
loadImage();
|
||||
|
||||
return () => {
|
||||
isMounted = false;
|
||||
};
|
||||
}, [fs, onError, path]);
|
||||
|
||||
if (isLoading) {
|
||||
return <Skeleton className={className || 'w-full h-64'} />;
|
||||
}
|
||||
|
||||
if (error || !dataUri) {
|
||||
return (
|
||||
<div className={className || 'w-full h-64 flex items-center justify-center bg-muted rounded'}>
|
||||
<div className="text-center text-muted-foreground space-y-2">
|
||||
<AlertCircle className="h-8 w-8 mx-auto" />
|
||||
<p className="text-xs">{error || 'Failed to load image'}</p>
|
||||
<p className="text-xs font-mono">{path}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<img
|
||||
src={dataUri}
|
||||
alt={alt}
|
||||
className={className}
|
||||
onClick={onClick}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import { formatRelativeTime } from '@/lib/utils';
|
||||
|
||||
interface GitCommit {
|
||||
oid: string;
|
||||
@@ -336,24 +337,6 @@ ${commitsToRevert.map(c => {
|
||||
}
|
||||
}, [isOpen, loadGitHistory]);
|
||||
|
||||
const formatRelativeTime = (timestamp: number) => {
|
||||
const now = Date.now();
|
||||
const commitTime = timestamp * 1000;
|
||||
const diffMs = now - commitTime;
|
||||
|
||||
const diffMinutes = Math.floor(diffMs / (1000 * 60));
|
||||
const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
|
||||
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
|
||||
|
||||
if (diffMinutes < 60) {
|
||||
return `${diffMinutes} minutes ago`;
|
||||
} else if (diffHours < 24) {
|
||||
return `${diffHours} hours ago`;
|
||||
} else {
|
||||
return `${diffDays} days ago`;
|
||||
}
|
||||
};
|
||||
|
||||
const getCommitMessageLines = (message: string) => {
|
||||
const lines = message.split('\n').filter(line => line.trim() !== '');
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { Plus, ExternalLink } from 'lucide-react';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { proxyUrl } from '@/lib/proxyUrl';
|
||||
|
||||
interface CloudflareWorkerScript {
|
||||
id: string;
|
||||
etag: string;
|
||||
handlers: string[];
|
||||
modified_on: string;
|
||||
created_on: string;
|
||||
has_assets: boolean;
|
||||
}
|
||||
|
||||
interface CloudflareDeployFormProps {
|
||||
apiKey: string;
|
||||
accountId: string;
|
||||
baseURL?: string;
|
||||
baseDomain?: string;
|
||||
projectId: string;
|
||||
projectName?: string;
|
||||
savedProjectName?: string;
|
||||
onProjectChange: (projectName: string) => void;
|
||||
corsProxy?: string;
|
||||
}
|
||||
|
||||
export function CloudflareDeployForm({
|
||||
apiKey,
|
||||
accountId,
|
||||
baseURL = 'https://api.cloudflare.com/client/v4',
|
||||
baseDomain = 'workers.dev',
|
||||
projectId,
|
||||
projectName,
|
||||
savedProjectName,
|
||||
onProjectChange,
|
||||
corsProxy,
|
||||
}: CloudflareDeployFormProps) {
|
||||
const [workers, setWorkers] = useState<CloudflareWorkerScript[]>([]);
|
||||
const [workersSubdomain, setWorkersSubdomain] = useState<string | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [selectedProjectName, setSelectedProjectName] = useState<string>('');
|
||||
const [newProjectName, setNewProjectName] = useState(projectName || projectId);
|
||||
|
||||
const fetchWorkersData = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
// Fetch workers subdomain and workers list in parallel
|
||||
const subdomainUrl = `${baseURL}/accounts/${accountId}/workers/subdomain`;
|
||||
const workersUrl = `${baseURL}/accounts/${accountId}/workers/scripts`;
|
||||
|
||||
const [subdomainResponse, workersResponse] = await Promise.all([
|
||||
fetch(corsProxy ? proxyUrl(corsProxy, subdomainUrl) : subdomainUrl, {
|
||||
headers: { 'Authorization': `Bearer ${apiKey}` },
|
||||
}),
|
||||
fetch(corsProxy ? proxyUrl(corsProxy, workersUrl) : workersUrl, {
|
||||
headers: { 'Authorization': `Bearer ${apiKey}` },
|
||||
}),
|
||||
]);
|
||||
|
||||
if (!subdomainResponse.ok) {
|
||||
throw new Error(`Failed to fetch workers subdomain: ${subdomainResponse.status} ${subdomainResponse.statusText}`);
|
||||
}
|
||||
|
||||
if (!workersResponse.ok) {
|
||||
throw new Error(`Failed to fetch workers: ${workersResponse.status} ${workersResponse.statusText}`);
|
||||
}
|
||||
|
||||
const [subdomainData, workersData] = await Promise.all([
|
||||
subdomainResponse.json(),
|
||||
workersResponse.json(),
|
||||
]);
|
||||
|
||||
setWorkersSubdomain(subdomainData.result?.subdomain || null);
|
||||
setWorkers(workersData.result || []);
|
||||
|
||||
// If there's a saved project name and it exists in the list, select it
|
||||
// Otherwise leave it empty (showing placeholder)
|
||||
if (savedProjectName && workersData.result?.some((w: CloudflareWorkerScript) => w.id === savedProjectName)) {
|
||||
setSelectedProjectName(savedProjectName);
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to fetch workers data');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [apiKey, accountId, baseURL, savedProjectName, corsProxy]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchWorkersData();
|
||||
}, [fetchWorkersData]);
|
||||
|
||||
// Update newProjectName when switching to "new" if it's empty
|
||||
useEffect(() => {
|
||||
if (selectedProjectName === 'new' && !newProjectName) {
|
||||
setNewProjectName(projectName || projectId);
|
||||
}
|
||||
}, [selectedProjectName, newProjectName, projectName, projectId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedProjectName === '') {
|
||||
// No selection yet - don't call onProjectChange
|
||||
return;
|
||||
} else if (selectedProjectName === 'new') {
|
||||
onProjectChange(newProjectName);
|
||||
} else {
|
||||
onProjectChange(selectedProjectName);
|
||||
}
|
||||
}, [selectedProjectName, newProjectName, onProjectChange]);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Project</Label>
|
||||
<Skeleton className="h-10 w-full" />
|
||||
</div>
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const selectedWorker = workers.find(w => w.id === selectedProjectName);
|
||||
|
||||
// Construct the URL preview
|
||||
const getWorkerUrl = (scriptName: string) => {
|
||||
if (workersSubdomain) {
|
||||
return `https://${scriptName}.${workersSubdomain}.${baseDomain}`;
|
||||
}
|
||||
return `https://${scriptName}.<subdomain>.${baseDomain}`;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="cloudflare-project">Select Worker</Label>
|
||||
<Select value={selectedProjectName} onValueChange={setSelectedProjectName}>
|
||||
<SelectTrigger id="cloudflare-project">
|
||||
<SelectValue placeholder="Select a worker or create new..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="new">
|
||||
<div className="flex items-center gap-2">
|
||||
<Plus className="h-4 w-4" />
|
||||
Create new worker
|
||||
</div>
|
||||
</SelectItem>
|
||||
{workers.map((worker) => (
|
||||
<SelectItem key={worker.id} value={worker.id}>
|
||||
{worker.id}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{selectedProjectName === 'new' ? (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="new-project-name">New Worker Name</Label>
|
||||
<Input
|
||||
id="new-project-name"
|
||||
value={newProjectName}
|
||||
onChange={(e) => setNewProjectName(e.target.value)}
|
||||
placeholder={projectName || projectId}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
URL: <span className="font-mono">{getWorkerUrl(newProjectName || projectId)}</span>
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
A new worker will be created when you deploy
|
||||
</p>
|
||||
</div>
|
||||
) : selectedWorker ? (
|
||||
<div className="space-y-2">
|
||||
<div className="rounded-lg border p-3 space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium">{selectedWorker.id}</p>
|
||||
<p className="text-xs text-muted-foreground font-mono">
|
||||
{getWorkerUrl(selectedWorker.id)}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => window.open(`https://dash.cloudflare.com/${accountId}/workers/services/view/${selectedWorker.id}`, '_blank')}
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Deployment will update this existing worker
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { Plus, ExternalLink } from 'lucide-react';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { proxyUrl } from '@/lib/proxyUrl';
|
||||
|
||||
interface DenoProject {
|
||||
id: string;
|
||||
name: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
interface DenoDeployFormProps {
|
||||
apiKey: string;
|
||||
organizationId: string;
|
||||
baseURL?: string;
|
||||
baseDomain?: string;
|
||||
projectId: string;
|
||||
projectName?: string;
|
||||
savedProjectName?: string;
|
||||
onProjectChange: (projectName: string) => void;
|
||||
corsProxy?: string;
|
||||
}
|
||||
|
||||
export function DenoDeployForm({
|
||||
apiKey,
|
||||
organizationId,
|
||||
baseURL = 'https://api.deno.com/v1',
|
||||
baseDomain = 'deno.dev',
|
||||
projectId,
|
||||
projectName,
|
||||
savedProjectName,
|
||||
onProjectChange,
|
||||
corsProxy,
|
||||
}: DenoDeployFormProps) {
|
||||
const [projects, setProjects] = useState<DenoProject[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [selectedProjectName, setSelectedProjectName] = useState<string>('');
|
||||
const [newProjectName, setNewProjectName] = useState(projectName || projectId);
|
||||
|
||||
const fetchProjects = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const url = `${baseURL}/organizations/${organizationId}/projects?limit=100`;
|
||||
const targetUrl = corsProxy ? proxyUrl(corsProxy, url) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
headers: { 'Authorization': `Bearer ${apiKey}` },
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch projects: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const data: DenoProject[] = await response.json();
|
||||
setProjects(data);
|
||||
|
||||
// If there's a saved project name and it exists in the list, select it
|
||||
// Otherwise leave it empty (showing placeholder)
|
||||
if (savedProjectName && data.some((p: DenoProject) => p.name === savedProjectName)) {
|
||||
setSelectedProjectName(savedProjectName);
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to fetch projects');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [apiKey, organizationId, baseURL, savedProjectName, corsProxy]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchProjects();
|
||||
}, [fetchProjects]);
|
||||
|
||||
// Update newProjectName when switching to "new" if it's empty
|
||||
useEffect(() => {
|
||||
if (selectedProjectName === 'new' && !newProjectName) {
|
||||
setNewProjectName(projectName || projectId);
|
||||
}
|
||||
}, [selectedProjectName, newProjectName, projectName, projectId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedProjectName === '') {
|
||||
// No selection yet - don't call onProjectChange
|
||||
return;
|
||||
} else if (selectedProjectName === 'new') {
|
||||
onProjectChange(newProjectName);
|
||||
} else {
|
||||
onProjectChange(selectedProjectName);
|
||||
}
|
||||
}, [selectedProjectName, newProjectName, onProjectChange]);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Project</Label>
|
||||
<Skeleton className="h-10 w-full" />
|
||||
</div>
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const selectedProject = projects.find(p => p.name === selectedProjectName);
|
||||
|
||||
// Construct the URL preview
|
||||
const getProjectUrl = (name: string) => {
|
||||
return `https://${name}.${baseDomain}`;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="deno-project">Select Project</Label>
|
||||
<Select value={selectedProjectName} onValueChange={setSelectedProjectName}>
|
||||
<SelectTrigger id="deno-project">
|
||||
<SelectValue placeholder="Select a project or create new..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="new">
|
||||
<div className="flex items-center gap-2">
|
||||
<Plus className="h-4 w-4" />
|
||||
Create new project
|
||||
</div>
|
||||
</SelectItem>
|
||||
{projects.map((project) => (
|
||||
<SelectItem key={project.id} value={project.name}>
|
||||
{project.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{selectedProjectName === 'new' ? (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="new-project-name">New Project Name</Label>
|
||||
<Input
|
||||
id="new-project-name"
|
||||
value={newProjectName}
|
||||
onChange={(e) => setNewProjectName(e.target.value)}
|
||||
placeholder={projectName || projectId}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
URL: <span className="font-mono">{getProjectUrl(newProjectName || projectId)}</span>
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
A new project will be created when you deploy
|
||||
</p>
|
||||
</div>
|
||||
) : selectedProject ? (
|
||||
<div className="space-y-2">
|
||||
<div className="rounded-lg border p-3 space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium">{selectedProject.name}</p>
|
||||
<p className="text-xs text-muted-foreground font-mono">
|
||||
{getProjectUrl(selectedProject.name)}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => window.open(`https://dash.deno.com/projects/${selectedProject.name}`, '_blank')}
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Deployment will create a new version for this project
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,24 +1,42 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { AlertCircle } from 'lucide-react';
|
||||
|
||||
interface ShakespeareDeployFormProps {
|
||||
host?: string;
|
||||
projectId: string;
|
||||
savedSubdomain?: string;
|
||||
onSubdomainChange: (subdomain: string) => void;
|
||||
onValidationChange?: (isValid: boolean) => void;
|
||||
}
|
||||
|
||||
export function ShakespeareDeployForm({
|
||||
host = 'shakespeare.wtf',
|
||||
projectId,
|
||||
savedSubdomain,
|
||||
onSubdomainChange,
|
||||
onValidationChange,
|
||||
}: ShakespeareDeployFormProps) {
|
||||
const [subdomain, setSubdomain] = useState(projectId);
|
||||
const [subdomain, setSubdomain] = useState(savedSubdomain || projectId);
|
||||
|
||||
// Update subdomain when savedSubdomain changes (e.g., when switching providers)
|
||||
useEffect(() => {
|
||||
setSubdomain(savedSubdomain || projectId);
|
||||
}, [savedSubdomain, projectId]);
|
||||
|
||||
// Validate subdomain: no periods allowed (only single-level subdomains)
|
||||
const hasPeriod = subdomain.includes('.');
|
||||
const isValid = subdomain.trim() !== '' && !hasPeriod;
|
||||
|
||||
useEffect(() => {
|
||||
onSubdomainChange(subdomain);
|
||||
}, [subdomain, onSubdomainChange]);
|
||||
|
||||
useEffect(() => {
|
||||
onValidationChange?.(isValid);
|
||||
}, [isValid, onValidationChange]);
|
||||
|
||||
const fullDomain = subdomain ? `${subdomain}.${host}` : `${projectId}.${host}`;
|
||||
|
||||
return (
|
||||
@@ -30,7 +48,14 @@ export function ShakespeareDeployForm({
|
||||
value={subdomain}
|
||||
onChange={(e) => setSubdomain(e.target.value)}
|
||||
placeholder={projectId}
|
||||
className={hasPeriod ? 'border-destructive' : ''}
|
||||
/>
|
||||
{hasPeriod && (
|
||||
<div className="flex items-start gap-2 text-sm text-destructive">
|
||||
<AlertCircle className="h-4 w-4 mt-0.5 flex-shrink-0" />
|
||||
<span>Subdomain cannot contain periods. Use hyphens instead (e.g., "nostr-radar").</span>
|
||||
</div>
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Will deploy to: <span className="font-mono">{fullDomain}</span>
|
||||
</p>
|
||||
|
||||
@@ -2,3 +2,5 @@ export { ShakespeareDeployForm } from './ShakespeareDeployForm';
|
||||
export { NetlifyDeployForm } from './NetlifyDeployForm';
|
||||
export { VercelDeployForm } from './VercelDeployForm';
|
||||
export { NsiteDeployForm } from './NsiteDeployForm';
|
||||
export { CloudflareDeployForm } from './CloudflareDeployForm';
|
||||
export { DenoDeployForm } from './DenoDeployForm';
|
||||
@@ -3,6 +3,7 @@ import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { TagInput } from '@/components/ui/tag-input';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
@@ -33,12 +34,15 @@ import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostr } from '@/hooks/useNostr';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { DotAI } from '@/lib/DotAI';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import {
|
||||
createRepositoryAnnouncementEvent,
|
||||
createRepositoryNaddr,
|
||||
validateRepositoryAnnouncementData,
|
||||
validateRepositoryId,
|
||||
parseRepositoryAnnouncement,
|
||||
} from '@/lib/announceRepository';
|
||||
|
||||
export interface AnnounceRepositoryResult {
|
||||
@@ -74,6 +78,7 @@ export function AnnounceRepositoryDialog({
|
||||
const [webUrls, setWebUrls] = useState<string[]>([]);
|
||||
const [cloneUrls, setCloneUrls] = useState<string[]>([]);
|
||||
const [relays, setRelays] = useState<string[]>([]);
|
||||
const [tTags, setTTags] = useState<string[]>([]);
|
||||
const [earliestCommit, setEarliestCommit] = useState('');
|
||||
const [isCreating, setIsCreating] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
@@ -88,6 +93,7 @@ export function AnnounceRepositoryDialog({
|
||||
const { nostr } = useNostr();
|
||||
const { toast } = useToast();
|
||||
const { config } = useAppContext();
|
||||
const { fs } = useFS();
|
||||
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
|
||||
@@ -145,37 +151,57 @@ export function AnnounceRepositoryDialog({
|
||||
.join(' ');
|
||||
setName(defaultName);
|
||||
|
||||
// Only prepopulate if the arrays are empty (user hasn't made changes yet)
|
||||
if (cloneUrls.length === 0 && relays.length === 0) {
|
||||
// Prepopulate clone URLs and relays from ngitServers (matching original handlePushToNostr)
|
||||
if (user?.pubkey && config.ngitServers && config.ngitServers.length > 0) {
|
||||
// Clone URLs: https://{server}/{npub}/{repo-id}.git
|
||||
const npub = nip19.npubEncode(user.pubkey);
|
||||
const cloneUrls = config.ngitServers.map(server =>
|
||||
`https://${server}/${npub}/${defaultRepoId}.git`
|
||||
);
|
||||
setCloneUrls(cloneUrls);
|
||||
// Prepopulate clone URLs and relays from ngitServers (matching original handlePushToNostr)
|
||||
if (user?.pubkey && config.ngitServers && config.ngitServers.length > 0) {
|
||||
// Clone URLs: https://{server}/{npub}/{repo-id}.git
|
||||
const npub = nip19.npubEncode(user.pubkey);
|
||||
const cloneUrls = config.ngitServers.map(server =>
|
||||
`https://${server}/${npub}/${defaultRepoId}.git`
|
||||
);
|
||||
setCloneUrls(cloneUrls);
|
||||
|
||||
// Relay URLs: wss://{server}
|
||||
const relayUrls = config.ngitServers.map(server => `wss://${server}`);
|
||||
setRelays(relayUrls);
|
||||
} else {
|
||||
// Fallback to write relays if no ngitServers configured
|
||||
const writeRelays = config.relayMetadata.relays
|
||||
.filter(r => r.write)
|
||||
.map(r => r.url);
|
||||
setRelays(writeRelays.length > 0 ? writeRelays : ['wss://relay.nostr.band']);
|
||||
}
|
||||
// Relay URLs: wss://{server}
|
||||
const relayUrls = config.ngitServers.map(server => `wss://${server}`);
|
||||
setRelays(relayUrls);
|
||||
} else {
|
||||
// Fallback to write relays if no ngitServers configured
|
||||
const writeRelays = config.relayMetadata.relays
|
||||
.filter(r => r.write)
|
||||
.map(r => r.url);
|
||||
setRelays(writeRelays.length > 0 ? writeRelays : ['wss://relay.nostr.band']);
|
||||
}
|
||||
|
||||
// Prepopulate t-tags
|
||||
const defaultTTags: string[] = ['shakespeare'];
|
||||
|
||||
// Try to read template.json to get template name
|
||||
try {
|
||||
const dotAI = new DotAI(fs, projectPath);
|
||||
const template = await dotAI.readTemplate();
|
||||
if (template?.name) {
|
||||
// Convert template name to lowercase and add as t-tag
|
||||
const templateTag = template.name.toLowerCase();
|
||||
if (!defaultTTags.includes(templateTag)) {
|
||||
defaultTTags.push(templateTag);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to read template for t-tags:', error);
|
||||
}
|
||||
|
||||
setTTags(defaultTTags);
|
||||
|
||||
// Get earliest commit
|
||||
await getEarliestCommit();
|
||||
}, [projectId, config.relayMetadata, config.ngitServers, user?.pubkey, getEarliestCommit, cloneUrls.length, relays.length]);
|
||||
}, [projectId, projectPath, fs, config.relayMetadata, config.ngitServers, user?.pubkey, getEarliestCommit]);
|
||||
|
||||
// Load existing repository data if editing
|
||||
// Load existing repository data if editing, or prepopulate fields for new repos
|
||||
useEffect(() => {
|
||||
// Only run when dialog opens
|
||||
if (!isOpen || isPrepopulated) return;
|
||||
|
||||
const loadExistingRepo = async () => {
|
||||
if (!editNaddr || !isOpen) return;
|
||||
if (!editNaddr) return;
|
||||
|
||||
try {
|
||||
// Decode the naddr to get repository coordinates
|
||||
@@ -209,21 +235,23 @@ export function AnnounceRepositoryDialog({
|
||||
// Use the most recent event
|
||||
const event = events.sort((a, b) => b.created_at - a.created_at)[0];
|
||||
|
||||
// Parse tags to populate form fields
|
||||
const nameTag = event.tags.find(([name]) => name === 'name');
|
||||
const descriptionTag = event.tags.find(([name]) => name === 'description');
|
||||
const webTag = event.tags.find(([name]) => name === 'web');
|
||||
const cloneTag = event.tags.find(([name]) => name === 'clone');
|
||||
const relaysTag = event.tags.find(([name]) => name === 'relays');
|
||||
const eucTag = event.tags.find(([name, , marker]) => name === 'r' && marker === 'euc');
|
||||
// Parse the NIP-34 repository announcement
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
|
||||
setRepoId(identifier);
|
||||
setName(nameTag?.[1] || '');
|
||||
setDescription(descriptionTag?.[1] || '');
|
||||
setWebUrls(webTag ? webTag.slice(1) : []);
|
||||
setCloneUrls(cloneTag ? cloneTag.slice(1) : []);
|
||||
setRelays(relaysTag ? relaysTag.slice(1) : []);
|
||||
setEarliestCommit(eucTag?.[1] || '');
|
||||
setRepoId(parsed.identifier);
|
||||
setName(parsed.name || '');
|
||||
setDescription(parsed.description || '');
|
||||
setWebUrls(parsed.webUrls);
|
||||
setCloneUrls(parsed.httpsCloneUrls);
|
||||
setRelays(parsed.relays);
|
||||
setEarliestCommit(parsed.earliestCommit || '');
|
||||
|
||||
// Extract t-tags from the event
|
||||
const extractedTTags = parsed.event.tags
|
||||
.filter(([name]) => name === 't')
|
||||
.map(([, value]) => value)
|
||||
.filter((value): value is string => !!value);
|
||||
setTTags(extractedTTags);
|
||||
|
||||
setIsPrepopulated(true);
|
||||
} catch (error) {
|
||||
@@ -236,13 +264,13 @@ export function AnnounceRepositoryDialog({
|
||||
}
|
||||
};
|
||||
|
||||
if (isOpen && editNaddr) {
|
||||
if (editNaddr) {
|
||||
loadExistingRepo();
|
||||
} else if (isOpen && !isPrepopulated) {
|
||||
} else {
|
||||
prepopulateFields();
|
||||
setIsPrepopulated(true);
|
||||
}
|
||||
}, [isOpen, isPrepopulated, prepopulateFields, editNaddr, nostr, config.relayMetadata, toast]);
|
||||
}, [isOpen, isPrepopulated, editNaddr, nostr, config.relayMetadata, toast, prepopulateFields]);
|
||||
|
||||
const addWebUrl = () => {
|
||||
if (newWebUrl.trim() && !webUrls.includes(newWebUrl.trim())) {
|
||||
@@ -317,6 +345,7 @@ export function AnnounceRepositoryDialog({
|
||||
webUrls,
|
||||
cloneUrls,
|
||||
relays,
|
||||
tTags,
|
||||
earliestCommit,
|
||||
});
|
||||
|
||||
@@ -389,6 +418,7 @@ export function AnnounceRepositoryDialog({
|
||||
setWebUrls([]);
|
||||
setCloneUrls([]);
|
||||
setRelays(['wss://relay.nostr.band']);
|
||||
setTTags([]);
|
||||
setEarliestCommit('');
|
||||
setError(null);
|
||||
setNewWebUrl('');
|
||||
@@ -414,7 +444,7 @@ export function AnnounceRepositoryDialog({
|
||||
</DialogHeader>
|
||||
|
||||
<ScrollArea className="max-h-[60vh]">
|
||||
<div className="space-y-6 pr-4">
|
||||
<div className="space-y-6 p-1 pr-4">
|
||||
{/* Error alert */}
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
@@ -640,6 +670,23 @@ export function AnnounceRepositoryDialog({
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Category Tags (t-tags) */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="category-tags">Category Tags</Label>
|
||||
<TagInput
|
||||
id="category-tags"
|
||||
value={tTags}
|
||||
onChange={setTTags}
|
||||
placeholder="e.g., nostr, social, web"
|
||||
disabled={isCreating}
|
||||
transformTag={(tag) => tag.trim().toLowerCase()}
|
||||
allowDuplicates={false}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Tags for categorizing your repository. Press space or comma to add a tag.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Earliest Commit */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="earliest-commit">Earliest Unique Commit</Label>
|
||||
|
||||
@@ -187,13 +187,23 @@ export function BranchManager({ projectId, currentBranch, onBranchChange }: Bran
|
||||
object: currentRef,
|
||||
});
|
||||
|
||||
toast({
|
||||
title: 'Branch created',
|
||||
description: `Created branch "${newBranchName}"`,
|
||||
// Automatically check out the new branch
|
||||
await git.checkout({
|
||||
dir: projectPath,
|
||||
ref: newBranchName.trim(),
|
||||
force: true,
|
||||
});
|
||||
|
||||
// Close the dialog before showing the toast
|
||||
setNewBranchName('');
|
||||
setIsCreateDialogOpen(false);
|
||||
|
||||
// Show success toast indicating the branch was created and checked out
|
||||
toast({
|
||||
title: 'Branch created and checked out',
|
||||
description: `Switched to new branch "${newBranchName.trim()}"`,
|
||||
});
|
||||
|
||||
await loadBranches();
|
||||
onBranchChange?.();
|
||||
} catch (error) {
|
||||
@@ -213,7 +223,6 @@ export function BranchManager({ projectId, currentBranch, onBranchChange }: Bran
|
||||
await git.checkout({
|
||||
dir: projectPath,
|
||||
ref: branchName,
|
||||
force: true,
|
||||
});
|
||||
|
||||
toast({
|
||||
|
||||
@@ -39,6 +39,7 @@ import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostr } from '@/hooks/useNostr';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { findCredentialsForRepo } from '@/lib/gitCredentials';
|
||||
import { parseRepositoryAnnouncement } from '@/lib/announceRepository';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import type { GitCredential } from '@/contexts/GitSettingsContext';
|
||||
|
||||
@@ -717,21 +718,20 @@ export function PullRequestDialog({
|
||||
const repoEvent = repoEvents[0];
|
||||
console.log('Found repository announcement event:', repoEvent);
|
||||
|
||||
// Parse the NIP-34 repository announcement
|
||||
const repoAnn = parseRepositoryAnnouncement(repoEvent);
|
||||
|
||||
// Get earliest unique commit from repository announcement
|
||||
const eucTag = repoEvent.tags.find((t: string[]) => t[0] === 'r' && t[2] === 'euc');
|
||||
if (eucTag) {
|
||||
earliestUniqueCommit = eucTag[1];
|
||||
if (repoAnn.earliestCommit) {
|
||||
earliestUniqueCommit = repoAnn.earliestCommit;
|
||||
console.log('Found earliest unique commit:', earliestUniqueCommit);
|
||||
} else {
|
||||
console.warn('No euc tag found in repository announcement');
|
||||
}
|
||||
|
||||
// Get relay hints from repository announcement
|
||||
// Per NIP-34, all relays are in a single tag: ["relays", "wss://...", "wss://...", ...]
|
||||
const relayTag = repoEvent.tags.find((t: string[]) => t[0] === 'relays');
|
||||
if (relayTag && relayTag.length > 1) {
|
||||
// Extract all relay URLs from the tag (skip the first element which is "relays")
|
||||
publishRelays = relayTag.slice(1);
|
||||
if (repoAnn.relays.length > 0) {
|
||||
publishRelays = repoAnn.relays;
|
||||
console.log('Publishing to repository relays:', publishRelays);
|
||||
} else {
|
||||
console.log('No relay hints in repository announcement, using configured relay');
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Check, Plus, Tag, X, Settings } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from '@/components/ui/popover';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { useLabels } from '@/hooks/useLabels';
|
||||
import { getLabelColor, LABEL_COLORS, type Label, type LabelColorName } from '@/lib/labels';
|
||||
import { useProjectLabels } from '@/hooks/useProjectLabels';
|
||||
import { LabelsManageDialog } from './LabelsManageDialog';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface LabelSelectorProps {
|
||||
projectId: string;
|
||||
/** Render as a compact badge list (for inline display) */
|
||||
compact?: boolean;
|
||||
}
|
||||
|
||||
const getRandomColor = (): LabelColorName => {
|
||||
const randomIndex = Math.floor(Math.random() * LABEL_COLORS.length);
|
||||
return LABEL_COLORS[randomIndex].name;
|
||||
};
|
||||
|
||||
export function LabelSelector({ projectId, compact }: LabelSelectorProps) {
|
||||
const { t } = useTranslation();
|
||||
const { labels, createLabel } = useLabels();
|
||||
const { getProjectLabels, addLabelToProject, removeLabelFromProject } = useProjectLabels();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [manageDialogOpen, setManageDialogOpen] = useState(false);
|
||||
const [showCreateForm, setShowCreateForm] = useState(false);
|
||||
const [newLabelName, setNewLabelName] = useState('');
|
||||
const [selectedColor, setSelectedColor] = useState<LabelColorName>(getRandomColor());
|
||||
|
||||
const projectLabelIds = getProjectLabels(projectId);
|
||||
const projectLabels = labels.filter(label => projectLabelIds.includes(label.id));
|
||||
|
||||
const handleToggleLabel = (label: Label) => {
|
||||
if (projectLabelIds.includes(label.id)) {
|
||||
removeLabelFromProject(projectId, label.id);
|
||||
} else {
|
||||
addLabelToProject(projectId, label.id);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreateLabel = () => {
|
||||
if (!newLabelName.trim()) return;
|
||||
|
||||
const newLabel = createLabel(newLabelName.trim(), selectedColor);
|
||||
addLabelToProject(projectId, newLabel.id);
|
||||
|
||||
// Reset form
|
||||
setNewLabelName('');
|
||||
setSelectedColor(getRandomColor());
|
||||
setShowCreateForm(false);
|
||||
};
|
||||
|
||||
const handleCancelCreate = () => {
|
||||
setNewLabelName('');
|
||||
setSelectedColor(getRandomColor());
|
||||
setShowCreateForm(false);
|
||||
};
|
||||
|
||||
if (compact) {
|
||||
return (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{projectLabels.map((label) => {
|
||||
const colorConfig = getLabelColor(label.color);
|
||||
return (
|
||||
<span
|
||||
key={label.id}
|
||||
className={cn(
|
||||
'inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium',
|
||||
colorConfig.bg,
|
||||
'text-white'
|
||||
)}
|
||||
>
|
||||
{label.name}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button variant="outline" className="w-full justify-start gap-2">
|
||||
<Tag className="h-4 w-4" />
|
||||
{projectLabels.length > 0 ? (
|
||||
<div className="flex flex-wrap gap-1 flex-1">
|
||||
{projectLabels.map((label) => {
|
||||
const colorConfig = getLabelColor(label.color);
|
||||
return (
|
||||
<span
|
||||
key={label.id}
|
||||
className={cn(
|
||||
'inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium',
|
||||
colorConfig.bg,
|
||||
'text-white'
|
||||
)}
|
||||
>
|
||||
{label.name}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<span className="text-muted-foreground">{t('addLabel')}</span>
|
||||
)}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-64 p-0" align="start">
|
||||
<div className="p-2">
|
||||
<p className="text-xs font-medium text-muted-foreground px-2 py-1">
|
||||
{t('selectLabels')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{labels.length > 0 ? (
|
||||
<div
|
||||
className="max-h-[200px] overflow-y-auto p-1"
|
||||
onWheel={(e) => {
|
||||
// Allow wheel scrolling within this container
|
||||
e.stopPropagation();
|
||||
}}
|
||||
>
|
||||
{labels.map((label) => {
|
||||
const colorConfig = getLabelColor(label.color);
|
||||
const isSelected = projectLabelIds.includes(label.id);
|
||||
return (
|
||||
<button
|
||||
key={label.id}
|
||||
onClick={() => handleToggleLabel(label)}
|
||||
className={cn(
|
||||
'w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-sm',
|
||||
'hover:bg-muted transition-colors',
|
||||
isSelected && 'bg-muted'
|
||||
)}
|
||||
>
|
||||
<div className={cn('w-3 h-3 rounded-full', colorConfig.bg)} />
|
||||
<span className="flex-1 text-left">{label.name}</span>
|
||||
{isSelected && <Check className="h-4 w-4 text-primary" />}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<div className="p-4 text-center text-sm text-muted-foreground">
|
||||
{t('noLabelsCreated')}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Separator />
|
||||
|
||||
<div className="p-1">
|
||||
{showCreateForm ? (
|
||||
<div className="p-2 space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
placeholder={t('labelName')}
|
||||
value={newLabelName}
|
||||
onChange={(e) => setNewLabelName(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
handleCreateLabel();
|
||||
} else if (e.key === 'Escape') {
|
||||
handleCancelCreate();
|
||||
}
|
||||
}}
|
||||
className="flex-1 h-8"
|
||||
autoFocus
|
||||
/>
|
||||
<button
|
||||
onClick={handleCancelCreate}
|
||||
className="p-1 hover:bg-muted rounded-md transition-colors"
|
||||
title="Cancel"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{LABEL_COLORS.map((color) => (
|
||||
<button
|
||||
key={color.name}
|
||||
onClick={() => setSelectedColor(color.name)}
|
||||
className={cn(
|
||||
'w-6 h-6 rounded-full transition-all',
|
||||
color.bg,
|
||||
selectedColor === color.name && 'ring-2 ring-offset-2 ring-primary'
|
||||
)}
|
||||
title={color.name}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handleCreateLabel}
|
||||
disabled={!newLabelName.trim()}
|
||||
className="w-full h-8"
|
||||
size="sm"
|
||||
>
|
||||
{t('create')}
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => setShowCreateForm(true)}
|
||||
className="w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-sm hover:bg-muted transition-colors"
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
{t('createNewLabel')}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={() => {
|
||||
setManageDialogOpen(true);
|
||||
setOpen(false);
|
||||
}}
|
||||
className="w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-sm hover:bg-muted transition-colors"
|
||||
>
|
||||
<Settings className="h-4 w-4" />
|
||||
{t('manageLabels')}
|
||||
</button>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
<LabelsManageDialog
|
||||
open={manageDialogOpen}
|
||||
onOpenChange={setManageDialogOpen}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Plus, Trash2, GripVertical, Check } from 'lucide-react';
|
||||
import {
|
||||
DndContext,
|
||||
closestCenter,
|
||||
KeyboardSensor,
|
||||
PointerSensor,
|
||||
useSensor,
|
||||
useSensors,
|
||||
type DragEndEvent,
|
||||
} from '@dnd-kit/core';
|
||||
import {
|
||||
arrayMove,
|
||||
SortableContext,
|
||||
sortableKeyboardCoordinates,
|
||||
useSortable,
|
||||
verticalListSortingStrategy,
|
||||
} from '@dnd-kit/sortable';
|
||||
import { CSS } from '@dnd-kit/utilities';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import {
|
||||
Accordion,
|
||||
AccordionContent,
|
||||
AccordionItem,
|
||||
AccordionTrigger,
|
||||
} from '@/components/ui/accordion';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import { useLabels } from '@/hooks/useLabels';
|
||||
import { LABEL_COLORS, getLabelColor, type LabelColorName, type Label as LabelType } from '@/lib/labels';
|
||||
import { useProjectLabels } from '@/hooks/useProjectLabels';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface LabelsManageDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
interface SortableLabelItemProps {
|
||||
label: LabelType;
|
||||
onUpdate: (name: string, color: LabelColorName) => void;
|
||||
onDelete: () => void;
|
||||
projectCount: number;
|
||||
}
|
||||
|
||||
function SortableLabelItem({ label, onUpdate, onDelete, projectCount }: SortableLabelItemProps) {
|
||||
const { t } = useTranslation();
|
||||
const colorConfig = getLabelColor(label.color);
|
||||
const [name, setName] = useState(label.name);
|
||||
const [color, setColor] = useState<LabelColorName>(label.color);
|
||||
|
||||
const {
|
||||
attributes,
|
||||
listeners,
|
||||
setNodeRef,
|
||||
transform,
|
||||
transition,
|
||||
isDragging,
|
||||
} = useSortable({ id: label.id });
|
||||
|
||||
const style = {
|
||||
transform: CSS.Transform.toString(transform),
|
||||
transition,
|
||||
};
|
||||
|
||||
const handleSave = () => {
|
||||
if (name.trim() && (name !== label.name || color !== label.color)) {
|
||||
onUpdate(name.trim(), color);
|
||||
}
|
||||
};
|
||||
|
||||
const hasChanges = name.trim() !== label.name || color !== label.color;
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={setNodeRef}
|
||||
style={style}
|
||||
className={cn(isDragging && "opacity-50")}
|
||||
>
|
||||
<AccordionItem value={label.id} className="border rounded-lg">
|
||||
<AccordionTrigger className="hover:no-underline py-3 pl-3 pr-4 [&[data-state=open]>svg]:rotate-180">
|
||||
<div className="flex items-center gap-2 flex-1 min-w-0">
|
||||
<button
|
||||
type="button"
|
||||
className="h-4 w-4 text-muted-foreground hover:text-foreground cursor-grab active:cursor-grabbing touch-none flex-shrink-0"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
{...attributes}
|
||||
{...listeners}
|
||||
>
|
||||
<GripVertical className="h-4 w-4" />
|
||||
</button>
|
||||
<div className={cn('w-3 h-3 rounded-full flex-shrink-0', colorConfig.bg)} />
|
||||
<span className="text-sm font-medium truncate text-left flex-1">{label.name}</span>
|
||||
<span className="text-xs text-muted-foreground flex-shrink-0 mx-2">
|
||||
{projectCount} {projectCount === 1 ? 'project' : 'projects'}
|
||||
</span>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="pb-4 pt-2 px-3">
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor={`label-name-${label.id}`}>{t('labelName')}</Label>
|
||||
<Input
|
||||
id={`label-name-${label.id}`}
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder={t('enterLabelName')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>{t('labelColor')}</Label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{LABEL_COLORS.map((colorOption) => (
|
||||
<button
|
||||
key={colorOption.name}
|
||||
type="button"
|
||||
onClick={() => setColor(colorOption.name)}
|
||||
className={cn(
|
||||
'w-6 h-6 rounded-full transition-all',
|
||||
colorOption.bg,
|
||||
color === colorOption.name && 'ring-2 ring-offset-2 ring-primary'
|
||||
)}
|
||||
title={colorOption.name}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-between gap-2 pt-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onDelete}
|
||||
className="text-destructive hover:text-destructive"
|
||||
>
|
||||
<Trash2 className="h-4 w-4 mr-1" />
|
||||
{t('delete')}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
onClick={handleSave}
|
||||
disabled={!name.trim() || !hasChanges}
|
||||
>
|
||||
<Check className="h-4 w-4 mr-1" />
|
||||
{t('save')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AddLabelItem({ onCreate }: { onCreate: (name: string, color: LabelColorName) => void }) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
// Function to get a random color from LABEL_COLORS
|
||||
const getRandomColor = (): LabelColorName => {
|
||||
const randomIndex = Math.floor(Math.random() * LABEL_COLORS.length);
|
||||
return LABEL_COLORS[randomIndex].name;
|
||||
};
|
||||
|
||||
const [name, setName] = useState('');
|
||||
const [color, setColor] = useState<LabelColorName>(getRandomColor());
|
||||
|
||||
const handleCreate = () => {
|
||||
if (name.trim()) {
|
||||
onCreate(name.trim(), color);
|
||||
setName('');
|
||||
setColor(getRandomColor());
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<AccordionItem value="add-new" className="border rounded-lg">
|
||||
<AccordionTrigger className="hover:no-underline py-3 pl-3 pr-4 [&[data-state=open]>svg]:rotate-180">
|
||||
<div className="flex items-center gap-2 flex-1">
|
||||
<Plus className="h-4 w-4" />
|
||||
<span className="text-sm font-medium">{t('createLabel')}</span>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="pb-4 pt-2 px-3">
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="new-label-name">{t('labelName')}</Label>
|
||||
<Input
|
||||
id="new-label-name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder={t('enterLabelName')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>{t('labelColor')}</Label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{LABEL_COLORS.map((colorOption) => (
|
||||
<button
|
||||
key={colorOption.name}
|
||||
type="button"
|
||||
onClick={() => setColor(colorOption.name)}
|
||||
className={cn(
|
||||
'w-6 h-6 rounded-full transition-all',
|
||||
colorOption.bg,
|
||||
color === colorOption.name && 'ring-2 ring-offset-2 ring-primary'
|
||||
)}
|
||||
title={colorOption.name}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
onClick={handleCreate}
|
||||
disabled={!name.trim()}
|
||||
>
|
||||
<Check className="h-4 w-4 mr-1" />
|
||||
{t('create')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
);
|
||||
}
|
||||
|
||||
export function LabelsManageDialog({ open, onOpenChange }: LabelsManageDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const { labels, createLabel, updateLabel, deleteLabel, reorderLabels } = useLabels();
|
||||
const { getProjectsByLabel, removeLabel: removeLabelFromProjects } = useProjectLabels();
|
||||
|
||||
const [deletingLabel, setDeletingLabel] = useState<LabelType | null>(null);
|
||||
|
||||
const sensors = useSensors(
|
||||
useSensor(PointerSensor, {
|
||||
activationConstraint: {
|
||||
distance: 8,
|
||||
},
|
||||
}),
|
||||
useSensor(KeyboardSensor, {
|
||||
coordinateGetter: sortableKeyboardCoordinates,
|
||||
})
|
||||
);
|
||||
|
||||
const handleDragEnd = (event: DragEndEvent) => {
|
||||
const { active, over } = event;
|
||||
|
||||
if (over && active.id !== over.id) {
|
||||
const oldIndex = labels.findIndex((label) => label.id === active.id);
|
||||
const newIndex = labels.findIndex((label) => label.id === over.id);
|
||||
|
||||
const newOrder = arrayMove(labels, oldIndex, newIndex);
|
||||
reorderLabels(newOrder.map((label) => label.id));
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreateLabel = (name: string, color: LabelColorName) => {
|
||||
createLabel(name, color);
|
||||
};
|
||||
|
||||
const handleUpdateLabel = (labelId: string) => (name: string, color: LabelColorName) => {
|
||||
updateLabel(labelId, { name, color });
|
||||
};
|
||||
|
||||
const handleConfirmDelete = () => {
|
||||
if (deletingLabel) {
|
||||
// Remove label from all projects first
|
||||
removeLabelFromProjects(deletingLabel.id);
|
||||
// Then delete the label itself
|
||||
deleteLabel(deletingLabel.id);
|
||||
setDeletingLabel(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
{t('manageLabels')}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<ScrollArea className="h-[400px]">
|
||||
<Accordion
|
||||
type="single"
|
||||
collapsible
|
||||
className="space-y-2"
|
||||
defaultValue={labels.length === 0 ? "add-new" : undefined}
|
||||
>
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
collisionDetection={closestCenter}
|
||||
onDragEnd={handleDragEnd}
|
||||
>
|
||||
<SortableContext
|
||||
items={labels.map((l) => l.id)}
|
||||
strategy={verticalListSortingStrategy}
|
||||
>
|
||||
{labels.map((label) => (
|
||||
<SortableLabelItem
|
||||
key={label.id}
|
||||
label={label}
|
||||
onUpdate={handleUpdateLabel(label.id)}
|
||||
onDelete={() => setDeletingLabel(label)}
|
||||
projectCount={getProjectsByLabel(label.id).length}
|
||||
/>
|
||||
))}
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
|
||||
<AddLabelItem onCreate={handleCreateLabel} />
|
||||
</Accordion>
|
||||
</ScrollArea>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Delete confirmation dialog */}
|
||||
<AlertDialog open={!!deletingLabel} onOpenChange={() => setDeletingLabel(null)}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{t('deleteLabel')}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{t('deleteLabelConfirmation', { name: deletingLabel?.name })}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>{t('cancel')}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleConfirmDelete}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{t('delete')}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { LabelsManageDialog } from './LabelsManageDialog';
|
||||
export { LabelSelector } from './LabelSelector';
|
||||
@@ -12,7 +12,7 @@ const AccordionItem = React.forwardRef<
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AccordionPrimitive.Item
|
||||
ref={ref}
|
||||
className={cn("border-b", className)}
|
||||
className={cn("border rounded-lg bg-card text-card-foreground shadow-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
|
||||
@@ -11,7 +11,7 @@ const Checkbox = React.forwardRef<
|
||||
<CheckboxPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
|
||||
"peer h-4 w-4 shrink-0 rounded-xs border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -2,8 +2,13 @@ import * as React from "react"
|
||||
import { Eye, EyeOff } from "lucide-react"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const PasswordInput = React.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLInputElement>>(
|
||||
({ className, ...props }, ref) => {
|
||||
interface PasswordInputProps extends React.InputHTMLAttributes<HTMLInputElement> {
|
||||
/** Whether to show the visibility toggle button. Defaults to true. */
|
||||
showToggle?: boolean;
|
||||
}
|
||||
|
||||
const PasswordInput = React.forwardRef<HTMLInputElement, PasswordInputProps>(
|
||||
({ className, showToggle = true, ...props }, ref) => {
|
||||
const [showPassword, setShowPassword] = React.useState(false)
|
||||
const [isFocused, setIsFocused] = React.useState(false)
|
||||
|
||||
@@ -12,7 +17,8 @@ const PasswordInput = React.forwardRef<HTMLInputElement, React.InputHTMLAttribut
|
||||
<input
|
||||
type={showPassword ? "text" : "password"}
|
||||
className={cn(
|
||||
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 pr-10 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
showToggle && "pr-10",
|
||||
isFocused && "ring-2 ring-ring ring-offset-2"
|
||||
)}
|
||||
ref={ref}
|
||||
@@ -26,19 +32,21 @@ const PasswordInput = React.forwardRef<HTMLInputElement, React.InputHTMLAttribut
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground focus:outline-none disabled:cursor-not-allowed disabled:opacity-50"
|
||||
disabled={props.disabled}
|
||||
aria-label={showPassword ? "Hide password" : "Show password"}
|
||||
>
|
||||
{showPassword ? (
|
||||
<EyeOff className="h-4 w-4" />
|
||||
) : (
|
||||
<Eye className="h-4 w-4" />
|
||||
)}
|
||||
</button>
|
||||
{showToggle && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground focus:outline-none disabled:cursor-not-allowed disabled:opacity-50"
|
||||
disabled={props.disabled}
|
||||
aria-label={showPassword ? "Hide password" : "Show password"}
|
||||
>
|
||||
{showPassword ? (
|
||||
<EyeOff className="h-4 w-4" />
|
||||
) : (
|
||||
<Eye className="h-4 w-4" />
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ const SelectTrigger = React.forwardRef<
|
||||
<SelectPrimitive.Trigger
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
|
||||
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground hover:bg-border/20 dark:hover:bg-border/50 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { TagInput } from './tag-input';
|
||||
|
||||
describe('TagInput', () => {
|
||||
it('renders with placeholder when no tags', () => {
|
||||
const onChange = vi.fn();
|
||||
render(
|
||||
<TagInput
|
||||
value={[]}
|
||||
onChange={onChange}
|
||||
placeholder="Add tags..."
|
||||
/>
|
||||
);
|
||||
|
||||
const input = screen.getByPlaceholderText('Add tags...');
|
||||
expect(input).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays existing tags', () => {
|
||||
const onChange = vi.fn();
|
||||
render(
|
||||
<TagInput
|
||||
value={['tag1', 'tag2', 'tag3']}
|
||||
onChange={onChange}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('tag1')).toBeInTheDocument();
|
||||
expect(screen.getByText('tag2')).toBeInTheDocument();
|
||||
expect(screen.getByText('tag3')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('adds tag on space key', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
|
||||
render(
|
||||
<TagInput
|
||||
value={[]}
|
||||
onChange={onChange}
|
||||
placeholder="Add tags..."
|
||||
/>
|
||||
);
|
||||
|
||||
const input = screen.getByPlaceholderText('Add tags...');
|
||||
await user.type(input, 'newtag ');
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith(['newtag']);
|
||||
});
|
||||
|
||||
it('adds tag on comma key', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
|
||||
render(
|
||||
<TagInput
|
||||
value={[]}
|
||||
onChange={onChange}
|
||||
placeholder="Add tags..."
|
||||
/>
|
||||
);
|
||||
|
||||
const input = screen.getByPlaceholderText('Add tags...');
|
||||
await user.type(input, 'newtag,');
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith(['newtag']);
|
||||
});
|
||||
|
||||
it('adds tag on Enter key', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
|
||||
render(
|
||||
<TagInput
|
||||
value={[]}
|
||||
onChange={onChange}
|
||||
placeholder="Add tags..."
|
||||
/>
|
||||
);
|
||||
|
||||
const input = screen.getByPlaceholderText('Add tags...');
|
||||
await user.type(input, 'newtag{Enter}');
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith(['newtag']);
|
||||
});
|
||||
|
||||
it('removes last tag on Backspace when input is empty', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
|
||||
render(
|
||||
<TagInput
|
||||
value={['tag1', 'tag2']}
|
||||
onChange={onChange}
|
||||
/>
|
||||
);
|
||||
|
||||
const input = screen.getByRole('textbox');
|
||||
await user.click(input);
|
||||
await user.keyboard('{Backspace}');
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith(['tag1']);
|
||||
});
|
||||
|
||||
it('removes tag when clicking X button', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
|
||||
render(
|
||||
<TagInput
|
||||
value={['tag1', 'tag2', 'tag3']}
|
||||
onChange={onChange}
|
||||
/>
|
||||
);
|
||||
|
||||
const removeButtons = screen.getAllByRole('button');
|
||||
await user.click(removeButtons[1]); // Remove tag2
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith(['tag1', 'tag3']);
|
||||
});
|
||||
|
||||
it('transforms tags using transformTag function', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
|
||||
render(
|
||||
<TagInput
|
||||
value={[]}
|
||||
onChange={onChange}
|
||||
transformTag={(tag) => tag.toUpperCase()}
|
||||
placeholder="Add tags..."
|
||||
/>
|
||||
);
|
||||
|
||||
const input = screen.getByPlaceholderText('Add tags...');
|
||||
await user.type(input, 'lowercase ');
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith(['LOWERCASE']);
|
||||
});
|
||||
|
||||
it('prevents duplicate tags by default', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
|
||||
render(
|
||||
<TagInput
|
||||
value={['existing']}
|
||||
onChange={onChange}
|
||||
placeholder="Add tags..."
|
||||
/>
|
||||
);
|
||||
|
||||
const input = screen.getByRole('textbox');
|
||||
await user.type(input, 'existing ');
|
||||
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('allows duplicate tags when allowDuplicates is true', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
|
||||
render(
|
||||
<TagInput
|
||||
value={['existing']}
|
||||
onChange={onChange}
|
||||
allowDuplicates={true}
|
||||
placeholder="Add tags..."
|
||||
/>
|
||||
);
|
||||
|
||||
const input = screen.getByRole('textbox');
|
||||
await user.type(input, 'existing ');
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith(['existing', 'existing']);
|
||||
});
|
||||
|
||||
it('validates tags using validateTag function', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
|
||||
render(
|
||||
<TagInput
|
||||
value={[]}
|
||||
onChange={onChange}
|
||||
validateTag={(tag) => tag.length >= 3}
|
||||
placeholder="Add tags..."
|
||||
/>
|
||||
);
|
||||
|
||||
const input = screen.getByPlaceholderText('Add tags...');
|
||||
|
||||
// Try adding tag that's too short
|
||||
await user.type(input, 'ab ');
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
|
||||
// Add valid tag
|
||||
await user.type(input, 'valid ');
|
||||
expect(onChange).toHaveBeenCalledWith(['valid']);
|
||||
});
|
||||
|
||||
it('does not add empty tags', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
|
||||
render(
|
||||
<TagInput
|
||||
value={[]}
|
||||
onChange={onChange}
|
||||
placeholder="Add tags..."
|
||||
/>
|
||||
);
|
||||
|
||||
const input = screen.getByPlaceholderText('Add tags...');
|
||||
await user.type(input, ' '); // Just spaces
|
||||
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('focuses input when container is clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
|
||||
const { container } = render(
|
||||
<TagInput
|
||||
value={['tag1']}
|
||||
onChange={onChange}
|
||||
/>
|
||||
);
|
||||
|
||||
const inputContainer = container.querySelector('div');
|
||||
if (inputContainer) {
|
||||
await user.click(inputContainer);
|
||||
}
|
||||
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveFocus();
|
||||
});
|
||||
|
||||
it('is disabled when disabled prop is true', () => {
|
||||
const onChange = vi.fn();
|
||||
|
||||
render(
|
||||
<TagInput
|
||||
value={['tag1']}
|
||||
onChange={onChange}
|
||||
disabled={true}
|
||||
/>
|
||||
);
|
||||
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toBeDisabled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,172 @@
|
||||
import * as React from 'react';
|
||||
import { X } from 'lucide-react';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export interface TagInputProps
|
||||
extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'value' | 'onChange'> {
|
||||
value: string[];
|
||||
onChange: (tags: string[]) => void;
|
||||
/** Character(s) that trigger tag creation. Default: [' ', ','] */
|
||||
delimiters?: string[];
|
||||
/** Transform tag before adding (e.g., toLowerCase). Default: (tag) => tag.trim() */
|
||||
transformTag?: (tag: string) => string;
|
||||
/** Validate tag before adding. Return false to reject. */
|
||||
validateTag?: (tag: string) => boolean;
|
||||
/** Allow duplicate tags. Default: false */
|
||||
allowDuplicates?: boolean;
|
||||
}
|
||||
|
||||
export const TagInput = React.forwardRef<HTMLInputElement, TagInputProps>(
|
||||
(
|
||||
{
|
||||
className,
|
||||
value = [],
|
||||
onChange,
|
||||
delimiters = [' ', ','],
|
||||
transformTag = (tag) => tag.trim(),
|
||||
validateTag,
|
||||
allowDuplicates = false,
|
||||
disabled,
|
||||
placeholder,
|
||||
...props
|
||||
},
|
||||
ref
|
||||
) => {
|
||||
const [inputValue, setInputValue] = React.useState('');
|
||||
const inputRef = React.useRef<HTMLInputElement>(null);
|
||||
const containerRef = React.useRef<HTMLDivElement>(null);
|
||||
|
||||
// Combine external ref with internal ref
|
||||
React.useImperativeHandle(ref, () => inputRef.current!);
|
||||
|
||||
const addTag = (tag: string) => {
|
||||
const transformed = transformTag(tag);
|
||||
|
||||
if (!transformed) return;
|
||||
|
||||
// Check for duplicates if not allowed
|
||||
if (!allowDuplicates && value.includes(transformed)) {
|
||||
setInputValue('');
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate if validator provided
|
||||
if (validateTag && !validateTag(transformed)) {
|
||||
setInputValue('');
|
||||
return;
|
||||
}
|
||||
|
||||
onChange([...value, transformed]);
|
||||
setInputValue('');
|
||||
};
|
||||
|
||||
const removeTag = (index: number) => {
|
||||
onChange(value.filter((_, i) => i !== index));
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
// Handle delimiters (space, comma, etc.)
|
||||
if (delimiters.includes(e.key)) {
|
||||
e.preventDefault();
|
||||
if (inputValue.trim()) {
|
||||
addTag(inputValue);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle Enter key
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
if (inputValue.trim()) {
|
||||
addTag(inputValue);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle Backspace - delete last tag if input is empty
|
||||
if (e.key === 'Backspace' && !inputValue && value.length > 0) {
|
||||
e.preventDefault();
|
||||
removeTag(value.length - 1);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const newValue = e.target.value;
|
||||
|
||||
// Check if any delimiter was typed
|
||||
const hasDelimiter = delimiters.some(delimiter => newValue.includes(delimiter));
|
||||
|
||||
if (hasDelimiter) {
|
||||
// Extract the part before the delimiter
|
||||
const parts = newValue.split(new RegExp(`[${delimiters.map(d => d === ' ' ? '\\s' : d).join('')}]`));
|
||||
const tagToAdd = parts[0];
|
||||
|
||||
if (tagToAdd.trim()) {
|
||||
addTag(tagToAdd);
|
||||
}
|
||||
} else {
|
||||
setInputValue(newValue);
|
||||
}
|
||||
};
|
||||
|
||||
const handleContainerClick = () => {
|
||||
inputRef.current?.focus();
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className={cn(
|
||||
'flex min-h-10 w-full flex-wrap gap-1.5 rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background',
|
||||
'focus-within:outline-none focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2',
|
||||
disabled && 'cursor-not-allowed opacity-50',
|
||||
className
|
||||
)}
|
||||
onClick={handleContainerClick}
|
||||
>
|
||||
{/* Render tags */}
|
||||
{value.map((tag, index) => (
|
||||
<Badge
|
||||
key={index}
|
||||
variant="secondary"
|
||||
className="gap-1 pr-1.5 pl-2.5 py-0.5 h-6"
|
||||
>
|
||||
<span>{tag}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="ml-1 rounded-sm hover:bg-secondary-foreground/20 focus:outline-none focus:ring-1 focus:ring-ring"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
removeTag(index);
|
||||
}}
|
||||
disabled={disabled}
|
||||
>
|
||||
<X className="h-3 w-3" />
|
||||
<span className="sr-only">Remove {tag}</span>
|
||||
</button>
|
||||
</Badge>
|
||||
))}
|
||||
|
||||
{/* Input field */}
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="text"
|
||||
value={inputValue}
|
||||
onChange={handleInputChange}
|
||||
onKeyDown={handleKeyDown}
|
||||
disabled={disabled}
|
||||
placeholder={value.length === 0 ? placeholder : undefined}
|
||||
className={cn(
|
||||
'flex-1 min-w-[120px] bg-transparent outline-none placeholder:text-muted-foreground',
|
||||
'disabled:cursor-not-allowed'
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
TagInput.displayName = 'TagInput';
|
||||
@@ -2,15 +2,28 @@ import { createContext } from 'react';
|
||||
|
||||
export interface AIProvider {
|
||||
id: string;
|
||||
name: string;
|
||||
baseURL: string;
|
||||
apiKey?: string;
|
||||
nostr?: boolean;
|
||||
proxy?: boolean;
|
||||
}
|
||||
|
||||
export interface MCPServer {
|
||||
type: 'streamable-http';
|
||||
url: string;
|
||||
headers?: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface MCPServers {
|
||||
[key: string]: MCPServer;
|
||||
}
|
||||
|
||||
export interface AISettings {
|
||||
providers: AIProvider[];
|
||||
recentlyUsedModels: string[];
|
||||
imageModel?: string;
|
||||
mcpServers?: MCPServers;
|
||||
}
|
||||
|
||||
export interface AISettingsContextType {
|
||||
@@ -20,6 +33,8 @@ export interface AISettingsContextType {
|
||||
removeProvider: (id: string) => void;
|
||||
setProviders: (providers: AIProvider[]) => void;
|
||||
addRecentlyUsedModel: (modelId: string) => void;
|
||||
setMCPServer: (name: string, server: MCPServer) => void;
|
||||
removeMCPServer: (name: string) => void;
|
||||
isConfigured: boolean;
|
||||
}
|
||||
|
||||
|
||||
@@ -9,13 +9,22 @@ export interface RelayMetadata {
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
export interface ProjectTemplate {
|
||||
/** Template name */
|
||||
name: string;
|
||||
/** Template description */
|
||||
description: string;
|
||||
/** Git repository URL */
|
||||
url: string;
|
||||
}
|
||||
|
||||
export interface AppConfig {
|
||||
/** Current theme */
|
||||
theme: Theme;
|
||||
/** NIP-65 relay list metadata */
|
||||
relayMetadata: RelayMetadata;
|
||||
/** Git repository URL to use as project template */
|
||||
projectTemplate: string;
|
||||
/** Available project templates */
|
||||
templates: ProjectTemplate[];
|
||||
/** ESM CDN URL for package imports */
|
||||
esmUrl: string;
|
||||
/** HTTP proxy used to bypass CORS for AI and Git operations */
|
||||
@@ -40,15 +49,21 @@ export interface AppConfig {
|
||||
fsPathTmp: string;
|
||||
/** VFS path for plugins directory */
|
||||
fsPathPlugins: string;
|
||||
/** VFS path for templates directory */
|
||||
fsPathTemplates: string;
|
||||
/** Sentry DSN for error reporting (empty string = disabled) */
|
||||
sentryDsn: string;
|
||||
/** Whether the user has enabled Sentry error reporting */
|
||||
sentryEnabled: boolean;
|
||||
/** System prompt EJS template */
|
||||
systemPrompt?: string;
|
||||
}
|
||||
|
||||
export interface AppContextType {
|
||||
/** Current application configuration */
|
||||
config: AppConfig;
|
||||
/** Default application configuration */
|
||||
defaultConfig: AppConfig;
|
||||
/** Update configuration using a callback that receives current config and returns new config */
|
||||
updateConfig: (updater: (currentConfig: Partial<AppConfig>) => Partial<AppConfig>) => void;
|
||||
}
|
||||
|
||||
@@ -32,7 +32,25 @@ export interface NsiteProvider extends BaseDeployProvider {
|
||||
blossomServers: string[];
|
||||
}
|
||||
|
||||
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider;
|
||||
export interface CloudflareProvider extends BaseDeployProvider {
|
||||
type: 'cloudflare';
|
||||
apiKey: string;
|
||||
accountId: string;
|
||||
baseURL?: string;
|
||||
baseDomain?: string;
|
||||
proxy?: boolean;
|
||||
}
|
||||
|
||||
export interface DenoDeployProvider extends BaseDeployProvider {
|
||||
type: 'deno';
|
||||
apiKey: string;
|
||||
organizationId: string;
|
||||
baseURL?: string;
|
||||
baseDomain?: string;
|
||||
proxy?: boolean;
|
||||
}
|
||||
|
||||
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider;
|
||||
|
||||
export interface DeploySettings {
|
||||
providers: DeployProvider[];
|
||||
|
||||
@@ -66,11 +66,7 @@ export function useAIChat({
|
||||
setMessages(prev => [...prev, message]);
|
||||
// Whenever an assistant message is added, it means streaming is done (until we get another streamingUpdate)
|
||||
if (message.role === 'assistant') {
|
||||
setStreamingMessage({
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
reasoning_content: '',
|
||||
});
|
||||
setStreamingMessage(undefined);
|
||||
}
|
||||
}
|
||||
}, [projectId]);
|
||||
@@ -114,7 +110,10 @@ export function useAIChat({
|
||||
}, [projectId]);
|
||||
|
||||
// Actions
|
||||
const sendMessage = useCallback(async (content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText>, providerModel: string) => {
|
||||
const sendMessage = useCallback(async (
|
||||
content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage>,
|
||||
providerModel: string
|
||||
) => {
|
||||
try {
|
||||
await initSession();
|
||||
await sessionManager.sendMessage(projectId, content, providerModel);
|
||||
|
||||
@@ -1,501 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
import { useAIProjectId } from './useAIProjectId';
|
||||
import { useAISettings } from './useAISettings';
|
||||
import { useCurrentUser } from './useCurrentUser';
|
||||
import { useAppContext } from './useAppContext';
|
||||
import { useProjectsManager } from './useProjectsManager';
|
||||
import { createAIClient } from '@/lib/ai-client';
|
||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
import type { ProjectsManager } from '@/lib/ProjectsManager';
|
||||
|
||||
// Mock the hooks and dependencies
|
||||
vi.mock('./useAISettings');
|
||||
vi.mock('./useCurrentUser');
|
||||
vi.mock('./useAppContext');
|
||||
vi.mock('./useProjectsManager');
|
||||
vi.mock('@/lib/ai-client');
|
||||
vi.mock('@/lib/parseProviderModel');
|
||||
|
||||
describe('useAIProjectId', () => {
|
||||
const mockUseAISettings = vi.mocked(useAISettings);
|
||||
const mockUseCurrentUser = vi.mocked(useCurrentUser);
|
||||
const mockUseAppContext = vi.mocked(useAppContext);
|
||||
const mockUseProjectsManager = vi.mocked(useProjectsManager);
|
||||
const mockCreateAIClient = vi.mocked(createAIClient);
|
||||
const mockParseProviderModel = vi.mocked(parseProviderModel);
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
// Mock fetch globally
|
||||
global.fetch = vi.fn();
|
||||
|
||||
// Mock useCurrentUser to return undefined user by default
|
||||
mockUseCurrentUser.mockReturnValue({
|
||||
user: undefined,
|
||||
users: [],
|
||||
});
|
||||
|
||||
// Mock useAppContext
|
||||
mockUseAppContext.mockReturnValue({
|
||||
config: {
|
||||
theme: 'dark',
|
||||
relayMetadata: {
|
||||
relays: [{ url: 'wss://relay.damus.io', read: true, write: true }],
|
||||
updatedAt: 0,
|
||||
},
|
||||
projectTemplate: 'https://github.com/example/template',
|
||||
esmUrl: 'https://esm.sh',
|
||||
corsProxy: 'https://proxy.example.com/{href}',
|
||||
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
||||
previewDomain: 'local-shakespeare.dev',
|
||||
showcaseEnabled: true,
|
||||
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
|
||||
ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'],
|
||||
fsPathProjects: '/projects',
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
fsPathPlugins: '/plugins',
|
||||
sentryDsn: '',
|
||||
sentryEnabled: false,
|
||||
},
|
||||
updateConfig: vi.fn(),
|
||||
});
|
||||
|
||||
// Mock useProjectsManager
|
||||
const mockProjectsManager = {
|
||||
getProject: vi.fn().mockResolvedValue(null),
|
||||
} as unknown as ProjectsManager;
|
||||
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
|
||||
|
||||
// Mock parseProviderModel
|
||||
mockParseProviderModel.mockReturnValue({
|
||||
provider: { id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' },
|
||||
model: 'gpt-4',
|
||||
});
|
||||
|
||||
// Mock createAIClient
|
||||
const mockCompletion = {
|
||||
choices: [{ message: { content: 'test-project-name' } }]
|
||||
};
|
||||
const mockOpenAI = {
|
||||
chat: {
|
||||
completions: {
|
||||
create: vi.fn().mockResolvedValue(mockCompletion)
|
||||
}
|
||||
}
|
||||
} as unknown as ReturnType<typeof createAIClient>;
|
||||
mockCreateAIClient.mockReturnValue(mockOpenAI);
|
||||
});
|
||||
|
||||
it('should return not configured when AI settings are not configured', () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: { providers: [], recentlyUsedModels: [] },
|
||||
isConfigured: false,
|
||||
updateSettings: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
|
||||
expect(result.current.isConfigured).toBe(false);
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
});
|
||||
|
||||
it('should throw error when trying to generate ID without configuration', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: { providers: [], recentlyUsedModels: [] },
|
||||
isConfigured: false,
|
||||
updateSettings: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
|
||||
await expect(result.current.generateProjectId('openai/gpt-4', 'test prompt')).rejects.toThrow(
|
||||
'AI settings not configured'
|
||||
);
|
||||
});
|
||||
|
||||
it('should throw error when prompt is empty', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: [
|
||||
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
],
|
||||
recentlyUsedModels: []
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
|
||||
await expect(result.current.generateProjectId('openai/gpt-4', '')).rejects.toThrow(
|
||||
'Prompt cannot be empty'
|
||||
);
|
||||
});
|
||||
|
||||
it('should have configured status when providers are available', () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: [
|
||||
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
],
|
||||
recentlyUsedModels: []
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
|
||||
expect(result.current.isConfigured).toBe(true);
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
});
|
||||
|
||||
it('should successfully generate project ID', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: [
|
||||
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
],
|
||||
recentlyUsedModels: []
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
|
||||
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
|
||||
|
||||
expect(projectId).toBe('test-project-name');
|
||||
expect(mockParseProviderModel).toHaveBeenCalledWith('openai/gpt-4', [
|
||||
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
]);
|
||||
expect(mockCreateAIClient).toHaveBeenCalledWith(
|
||||
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' },
|
||||
undefined,
|
||||
'https://proxy.example.com/{href}'
|
||||
);
|
||||
});
|
||||
|
||||
it('should fallback to untitled when project exists', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: [
|
||||
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
],
|
||||
recentlyUsedModels: []
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
// Mock AI response - returns a project name that already exists
|
||||
const mockCompletion = {
|
||||
choices: [{ message: { content: 'existing-project' } }]
|
||||
};
|
||||
const mockOpenAI = {
|
||||
chat: {
|
||||
completions: {
|
||||
create: vi.fn().mockResolvedValueOnce(mockCompletion)
|
||||
}
|
||||
}
|
||||
} as unknown as ReturnType<typeof createAIClient>;
|
||||
mockCreateAIClient.mockReturnValue(mockOpenAI);
|
||||
|
||||
// Mock getProject - first call returns project (exists), second returns null (untitled is available)
|
||||
const mockGetProject = vi.fn()
|
||||
.mockResolvedValueOnce({ id: 'existing-project', name: 'Existing Project', path: '/projects/existing-project', lastModified: new Date() })
|
||||
.mockResolvedValueOnce(null);
|
||||
|
||||
const mockProjectsManager = {
|
||||
getProject: mockGetProject,
|
||||
} as unknown as ProjectsManager;
|
||||
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
|
||||
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
|
||||
|
||||
expect(projectId).toBe('untitled');
|
||||
expect(mockGetProject).toHaveBeenCalledTimes(2);
|
||||
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'existing-project');
|
||||
expect(mockGetProject).toHaveBeenNthCalledWith(2, 'untitled');
|
||||
|
||||
// Should have called AI only once
|
||||
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should fallback to untitled-1 when untitled exists', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: [
|
||||
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
],
|
||||
recentlyUsedModels: []
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
// Mock AI to return a project name that already exists
|
||||
const mockCompletion = {
|
||||
choices: [{ message: { content: 'taken-project' } }]
|
||||
};
|
||||
const mockOpenAI = {
|
||||
chat: {
|
||||
completions: {
|
||||
create: vi.fn().mockResolvedValue(mockCompletion)
|
||||
}
|
||||
}
|
||||
} as unknown as ReturnType<typeof createAIClient>;
|
||||
mockCreateAIClient.mockReturnValue(mockOpenAI);
|
||||
|
||||
// Mock getProject - taken-project exists, untitled exists, untitled-1 is available
|
||||
const mockGetProject = vi.fn()
|
||||
.mockResolvedValueOnce({ id: 'taken-project', name: 'Taken Project', path: '/projects/taken-project', lastModified: new Date() })
|
||||
.mockResolvedValueOnce({ id: 'untitled', name: 'Untitled', path: '/projects/untitled', lastModified: new Date() })
|
||||
.mockResolvedValueOnce(null);
|
||||
|
||||
const mockProjectsManager = {
|
||||
getProject: mockGetProject,
|
||||
} as unknown as ProjectsManager;
|
||||
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
|
||||
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
|
||||
|
||||
expect(projectId).toBe('untitled-1');
|
||||
expect(mockGetProject).toHaveBeenCalledTimes(3);
|
||||
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'taken-project');
|
||||
expect(mockGetProject).toHaveBeenNthCalledWith(2, 'untitled');
|
||||
expect(mockGetProject).toHaveBeenNthCalledWith(3, 'untitled-1');
|
||||
|
||||
// Should have called AI only once
|
||||
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should fallback to untitled when AI generates too long name', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: [
|
||||
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
],
|
||||
recentlyUsedModels: []
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
// Mock AI to return a very long project name (over 50 characters)
|
||||
const mockCompletion = {
|
||||
choices: [{ message: { content: 'this-is-a-very-long-project-name-that-exceeds-the-maximum-allowed-length-limit' } }]
|
||||
};
|
||||
const mockOpenAI = {
|
||||
chat: {
|
||||
completions: {
|
||||
create: vi.fn().mockResolvedValue(mockCompletion)
|
||||
}
|
||||
}
|
||||
} as unknown as ReturnType<typeof createAIClient>;
|
||||
mockCreateAIClient.mockReturnValue(mockOpenAI);
|
||||
|
||||
// Mock getProject - untitled is available
|
||||
const mockGetProject = vi.fn().mockResolvedValue(null);
|
||||
|
||||
const mockProjectsManager = {
|
||||
getProject: mockGetProject,
|
||||
} as unknown as ProjectsManager;
|
||||
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
|
||||
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
|
||||
|
||||
expect(projectId).toBe('untitled');
|
||||
expect(mockGetProject).toHaveBeenCalledTimes(1);
|
||||
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'untitled');
|
||||
|
||||
// Should have called AI only once
|
||||
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should fallback to untitled when AI generates invalid name', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: [
|
||||
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
],
|
||||
recentlyUsedModels: []
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
// Mock AI to return an invalid project name (doesn't match regex)
|
||||
const mockCompletion = {
|
||||
choices: [{ message: { content: 'Invalid Project Name!' } }]
|
||||
};
|
||||
const mockOpenAI = {
|
||||
chat: {
|
||||
completions: {
|
||||
create: vi.fn().mockResolvedValue(mockCompletion)
|
||||
}
|
||||
}
|
||||
} as unknown as ReturnType<typeof createAIClient>;
|
||||
mockCreateAIClient.mockReturnValue(mockOpenAI);
|
||||
|
||||
// Mock getProject - untitled is available
|
||||
const mockGetProject = vi.fn().mockResolvedValue(null);
|
||||
|
||||
const mockProjectsManager = {
|
||||
getProject: mockGetProject,
|
||||
} as unknown as ProjectsManager;
|
||||
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
|
||||
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
|
||||
|
||||
expect(projectId).toBe('untitled');
|
||||
expect(mockGetProject).toHaveBeenCalledTimes(1);
|
||||
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'untitled');
|
||||
|
||||
// Should have called AI only once
|
||||
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should fallback to untitled-2 when untitled and untitled-1 exist', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: [
|
||||
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
],
|
||||
recentlyUsedModels: []
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
// Mock AI to return a project name that already exists
|
||||
const mockCompletion = {
|
||||
choices: [{ message: { content: 'taken-project' } }]
|
||||
};
|
||||
const mockOpenAI = {
|
||||
chat: {
|
||||
completions: {
|
||||
create: vi.fn().mockResolvedValue(mockCompletion)
|
||||
}
|
||||
}
|
||||
} as unknown as ReturnType<typeof createAIClient>;
|
||||
mockCreateAIClient.mockReturnValue(mockOpenAI);
|
||||
|
||||
// Mock getProject - taken-project exists, untitled exists, untitled-1 exists, untitled-2 is available
|
||||
const mockGetProject = vi.fn()
|
||||
.mockResolvedValueOnce({ id: 'taken-project', name: 'Taken Project', path: '/projects/taken-project', lastModified: new Date() })
|
||||
.mockResolvedValueOnce({ id: 'untitled', name: 'Untitled', path: '/projects/untitled', lastModified: new Date() })
|
||||
.mockResolvedValueOnce({ id: 'untitled-1', name: 'Untitled 1', path: '/projects/untitled-1', lastModified: new Date() })
|
||||
.mockResolvedValueOnce(null);
|
||||
|
||||
const mockProjectsManager = {
|
||||
getProject: mockGetProject,
|
||||
} as unknown as ProjectsManager;
|
||||
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
|
||||
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
|
||||
|
||||
expect(projectId).toBe('untitled-2');
|
||||
expect(mockGetProject).toHaveBeenCalledTimes(4);
|
||||
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'taken-project');
|
||||
expect(mockGetProject).toHaveBeenNthCalledWith(2, 'untitled');
|
||||
expect(mockGetProject).toHaveBeenNthCalledWith(3, 'untitled-1');
|
||||
expect(mockGetProject).toHaveBeenNthCalledWith(4, 'untitled-2');
|
||||
|
||||
// Should have called AI only once
|
||||
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should handle loading state correctly', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: [
|
||||
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
],
|
||||
recentlyUsedModels: []
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
|
||||
const promise = result.current.generateProjectId('openai/gpt-4', 'Test prompt');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isLoading).toBe(false); // Should be false after completion
|
||||
});
|
||||
|
||||
await promise;
|
||||
});
|
||||
});
|
||||
@@ -1,96 +0,0 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { createAIClient } from '@/lib/ai-client';
|
||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
|
||||
interface UseAIProjectIdOptions {
|
||||
onError?: (error: string) => void;
|
||||
}
|
||||
|
||||
export function useAIProjectId({ onError }: UseAIProjectIdOptions = {}) {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const { settings, isConfigured } = useAISettings();
|
||||
const { user } = useCurrentUser();
|
||||
const { config } = useAppContext();
|
||||
const projectsManager = useProjectsManager();
|
||||
|
||||
const generateProjectId = useCallback(async (providerModel: string, prompt: string): Promise<string> => {
|
||||
if (!isConfigured) {
|
||||
throw new Error('AI settings not configured');
|
||||
}
|
||||
|
||||
if (!prompt.trim()) {
|
||||
throw new Error('Prompt cannot be empty');
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
// Initialize OpenAI client
|
||||
const { model, provider } = parseProviderModel(providerModel, settings.providers);
|
||||
const openai = createAIClient(provider, user, config.corsProxy);
|
||||
|
||||
const systemPrompt = `You are a product expert. Given the user's project description, come up with a short, unique, and memorable name for their product or brand. Generate only the name without any additional text or punctuation. The name should be lowercase, use hyphens instead of spaces, and contain only alphanumeric characters and hyphens. Avoid using special characters or underscores.`;
|
||||
|
||||
const messages = [
|
||||
{ role: 'system' as const, content: systemPrompt },
|
||||
{ role: 'user' as const, content: prompt }
|
||||
];
|
||||
|
||||
// Try once to generate a project name
|
||||
const completion = await openai.chat.completions.create({
|
||||
model,
|
||||
messages,
|
||||
temperature: 1,
|
||||
});
|
||||
|
||||
const projectId = completion.choices[0]?.message?.content?.trim();
|
||||
if (!projectId) {
|
||||
throw new Error('Failed to generate project name');
|
||||
}
|
||||
|
||||
// Validate the generated ID directly (no conversion)
|
||||
const validIdRegex = /^[a-z0-9]+(-[a-z0-9]+)*$/;
|
||||
if (projectId.length <= 50 && validIdRegex.test(projectId)) {
|
||||
// Check if project exists
|
||||
const existingProject = await projectsManager.getProject(projectId);
|
||||
if (existingProject === null) {
|
||||
// Valid and unique project ID
|
||||
return projectId;
|
||||
}
|
||||
}
|
||||
|
||||
// If we reach here, either the regex failed or the project already exists
|
||||
// Fall back to "untitled" with number suffixes
|
||||
let fallbackId = 'untitled';
|
||||
let counter = 1;
|
||||
|
||||
// Check if base "untitled" exists
|
||||
let existingProject = await projectsManager.getProject(fallbackId);
|
||||
|
||||
// Keep incrementing until we find an available name
|
||||
while (existingProject !== null) {
|
||||
fallbackId = `untitled-${counter}`;
|
||||
existingProject = await projectsManager.getProject(fallbackId);
|
||||
counter++;
|
||||
}
|
||||
|
||||
return fallbackId;
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Failed to generate project ID';
|
||||
onError?.(errorMessage);
|
||||
throw error;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [isConfigured, settings, onError, user, projectsManager, config.corsProxy]);
|
||||
|
||||
return {
|
||||
generateProjectId,
|
||||
isLoading,
|
||||
isConfigured
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
|
||||
/**
|
||||
* Hook to get the user's contact list (kind 3 follow list)
|
||||
* Returns an array of pubkeys that the user follows
|
||||
*/
|
||||
export function useContacts(userPubkey?: string) {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['nostr', 'contacts', userPubkey],
|
||||
queryFn: async (): Promise<string[]> => {
|
||||
if (!userPubkey) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Get the user's contact list (kind 3)
|
||||
const events = await nostr.query([{
|
||||
kinds: [3],
|
||||
authors: [userPubkey],
|
||||
limit: 1,
|
||||
}], { signal: AbortSignal.timeout(3000) });
|
||||
|
||||
if (events.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Get the most recent contact list event
|
||||
const contactList = events.sort((a, b) => b.created_at - a.created_at)[0];
|
||||
|
||||
// Extract pubkeys from 'p' tags
|
||||
const followedPubkeys = contactList.tags
|
||||
.filter(tag => tag[0] === 'p' && tag[1])
|
||||
.map(tag => tag[1]);
|
||||
|
||||
return followedPubkeys;
|
||||
},
|
||||
enabled: !!userPubkey,
|
||||
staleTime: 60000, // 1 minute
|
||||
refetchInterval: 300000, // 5 minutes
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
describe('useDiscoverPlugins', () => {
|
||||
it('should validate NIP-34 event structure', () => {
|
||||
// Example of a valid NIP-34 repository announcement event
|
||||
const validEvent: NostrEvent = {
|
||||
id: 'test-event-id',
|
||||
pubkey: 'test-pubkey',
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
kind: 30617,
|
||||
tags: [
|
||||
['d', 'test-plugin'],
|
||||
['name', 'Test Plugin'],
|
||||
['description', 'A test Shakespeare plugin'],
|
||||
['clone', 'https://github.com/user/test-plugin.git'],
|
||||
['web', 'https://github.com/user/test-plugin'],
|
||||
['t', 'shakespeare-plugin'],
|
||||
],
|
||||
content: '',
|
||||
sig: 'test-signature',
|
||||
};
|
||||
|
||||
// Verify the event has the correct kind
|
||||
expect(validEvent.kind).toBe(30617);
|
||||
|
||||
// Verify required tags exist
|
||||
const dTag = validEvent.tags.find(([name]) => name === 'd')?.[1];
|
||||
const nameTag = validEvent.tags.find(([name]) => name === 'name')?.[1];
|
||||
const tTag = validEvent.tags.find(([name, value]) => name === 't' && value === 'shakespeare-plugin');
|
||||
|
||||
expect(dTag).toBe('test-plugin');
|
||||
expect(nameTag).toBe('Test Plugin');
|
||||
expect(tTag).toBeDefined();
|
||||
});
|
||||
|
||||
it('should identify required fields for plugin discovery', () => {
|
||||
const event: NostrEvent = {
|
||||
id: 'test-event-id',
|
||||
pubkey: 'test-pubkey',
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
kind: 30617,
|
||||
tags: [
|
||||
['d', 'minimal-plugin'],
|
||||
['name', 'Minimal Plugin'],
|
||||
['t', 'shakespeare-plugin'],
|
||||
],
|
||||
content: '',
|
||||
sig: 'test-signature',
|
||||
};
|
||||
|
||||
const dTag = event.tags.find(([name]) => name === 'd')?.[1];
|
||||
const nameTag = event.tags.find(([name]) => name === 'name')?.[1];
|
||||
|
||||
// These are the minimum required fields
|
||||
expect(dTag).toBeDefined();
|
||||
expect(nameTag).toBeDefined();
|
||||
});
|
||||
|
||||
it('should handle optional fields gracefully', () => {
|
||||
const event: NostrEvent = {
|
||||
id: 'test-event-id',
|
||||
pubkey: 'test-pubkey',
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
kind: 30617,
|
||||
tags: [
|
||||
['d', 'plugin-without-optional'],
|
||||
['name', 'Plugin Without Optional Fields'],
|
||||
['t', 'shakespeare-plugin'],
|
||||
],
|
||||
content: '',
|
||||
sig: 'test-signature',
|
||||
};
|
||||
|
||||
const descriptionTag = event.tags.find(([name]) => name === 'description')?.[1];
|
||||
const cloneTag = event.tags.find(([name]) => name === 'clone')?.[1];
|
||||
const webTag = event.tags.find(([name]) => name === 'web')?.[1];
|
||||
|
||||
// Optional fields should be undefined
|
||||
expect(descriptionTag).toBeUndefined();
|
||||
expect(cloneTag).toBeUndefined();
|
||||
expect(webTag).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
import { useCurrentUser } from './useCurrentUser';
|
||||
import { useContacts } from './useContacts';
|
||||
|
||||
export interface DiscoveredPlugin {
|
||||
id: string;
|
||||
event: NostrEvent;
|
||||
name: string;
|
||||
description: string;
|
||||
cloneUrl?: string;
|
||||
webUrl?: string;
|
||||
author: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to discover Shakespeare plugins on Nostr
|
||||
* Queries NIP-34 git repository announcements with t-tag "shakespeare-plugin"
|
||||
* Filters to only show plugins by the current user and people they follow
|
||||
*/
|
||||
export function useDiscoverPlugins() {
|
||||
const { nostr } = useNostr();
|
||||
const { user } = useCurrentUser();
|
||||
const { data: contacts } = useContacts(user?.pubkey);
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['discover-plugins', user?.pubkey, contacts],
|
||||
queryFn: async () => {
|
||||
// Build authors list: current user + people they follow
|
||||
const authors: string[] = [];
|
||||
if (user?.pubkey) {
|
||||
authors.push(user.pubkey);
|
||||
}
|
||||
if (contacts && contacts.length > 0) {
|
||||
authors.push(...contacts);
|
||||
}
|
||||
|
||||
// If no authors (user not logged in or no follows), return empty array
|
||||
if (authors.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Query NIP-34 repository announcements (kind 30617) with shakespeare-plugin tag
|
||||
// Filter by authors: current user + people they follow
|
||||
const events = await nostr.query(
|
||||
[
|
||||
{
|
||||
kinds: [30617],
|
||||
authors,
|
||||
'#t': ['shakespeare-plugin'],
|
||||
limit: 100,
|
||||
},
|
||||
],
|
||||
{ signal: AbortSignal.timeout(3000) }
|
||||
);
|
||||
|
||||
// Transform events into DiscoveredPlugin objects
|
||||
const plugins: DiscoveredPlugin[] = events
|
||||
.map((event): DiscoveredPlugin | null => {
|
||||
const dTag = event.tags.find(([name]) => name === 'd')?.[1];
|
||||
const nameTag = event.tags.find(([name]) => name === 'name')?.[1];
|
||||
const descriptionTag = event.tags.find(([name]) => name === 'description')?.[1];
|
||||
const cloneTag = event.tags.find(([name]) => name === 'clone')?.[1];
|
||||
const webTag = event.tags.find(([name]) => name === 'web')?.[1];
|
||||
|
||||
// Skip events without required fields
|
||||
if (!dTag || !nameTag) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
id: dTag,
|
||||
event,
|
||||
name: nameTag,
|
||||
description: descriptionTag || '',
|
||||
cloneUrl: cloneTag,
|
||||
webUrl: webTag,
|
||||
author: event.pubkey,
|
||||
};
|
||||
})
|
||||
.filter((plugin): plugin is DiscoveredPlugin => plugin !== null);
|
||||
|
||||
return plugins;
|
||||
},
|
||||
staleTime: 5 * 60 * 1000, // 5 minutes
|
||||
});
|
||||
}
|
||||
@@ -17,5 +17,7 @@ export function useFSPaths() {
|
||||
tmpPath: config.fsPathTmp,
|
||||
/** Plugins directory path (default: /plugins) */
|
||||
pluginsPath: config.fsPathPlugins,
|
||||
/** Templates directory path (default: /templates) */
|
||||
templatesPath: config.fsPathTemplates,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
import type { Repository } from './useUserRepositories';
|
||||
|
||||
// Kind 30617 for repository announcements (NIP-34)
|
||||
const REPOSITORY_KIND = 30617;
|
||||
|
||||
/**
|
||||
* Hook to get repositories from a list of followed users
|
||||
*/
|
||||
export function useFollowedRepositories(followedPubkeys: string[] = []) {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['nostr', 'followed-repositories', followedPubkeys.sort().join(',')],
|
||||
queryFn: async (): Promise<Repository[]> => {
|
||||
if (followedPubkeys.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Get all repository announcements from followed users
|
||||
const events = await nostr.query([{
|
||||
kinds: [REPOSITORY_KIND],
|
||||
authors: followedPubkeys,
|
||||
limit: 500, // Increased limit to get more repos from follows
|
||||
}], { signal: AbortSignal.timeout(5000) });
|
||||
|
||||
// Process repository events
|
||||
const repositories: Repository[] = [];
|
||||
const repoMap = new Map<string, NostrEvent>();
|
||||
|
||||
// Group by author+d-tag to get latest version of each repo
|
||||
for (const event of events) {
|
||||
const dTag = event.tags.find(tag => tag[0] === 'd')?.[1];
|
||||
if (!dTag) continue;
|
||||
|
||||
const key = `${event.pubkey}:${dTag}`;
|
||||
const existing = repoMap.get(key);
|
||||
if (!existing || event.created_at > existing.created_at) {
|
||||
repoMap.set(key, event);
|
||||
}
|
||||
}
|
||||
|
||||
// Convert to Repository objects
|
||||
for (const [, event] of repoMap) {
|
||||
try {
|
||||
const dTag = event.tags.find(tag => tag[0] === 'd')?.[1];
|
||||
if (!dTag) continue;
|
||||
|
||||
const name = event.tags.find(tag => tag[0] === 'name')?.[1] || dTag;
|
||||
const description = event.tags.find(tag => tag[0] === 'description')?.[1] || '';
|
||||
const webUrls = event.tags.filter(tag => tag[0] === 'web').map(tag => tag[1]).filter(Boolean);
|
||||
const cloneUrls = event.tags.filter(tag => tag[0] === 'clone').map(tag => tag[1]).filter(Boolean);
|
||||
const relays = event.tags.filter(tag => tag[0] === 'relays').map(tag => tag[1]).filter(Boolean);
|
||||
const maintainers = event.tags.filter(tag => tag[0] === 'maintainers').map(tag => tag[1]).filter(Boolean);
|
||||
const repoTags = event.tags.filter(tag => tag[0] === 't' && tag[1] !== 'personal-fork').map(tag => tag[1]);
|
||||
const earliestUniqueCommit = event.tags.find(tag => tag[0] === 'r' && tag[2] === 'euc')?.[1];
|
||||
const isPersonalFork = event.tags.some(tag => tag[0] === 't' && tag[1] === 'personal-fork');
|
||||
|
||||
// Filter out invalid repositories without clone URLs
|
||||
if (cloneUrls.length === 0) {
|
||||
console.warn('Skipping repository without clone URLs:', dTag);
|
||||
continue;
|
||||
}
|
||||
|
||||
repositories.push({
|
||||
...event,
|
||||
repoId: dTag,
|
||||
name,
|
||||
description,
|
||||
webUrls,
|
||||
cloneUrls,
|
||||
relays,
|
||||
maintainers,
|
||||
repoTags,
|
||||
earliestUniqueCommit,
|
||||
isPersonalFork,
|
||||
});
|
||||
} catch (error) {
|
||||
console.warn('Failed to parse repository:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by created_at (newest first)
|
||||
return repositories.sort((a, b) => b.created_at - a.created_at);
|
||||
},
|
||||
enabled: followedPubkeys.length > 0,
|
||||
staleTime: 30000, // 30 seconds
|
||||
refetchInterval: 60000, // 1 minute
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,503 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
import { useGenerateProjectInfo } from './useGenerateProjectInfo';
|
||||
import { useAISettings } from './useAISettings';
|
||||
import { useCurrentUser } from './useCurrentUser';
|
||||
import { useAppContext } from './useAppContext';
|
||||
import { useProjectsManager } from './useProjectsManager';
|
||||
import { createAIClient } from '@/lib/ai-client';
|
||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
import type { ProjectsManager } from '@/lib/ProjectsManager';
|
||||
import type { ProjectTemplate } from '@/contexts/AppContext';
|
||||
|
||||
// Mock the hooks and dependencies
|
||||
vi.mock('./useAISettings');
|
||||
vi.mock('./useCurrentUser');
|
||||
vi.mock('./useAppContext');
|
||||
vi.mock('./useProjectsManager');
|
||||
vi.mock('@/lib/ai-client');
|
||||
vi.mock('@/lib/parseProviderModel');
|
||||
|
||||
describe('useGenerateProjectInfo', () => {
|
||||
const mockUseAISettings = vi.mocked(useAISettings);
|
||||
const mockUseCurrentUser = vi.mocked(useCurrentUser);
|
||||
const mockUseAppContext = vi.mocked(useAppContext);
|
||||
const mockUseProjectsManager = vi.mocked(useProjectsManager);
|
||||
const mockCreateAIClient = vi.mocked(createAIClient);
|
||||
const mockParseProviderModel = vi.mocked(parseProviderModel);
|
||||
|
||||
const defaultTemplates: ProjectTemplate[] = [
|
||||
{
|
||||
name: "MKStack",
|
||||
description: "Build Nostr clients with React.",
|
||||
url: "https://gitlab.com/soapbox-pub/mkstack.git"
|
||||
},
|
||||
{
|
||||
name: "VanillaJS",
|
||||
description: "Simple vanilla JavaScript template.",
|
||||
url: "https://github.com/example/vanilla-template.git"
|
||||
}
|
||||
];
|
||||
|
||||
let mockGetProject: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
// Mock fetch globally
|
||||
global.fetch = vi.fn();
|
||||
|
||||
// Mock useCurrentUser to return undefined user by default
|
||||
mockUseCurrentUser.mockReturnValue({
|
||||
user: undefined,
|
||||
users: [],
|
||||
});
|
||||
|
||||
// Mock useAppContext
|
||||
const config = {
|
||||
theme: 'dark' as const,
|
||||
relayMetadata: {
|
||||
relays: [{ url: 'wss://relay.damus.io', read: true, write: true }],
|
||||
updatedAt: 0,
|
||||
},
|
||||
templates: defaultTemplates,
|
||||
esmUrl: 'https://esm.sh',
|
||||
corsProxy: 'https://proxy.example.com/{href}',
|
||||
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
||||
previewDomain: 'local-shakespeare.dev',
|
||||
showcaseEnabled: true,
|
||||
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
|
||||
ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'],
|
||||
fsPathProjects: '/projects',
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
fsPathPlugins: '/plugins',
|
||||
fsPathTemplates: '/templates',
|
||||
sentryDsn: '',
|
||||
sentryEnabled: false,
|
||||
};
|
||||
mockUseAppContext.mockReturnValue({
|
||||
config,
|
||||
defaultConfig: config,
|
||||
updateConfig: vi.fn(),
|
||||
});
|
||||
|
||||
// Mock useProjectsManager
|
||||
mockGetProject = vi.fn().mockResolvedValue(null);
|
||||
const mockProjectsManager = {
|
||||
getProject: mockGetProject,
|
||||
} as unknown as ProjectsManager;
|
||||
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
|
||||
|
||||
// Mock parseProviderModel
|
||||
mockParseProviderModel.mockReturnValue({
|
||||
provider: { id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' },
|
||||
model: 'gpt-4',
|
||||
});
|
||||
|
||||
// Mock createAIClient
|
||||
const mockCompletion = {
|
||||
choices: [{
|
||||
message: {
|
||||
tool_calls: [{
|
||||
type: 'function' as const,
|
||||
function: {
|
||||
name: 'create_project',
|
||||
arguments: JSON.stringify({
|
||||
project_name: 'test-project-name',
|
||||
template_url: 'https://gitlab.com/soapbox-pub/mkstack.git'
|
||||
})
|
||||
}
|
||||
}]
|
||||
}
|
||||
}]
|
||||
};
|
||||
const mockOpenAI = {
|
||||
chat: {
|
||||
completions: {
|
||||
create: vi.fn().mockResolvedValue(mockCompletion)
|
||||
}
|
||||
}
|
||||
} as unknown as ReturnType<typeof createAIClient>;
|
||||
mockCreateAIClient.mockReturnValue(mockOpenAI);
|
||||
});
|
||||
|
||||
it('should return not configured when AI settings are not configured', () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: { providers: [], recentlyUsedModels: [], mcpServers: {} },
|
||||
isConfigured: false,
|
||||
updateSettings: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useGenerateProjectInfo());
|
||||
|
||||
expect(result.current.isConfigured).toBe(false);
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
});
|
||||
|
||||
it('should throw error when trying to generate without configuration', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: { providers: [], recentlyUsedModels: [], mcpServers: {} },
|
||||
isConfigured: false,
|
||||
updateSettings: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useGenerateProjectInfo());
|
||||
|
||||
await expect(result.current.generateProjectInfo('openai/gpt-4', 'test prompt')).rejects.toThrow(
|
||||
'AI settings not configured'
|
||||
);
|
||||
});
|
||||
|
||||
it('should throw error when prompt is empty', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: [
|
||||
{ id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
],
|
||||
recentlyUsedModels: [],
|
||||
mcpServers: {}
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useGenerateProjectInfo());
|
||||
|
||||
await expect(result.current.generateProjectInfo('openai/gpt-4', '')).rejects.toThrow(
|
||||
'Prompt cannot be empty'
|
||||
);
|
||||
});
|
||||
|
||||
it('should throw error when no templates are configured', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: [
|
||||
{ id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
],
|
||||
recentlyUsedModels: [],
|
||||
mcpServers: {}
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
});
|
||||
|
||||
// Mock config with no templates
|
||||
const config = {
|
||||
theme: 'dark' as const,
|
||||
relayMetadata: {
|
||||
relays: [{ url: 'wss://relay.damus.io', read: true, write: true }],
|
||||
updatedAt: 0,
|
||||
},
|
||||
templates: [],
|
||||
esmUrl: 'https://esm.sh',
|
||||
corsProxy: 'https://proxy.example.com/{href}',
|
||||
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
||||
previewDomain: 'local-shakespeare.dev',
|
||||
showcaseEnabled: true,
|
||||
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
|
||||
ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'],
|
||||
fsPathProjects: '/projects',
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
fsPathPlugins: '/plugins',
|
||||
fsPathTemplates: '/templates',
|
||||
sentryDsn: '',
|
||||
sentryEnabled: false,
|
||||
};
|
||||
mockUseAppContext.mockReturnValue({
|
||||
config,
|
||||
defaultConfig: config,
|
||||
updateConfig: vi.fn(),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useGenerateProjectInfo());
|
||||
|
||||
await expect(result.current.generateProjectInfo('openai/gpt-4', 'test prompt')).rejects.toThrow(
|
||||
'No templates configured'
|
||||
);
|
||||
});
|
||||
|
||||
it('should successfully generate project info with template selection', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: [
|
||||
{ id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
],
|
||||
recentlyUsedModels: [],
|
||||
mcpServers: {}
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useGenerateProjectInfo());
|
||||
|
||||
const projectInfo = await result.current.generateProjectInfo('openai/gpt-4', 'A social media app for developers');
|
||||
|
||||
expect(projectInfo).toEqual({
|
||||
projectId: 'test-project-name',
|
||||
template: {
|
||||
name: 'MKStack',
|
||||
description: 'Build Nostr clients with React.',
|
||||
url: 'https://gitlab.com/soapbox-pub/mkstack.git'
|
||||
}
|
||||
});
|
||||
expect(mockParseProviderModel).toHaveBeenCalledWith('openai/gpt-4', [
|
||||
{ id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
]);
|
||||
expect(mockCreateAIClient).toHaveBeenCalledWith(
|
||||
{ id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' },
|
||||
undefined,
|
||||
'https://proxy.example.com/{href}'
|
||||
);
|
||||
});
|
||||
|
||||
it('should fallback to first template when AI selects invalid template URL', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: [
|
||||
{ id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
],
|
||||
recentlyUsedModels: [],
|
||||
mcpServers: {}
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
});
|
||||
|
||||
// Mock AI to return invalid template URL
|
||||
const mockCompletion = {
|
||||
choices: [{
|
||||
message: {
|
||||
tool_calls: [{
|
||||
type: 'function' as const,
|
||||
function: {
|
||||
name: 'create_project',
|
||||
arguments: JSON.stringify({
|
||||
project_name: 'test-project',
|
||||
template_url: 'https://invalid-url.com/template.git'
|
||||
})
|
||||
}
|
||||
}]
|
||||
}
|
||||
}]
|
||||
};
|
||||
const mockOpenAI = {
|
||||
chat: {
|
||||
completions: {
|
||||
create: vi.fn().mockResolvedValue(mockCompletion)
|
||||
}
|
||||
}
|
||||
} as unknown as ReturnType<typeof createAIClient>;
|
||||
mockCreateAIClient.mockReturnValue(mockOpenAI);
|
||||
|
||||
const { result } = renderHook(() => useGenerateProjectInfo());
|
||||
|
||||
const projectInfo = await result.current.generateProjectInfo('openai/gpt-4', 'test prompt');
|
||||
|
||||
expect(projectInfo.template.url).toBe('https://gitlab.com/soapbox-pub/mkstack.git');
|
||||
expect(projectInfo.projectId).toBe('untitled');
|
||||
});
|
||||
|
||||
it('should increment AI-generated ID when project already exists', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: [
|
||||
{ id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
],
|
||||
recentlyUsedModels: [],
|
||||
mcpServers: {}
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
});
|
||||
|
||||
// Reset and override the mock to return project on first call, null on second
|
||||
mockGetProject.mockReset();
|
||||
mockGetProject
|
||||
.mockResolvedValueOnce({ id: 'test-project-name', name: 'Test Project', path: '/projects/test-project-name', lastModified: new Date() })
|
||||
.mockResolvedValue(null);
|
||||
|
||||
const { result } = renderHook(() => useGenerateProjectInfo());
|
||||
|
||||
const projectInfo = await result.current.generateProjectInfo('openai/gpt-4', 'test prompt');
|
||||
|
||||
expect(projectInfo.projectId).toBe('test-project-name-1');
|
||||
expect(projectInfo.template.url).toBe('https://gitlab.com/soapbox-pub/mkstack.git');
|
||||
expect(mockGetProject).toHaveBeenCalledTimes(2);
|
||||
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'test-project-name');
|
||||
expect(mockGetProject).toHaveBeenNthCalledWith(2, 'test-project-name-1');
|
||||
});
|
||||
|
||||
it('should increment multiple times when necessary', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: [
|
||||
{ id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
],
|
||||
recentlyUsedModels: [],
|
||||
mcpServers: {}
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
});
|
||||
|
||||
// Reset and override the mock - base and -1 exist, -2 is available
|
||||
mockGetProject.mockReset();
|
||||
mockGetProject
|
||||
.mockResolvedValueOnce({ id: 'test-project-name', name: 'Test Project', path: '/projects/test-project-name', lastModified: new Date() })
|
||||
.mockResolvedValueOnce({ id: 'test-project-name-1', name: 'Test Project 1', path: '/projects/test-project-name-1', lastModified: new Date() })
|
||||
.mockResolvedValue(null);
|
||||
|
||||
const { result } = renderHook(() => useGenerateProjectInfo());
|
||||
|
||||
const projectInfo = await result.current.generateProjectInfo('openai/gpt-4', 'test prompt');
|
||||
|
||||
expect(projectInfo.projectId).toBe('test-project-name-2');
|
||||
expect(projectInfo.template.url).toBe('https://gitlab.com/soapbox-pub/mkstack.git');
|
||||
expect(mockGetProject).toHaveBeenCalledTimes(3);
|
||||
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'test-project-name');
|
||||
expect(mockGetProject).toHaveBeenNthCalledWith(2, 'test-project-name-1');
|
||||
expect(mockGetProject).toHaveBeenNthCalledWith(3, 'test-project-name-2');
|
||||
});
|
||||
|
||||
it('should handle loading state correctly', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: [
|
||||
{ id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
],
|
||||
recentlyUsedModels: [],
|
||||
mcpServers: {}
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useGenerateProjectInfo());
|
||||
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
|
||||
const promise = result.current.generateProjectInfo('openai/gpt-4', 'Test prompt');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isLoading).toBe(false); // Should be false after completion
|
||||
});
|
||||
|
||||
await promise;
|
||||
});
|
||||
|
||||
it('should select second template when AI chooses it', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: [
|
||||
{ id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
],
|
||||
recentlyUsedModels: [],
|
||||
mcpServers: {}
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
});
|
||||
|
||||
// Mock AI to select the second template
|
||||
const mockCompletion = {
|
||||
choices: [{
|
||||
message: {
|
||||
tool_calls: [{
|
||||
type: 'function' as const,
|
||||
function: {
|
||||
name: 'create_project',
|
||||
arguments: JSON.stringify({
|
||||
project_name: 'vanilla-app',
|
||||
template_url: 'https://github.com/example/vanilla-template.git'
|
||||
})
|
||||
}
|
||||
}]
|
||||
}
|
||||
}]
|
||||
};
|
||||
const mockOpenAI = {
|
||||
chat: {
|
||||
completions: {
|
||||
create: vi.fn().mockResolvedValue(mockCompletion)
|
||||
}
|
||||
}
|
||||
} as unknown as ReturnType<typeof createAIClient>;
|
||||
mockCreateAIClient.mockReturnValue(mockOpenAI);
|
||||
|
||||
const { result } = renderHook(() => useGenerateProjectInfo());
|
||||
|
||||
const projectInfo = await result.current.generateProjectInfo('openai/gpt-4', 'A simple vanilla JS app');
|
||||
|
||||
expect(projectInfo).toEqual({
|
||||
projectId: 'vanilla-app',
|
||||
template: {
|
||||
name: 'VanillaJS',
|
||||
description: 'Simple vanilla JavaScript template.',
|
||||
url: 'https://github.com/example/vanilla-template.git'
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,187 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { createAIClient } from '@/lib/ai-client';
|
||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
import type { ChatCompletionMessageParam, ChatCompletionTool } from 'openai/resources/chat/completions';
|
||||
|
||||
interface UseGenerateProjectInfoOptions {
|
||||
onError?: (error: string) => void;
|
||||
}
|
||||
|
||||
interface ProjectInfo {
|
||||
projectId: string;
|
||||
template: {
|
||||
name: string;
|
||||
description: string;
|
||||
url: string;
|
||||
};
|
||||
}
|
||||
|
||||
export function useGenerateProjectInfo({ onError }: UseGenerateProjectInfoOptions = {}) {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const { settings, isConfigured } = useAISettings();
|
||||
const { user } = useCurrentUser();
|
||||
const { config } = useAppContext();
|
||||
const projectsManager = useProjectsManager();
|
||||
|
||||
// Helper function to generate incremented project name
|
||||
// Note: This assumes the baseId already exists (caller has verified this)
|
||||
const generateIncrementedId = useCallback(async (baseId: string, template: { url: string; name: string; description: string }, baseExists: boolean = true): Promise<ProjectInfo> => {
|
||||
// If base doesn't exist, just use it
|
||||
if (!baseExists) {
|
||||
const existingProject = await projectsManager.getProject(baseId);
|
||||
if (existingProject === null) {
|
||||
return {
|
||||
projectId: baseId,
|
||||
template,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Start incrementing from -1
|
||||
let counter = 1;
|
||||
let fallbackId = `${baseId}-${counter}`;
|
||||
let existingProject = await projectsManager.getProject(fallbackId);
|
||||
|
||||
// Keep incrementing until we find an available name
|
||||
while (existingProject !== null) {
|
||||
counter++;
|
||||
fallbackId = `${baseId}-${counter}`;
|
||||
existingProject = await projectsManager.getProject(fallbackId);
|
||||
}
|
||||
|
||||
return {
|
||||
projectId: fallbackId,
|
||||
template,
|
||||
};
|
||||
}, [projectsManager]);
|
||||
|
||||
const generateProjectInfo = useCallback(async (providerModel: string, prompt: string): Promise<ProjectInfo> => {
|
||||
if (!isConfigured) {
|
||||
throw new Error('AI settings not configured');
|
||||
}
|
||||
|
||||
if (!prompt.trim()) {
|
||||
throw new Error('Prompt cannot be empty');
|
||||
}
|
||||
|
||||
if (config.templates.length === 0) {
|
||||
throw new Error('No templates configured');
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
// Initialize OpenAI client
|
||||
const { model, provider } = parseProviderModel(providerModel, settings.providers);
|
||||
const openai = createAIClient(provider, user, config.corsProxy);
|
||||
|
||||
// Create project creation tool
|
||||
const createProjectTool: ChatCompletionTool = {
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'create_project',
|
||||
description: 'Create a new project by choosing a name and selecting the most appropriate template. You must call this tool to create the project.',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
project_name: {
|
||||
type: 'string',
|
||||
description: 'A short, unique, and memorable name for the project. Should be lowercase, use hyphens instead of spaces, and contain only alphanumeric characters and hyphens.',
|
||||
},
|
||||
template_url: {
|
||||
type: 'string',
|
||||
description: `The Git URL of the selected template. Must be one of: ${config.templates.map(t => t.url).join(', ')}`,
|
||||
enum: config.templates.map(t => t.url),
|
||||
},
|
||||
},
|
||||
required: ['project_name', 'template_url'],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const systemPrompt = `You are a product expert helping users create new projects. Given the user's project description, you must:
|
||||
|
||||
1. Generate a short, unique, and memorable name for their product or brand. The name should be lowercase, use hyphens instead of spaces, and contain only alphanumeric characters and hyphens. Avoid using special characters or underscores.
|
||||
|
||||
2. Select the most appropriate template from the available options:
|
||||
${config.templates.map(t => ` - ${t.name}: ${t.description} (${t.url})`).join('\n')}
|
||||
|
||||
You MUST call the create_project tool with your choices.`;
|
||||
|
||||
const messages: ChatCompletionMessageParam[] = [
|
||||
{ role: 'system', content: systemPrompt },
|
||||
{ role: 'user', content: prompt }
|
||||
];
|
||||
|
||||
// Call AI with tool
|
||||
const completion = await openai.chat.completions.create({
|
||||
model,
|
||||
messages,
|
||||
tools: [createProjectTool],
|
||||
tool_choice: { type: 'function', function: { name: 'create_project' } },
|
||||
temperature: 1,
|
||||
});
|
||||
|
||||
const toolCall = completion.choices[0]?.message?.tool_calls?.[0];
|
||||
|
||||
if (!toolCall || toolCall.type !== 'function' || toolCall.function.name !== 'create_project') {
|
||||
throw new Error('AI failed to create the project');
|
||||
}
|
||||
|
||||
const args = JSON.parse(toolCall.function.arguments);
|
||||
const templateUrl = args.template_url as string;
|
||||
const projectId = args.project_name as string;
|
||||
|
||||
// Validate template URL
|
||||
const selectedTemplate = config.templates.find(t => t.url === templateUrl);
|
||||
if (!selectedTemplate) {
|
||||
// Fallback to first template if invalid URL selected
|
||||
console.warn(`Invalid template URL selected: ${templateUrl}, falling back to first template`);
|
||||
return await generateIncrementedId('untitled', config.templates[0], false);
|
||||
}
|
||||
|
||||
// Validate the generated project ID
|
||||
const validIdRegex = /^[a-z0-9]+(-[a-z0-9]+)*$/;
|
||||
if (projectId && projectId.length <= 50 && validIdRegex.test(projectId)) {
|
||||
// Check if project exists
|
||||
const existingProject = await projectsManager.getProject(projectId);
|
||||
if (existingProject === null) {
|
||||
// Valid and unique project ID
|
||||
return {
|
||||
projectId,
|
||||
template: selectedTemplate,
|
||||
};
|
||||
}
|
||||
|
||||
// Project already exists - increment the AI-generated ID (baseExists = true)
|
||||
return await generateIncrementedId(projectId, selectedTemplate, true);
|
||||
}
|
||||
|
||||
// If we reach here, the regex failed - fall back to "untitled" with number suffixes
|
||||
return await generateIncrementedId('untitled', selectedTemplate, false);
|
||||
} catch (error) {
|
||||
// On any error, fall back to first template with untitled name
|
||||
console.error('Error generating project info:', error);
|
||||
|
||||
if (config.templates.length === 0) {
|
||||
const errorMessage = 'No templates configured';
|
||||
onError?.(errorMessage);
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
return await generateIncrementedId('untitled', config.templates[0], false);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [isConfigured, settings, onError, user, projectsManager, config.corsProxy, config.templates, generateIncrementedId]);
|
||||
|
||||
return {
|
||||
generateProjectInfo,
|
||||
isLoading,
|
||||
isConfigured
|
||||
};
|
||||
}
|
||||
@@ -37,7 +37,7 @@ function createWrapper(corsProxy: string) {
|
||||
relays: [{ url: 'wss://relay.test', read: true, write: true }],
|
||||
updatedAt: 0,
|
||||
},
|
||||
projectTemplate: 'https://gitlab.com/soapbox-pub/mkstack.git',
|
||||
templates: [{ name: 'MKStack', description: 'Build Nostr clients with React.', url: 'https://gitlab.com/soapbox-pub/mkstack.git' }],
|
||||
esmUrl: 'https://esm.test',
|
||||
corsProxy,
|
||||
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
||||
@@ -49,6 +49,7 @@ function createWrapper(corsProxy: string) {
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
fsPathPlugins: '/plugins',
|
||||
fsPathTemplates: '/templates',
|
||||
sentryDsn: '',
|
||||
sentryEnabled: false,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,720 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
import { useGitFetch } from './useGitFetch';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
|
||||
// Create mocks that can be reconfigured per test
|
||||
const mockGit = {
|
||||
findRoot: vi.fn(),
|
||||
listRemotes: vi.fn(),
|
||||
currentBranch: vi.fn(),
|
||||
resolveRef: vi.fn(),
|
||||
fetch: vi.fn(),
|
||||
};
|
||||
|
||||
const mockToast = vi.fn();
|
||||
const mockInvalidateQueries = vi.fn();
|
||||
|
||||
// Mock the git operations
|
||||
vi.mock('./useGit', () => ({
|
||||
useGit: () => ({
|
||||
git: mockGit,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('./useGitSettings', () => ({
|
||||
useGitSettings: () => ({
|
||||
settings: {
|
||||
credentials: [],
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('./useFSPaths', () => ({
|
||||
useFSPaths: () => ({
|
||||
projectsPath: '/projects',
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('./useToast', () => ({
|
||||
useToast: () => ({
|
||||
toast: mockToast,
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock QueryClient to track invalidateQueries calls
|
||||
vi.mock('@tanstack/react-query', async () => {
|
||||
const actual = await vi.importActual('@tanstack/react-query');
|
||||
return {
|
||||
...actual,
|
||||
useQueryClient: () => ({
|
||||
invalidateQueries: mockInvalidateQueries,
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
describe('useGitFetch', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockToast.mockClear();
|
||||
mockInvalidateQueries.mockClear();
|
||||
});
|
||||
|
||||
it('returns null state when projectId is null', async () => {
|
||||
const { result } = renderHook(() => useGitFetch(null), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
// When projectId is null, the query is disabled and won't fetch
|
||||
// So we just check the initial state
|
||||
expect(result.current.data).toBeUndefined();
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
expect(result.current.isSuccess).toBe(false);
|
||||
});
|
||||
|
||||
it('fetches remote updates successfully when default branch is checked out', async () => {
|
||||
// Setup mocks for default branch scenario
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('main');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Mock resolveRef calls in order:
|
||||
// 1. Read symbolic ref for default branch (returns the ref path)
|
||||
// 2. Get default branch OID before fetch
|
||||
// 3. Get current branch OID before fetch
|
||||
// 4. Get default branch OID after fetch
|
||||
// 5. Get current branch OID after fetch
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
|
||||
.mockResolvedValueOnce('abc123') // before default
|
||||
.mockResolvedValueOnce('abc123') // before current (same as default)
|
||||
.mockResolvedValueOnce('abc123') // after default
|
||||
.mockResolvedValueOnce('abc123'); // after current (same as default)
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.data).toMatchObject({
|
||||
defaultBranch: 'main',
|
||||
currentBranch: 'main',
|
||||
remoteUrl: 'https://github.com/test/repo.git',
|
||||
hasChanges: false,
|
||||
});
|
||||
|
||||
// Verify fetch was called
|
||||
expect(mockGit.fetch).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
dir: '/projects/test-project',
|
||||
remote: 'origin',
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('fetches remote updates successfully when non-default branch is checked out', async () => {
|
||||
// Setup mocks for non-default branch scenario
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('feature-branch');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Mock resolveRef calls in order:
|
||||
// 1. Read symbolic ref for default branch (returns the ref path)
|
||||
// 2. Get default branch OID before fetch
|
||||
// 3. Get current branch OID before fetch
|
||||
// 4. Get default branch OID after fetch
|
||||
// 5. Get current branch OID after fetch
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
|
||||
.mockResolvedValueOnce('abc123') // before default (main)
|
||||
.mockResolvedValueOnce('def456') // before current (feature-branch)
|
||||
.mockResolvedValueOnce('abc123') // after default (main)
|
||||
.mockResolvedValueOnce('def456'); // after current (feature-branch)
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.data).toMatchObject({
|
||||
defaultBranch: 'main',
|
||||
currentBranch: 'feature-branch',
|
||||
remoteUrl: 'https://github.com/test/repo.git',
|
||||
hasChanges: false,
|
||||
});
|
||||
|
||||
// Verify fetch was called
|
||||
expect(mockGit.fetch).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
dir: '/projects/test-project',
|
||||
remote: 'origin',
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('detects changes on default branch when checked out', async () => {
|
||||
// Setup mocks
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('main');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Mock resolveRef to simulate changes on default branch
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
|
||||
.mockResolvedValueOnce('abc123') // before default
|
||||
.mockResolvedValueOnce('abc123') // before current (same as default)
|
||||
.mockResolvedValueOnce('xyz789') // after default (changed!)
|
||||
.mockResolvedValueOnce('xyz789'); // after current (changed!)
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.data).toMatchObject({
|
||||
defaultBranch: 'main',
|
||||
currentBranch: 'main',
|
||||
hasChanges: true, // Changes detected on default branch
|
||||
});
|
||||
});
|
||||
|
||||
it('detects changes on non-default branch when checked out', async () => {
|
||||
// Setup mocks
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('feature-branch');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Mock resolveRef to simulate changes on non-default branch
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
|
||||
.mockResolvedValueOnce('abc123') // before default
|
||||
.mockResolvedValueOnce('def456') // before current
|
||||
.mockResolvedValueOnce('abc123') // after default (no change)
|
||||
.mockResolvedValueOnce('xyz789'); // after current (changed!)
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.data).toMatchObject({
|
||||
defaultBranch: 'main',
|
||||
currentBranch: 'feature-branch',
|
||||
hasChanges: true, // Changes detected on current branch
|
||||
});
|
||||
});
|
||||
|
||||
it('detects changes on both default and non-default branches', async () => {
|
||||
// Setup mocks
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('feature-branch');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Mock resolveRef to simulate changes on both branches
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
|
||||
.mockResolvedValueOnce('abc123') // before default
|
||||
.mockResolvedValueOnce('def456') // before current
|
||||
.mockResolvedValueOnce('new111') // after default (changed!)
|
||||
.mockResolvedValueOnce('new222'); // after current (changed!)
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.data).toMatchObject({
|
||||
defaultBranch: 'main',
|
||||
currentBranch: 'feature-branch',
|
||||
hasChanges: true, // Changes detected on both branches
|
||||
});
|
||||
});
|
||||
|
||||
it('detects changes on default branch when non-default branch is checked out', async () => {
|
||||
// Setup mocks
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('feature-branch');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Mock resolveRef to simulate changes on default branch only
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
|
||||
.mockResolvedValueOnce('abc123') // before default
|
||||
.mockResolvedValueOnce('def456') // before current
|
||||
.mockResolvedValueOnce('xyz789') // after default (changed!)
|
||||
.mockResolvedValueOnce('def456'); // after current (no change)
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.data).toMatchObject({
|
||||
defaultBranch: 'main',
|
||||
currentBranch: 'feature-branch',
|
||||
hasChanges: true, // Changes detected on default branch
|
||||
});
|
||||
});
|
||||
|
||||
it('can be manually refetched', async () => {
|
||||
// Setup mocks
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('main');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Mock resolveRef for initial fetch
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123');
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
const firstFetchTime = result.current.data?.fetchedAt;
|
||||
|
||||
// Setup mocks for refetch
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123');
|
||||
|
||||
// Manually trigger refetch
|
||||
await result.current.refetch();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.data?.fetchedAt).toBeGreaterThanOrEqual(firstFetchTime || 0);
|
||||
});
|
||||
|
||||
// Verify fetch was called twice (initial + refetch)
|
||||
expect(mockGit.fetch).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
describe('Toast Notifications', () => {
|
||||
it('shows toast when default branch changes (on default branch)', async () => {
|
||||
// Setup mocks for initial fetch (no changes)
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('main');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Initial fetch - no changes
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123');
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
// No toast on initial load
|
||||
expect(mockToast).not.toHaveBeenCalled();
|
||||
|
||||
// Setup for refetch with changes
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('xyz789') // Changed!
|
||||
.mockResolvedValueOnce('xyz789');
|
||||
|
||||
// Trigger refetch
|
||||
await result.current.refetch();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToast).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// Verify toast message
|
||||
expect(mockToast).toHaveBeenCalledWith({
|
||||
title: 'Remote changes detected',
|
||||
description: 'The main branch has new commits available.',
|
||||
variant: 'default',
|
||||
});
|
||||
|
||||
// Verify git status was invalidated
|
||||
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
|
||||
(call) => call[0]?.queryKey?.[0] === 'git-status'
|
||||
);
|
||||
expect(gitStatusCalls).toHaveLength(1);
|
||||
expect(gitStatusCalls[0][0]).toEqual({
|
||||
queryKey: ['git-status', 'test-project'],
|
||||
});
|
||||
});
|
||||
|
||||
it('shows toast when non-default branch changes (on non-default branch)', async () => {
|
||||
// Setup mocks for initial fetch (no changes)
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('feature-branch');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Initial fetch - no changes
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456');
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
// No toast on initial load
|
||||
expect(mockToast).not.toHaveBeenCalled();
|
||||
|
||||
// Setup for refetch with changes on feature branch
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456')
|
||||
.mockResolvedValueOnce('abc123') // main unchanged
|
||||
.mockResolvedValueOnce('xyz789'); // feature-branch changed!
|
||||
|
||||
// Trigger refetch
|
||||
await result.current.refetch();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToast).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// Verify toast message for feature branch
|
||||
expect(mockToast).toHaveBeenCalledWith({
|
||||
title: 'Remote changes detected',
|
||||
description: 'The feature-branch branch has new commits available.',
|
||||
variant: 'default',
|
||||
});
|
||||
|
||||
// Verify git status was invalidated
|
||||
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
|
||||
(call) => call[0]?.queryKey?.[0] === 'git-status'
|
||||
);
|
||||
expect(gitStatusCalls).toHaveLength(1);
|
||||
expect(gitStatusCalls[0][0]).toEqual({
|
||||
queryKey: ['git-status', 'test-project'],
|
||||
});
|
||||
});
|
||||
|
||||
it('shows toast when default branch changes (on non-default branch)', async () => {
|
||||
// Setup mocks for initial fetch (no changes)
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('feature-branch');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Initial fetch - no changes
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456');
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
// No toast on initial load
|
||||
expect(mockToast).not.toHaveBeenCalled();
|
||||
|
||||
// Setup for refetch with changes on main branch only
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456')
|
||||
.mockResolvedValueOnce('xyz789') // main changed!
|
||||
.mockResolvedValueOnce('def456'); // feature-branch unchanged
|
||||
|
||||
// Trigger refetch
|
||||
await result.current.refetch();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToast).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// Verify toast message for main branch
|
||||
expect(mockToast).toHaveBeenCalledWith({
|
||||
title: 'Remote changes detected',
|
||||
description: 'The main branch has new commits available.',
|
||||
variant: 'default',
|
||||
});
|
||||
|
||||
// Verify git status was invalidated
|
||||
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
|
||||
(call) => call[0]?.queryKey?.[0] === 'git-status'
|
||||
);
|
||||
expect(gitStatusCalls).toHaveLength(1);
|
||||
expect(gitStatusCalls[0][0]).toEqual({
|
||||
queryKey: ['git-status', 'test-project'],
|
||||
});
|
||||
});
|
||||
|
||||
it('shows two toasts when both branches change (on non-default branch)', async () => {
|
||||
// Setup mocks for initial fetch (no changes)
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('feature-branch');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Initial fetch - no changes
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456');
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
// No toast on initial load
|
||||
expect(mockToast).not.toHaveBeenCalled();
|
||||
|
||||
// Setup for refetch with changes on both branches
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456')
|
||||
.mockResolvedValueOnce('new111') // main changed!
|
||||
.mockResolvedValueOnce('new222'); // feature-branch changed!
|
||||
|
||||
// Trigger refetch
|
||||
await result.current.refetch();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToast).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
// Verify both toast messages
|
||||
expect(mockToast).toHaveBeenCalledWith({
|
||||
title: 'Remote changes detected',
|
||||
description: 'The main branch has new commits available.',
|
||||
variant: 'default',
|
||||
});
|
||||
expect(mockToast).toHaveBeenCalledWith({
|
||||
title: 'Remote changes detected',
|
||||
description: 'The feature-branch branch has new commits available.',
|
||||
variant: 'default',
|
||||
});
|
||||
|
||||
// Verify git status was invalidated twice (once per toast)
|
||||
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
|
||||
(call) => call[0]?.queryKey?.[0] === 'git-status'
|
||||
);
|
||||
expect(gitStatusCalls).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('does not show toast on initial load', async () => {
|
||||
// Setup mocks
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('main');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Initial fetch with changes detected in the fetch itself
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('xyz789') // Changed from before to after fetch
|
||||
.mockResolvedValueOnce('xyz789');
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
// Should report changes in data
|
||||
expect(result.current.data?.hasChanges).toBe(true);
|
||||
|
||||
// But no toast on initial load
|
||||
expect(mockToast).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not show toast when no changes detected', async () => {
|
||||
// Setup mocks for initial fetch
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('main');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Initial fetch - no changes
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123');
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
// Setup for refetch with no changes
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123');
|
||||
|
||||
// Trigger refetch
|
||||
await result.current.refetch();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
// No toast should be shown
|
||||
expect(mockToast).not.toHaveBeenCalled();
|
||||
|
||||
// Verify git status was not invalidated (filter out other queries like 'nostr')
|
||||
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
|
||||
(call) => call[0]?.queryKey?.[0] === 'git-status'
|
||||
);
|
||||
expect(gitStatusCalls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('does not show duplicate toast for same branch when default equals current', async () => {
|
||||
// Setup mocks for initial fetch
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('main');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Initial fetch - no changes
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123');
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
// Setup for refetch with changes (both default and current are 'main')
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('xyz789')
|
||||
.mockResolvedValueOnce('xyz789');
|
||||
|
||||
// Trigger refetch
|
||||
await result.current.refetch();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToast).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// Should only show one toast (for default branch), not two
|
||||
expect(mockToast).toHaveBeenCalledWith({
|
||||
title: 'Remote changes detected',
|
||||
description: 'The main branch has new commits available.',
|
||||
variant: 'default',
|
||||
});
|
||||
|
||||
// Should only invalidate once
|
||||
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
|
||||
(call) => call[0]?.queryKey?.[0] === 'git-status'
|
||||
);
|
||||
expect(gitStatusCalls).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,370 @@
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useGit } from './useGit';
|
||||
import { useFSPaths } from './useFSPaths';
|
||||
import { useGitSettings } from './useGitSettings';
|
||||
import { useToast } from './useToast';
|
||||
import { findCredentialsForRepo } from '@/lib/gitCredentials';
|
||||
import { useEffect, useRef } from 'react';
|
||||
|
||||
interface FetchResult {
|
||||
defaultBranch: string | null;
|
||||
defaultBranchOid: string | null;
|
||||
currentBranch: string | null;
|
||||
currentBranchOid: string | null;
|
||||
fetchedAt: number;
|
||||
hasChanges: boolean;
|
||||
remoteUrl: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to fetch updates from remote repository and detect changes.
|
||||
* Polls every 60 seconds and shows toast notifications when changes are detected.
|
||||
*
|
||||
* @param projectId - The project ID to fetch for
|
||||
* @returns Query result with manual refetch capability
|
||||
*/
|
||||
export function useGitFetch(projectId: string | null) {
|
||||
const { git } = useGit();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { settings } = useGitSettings();
|
||||
const { toast } = useToast();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
// Track previous state to detect changes
|
||||
const previousStateRef = useRef<{
|
||||
defaultBranchOid: string | null;
|
||||
currentBranchOid: string | null;
|
||||
dataUpdatedAt: number;
|
||||
} | null>(null);
|
||||
|
||||
const query = useQuery({
|
||||
queryKey: ['git-fetch', projectId],
|
||||
queryFn: async (): Promise<FetchResult> => {
|
||||
console.log('=== GIT FETCH STARTING ===');
|
||||
console.log('Project ID:', projectId);
|
||||
|
||||
if (!projectId) {
|
||||
console.log('No project ID, returning empty result');
|
||||
return {
|
||||
defaultBranch: null,
|
||||
defaultBranchOid: null,
|
||||
currentBranch: null,
|
||||
currentBranchOid: null,
|
||||
fetchedAt: Date.now(),
|
||||
hasChanges: false,
|
||||
remoteUrl: null,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const cwd = `${projectsPath}/${projectId}`;
|
||||
console.log('Working directory:', cwd);
|
||||
|
||||
// Check if we're in a git repository
|
||||
try {
|
||||
await git.findRoot({ filepath: cwd });
|
||||
console.log('Git repository found');
|
||||
} catch {
|
||||
console.log('Not a git repository');
|
||||
return {
|
||||
defaultBranch: null,
|
||||
defaultBranchOid: null,
|
||||
currentBranch: null,
|
||||
currentBranchOid: null,
|
||||
fetchedAt: Date.now(),
|
||||
hasChanges: false,
|
||||
remoteUrl: null,
|
||||
};
|
||||
}
|
||||
|
||||
// Get remotes
|
||||
const remotes = await git.listRemotes({ dir: cwd });
|
||||
console.log('Remotes found:', remotes);
|
||||
|
||||
if (remotes.length === 0) {
|
||||
console.log('No remotes configured');
|
||||
return {
|
||||
defaultBranch: null,
|
||||
defaultBranchOid: null,
|
||||
currentBranch: null,
|
||||
currentBranchOid: null,
|
||||
fetchedAt: Date.now(),
|
||||
hasChanges: false,
|
||||
remoteUrl: null,
|
||||
};
|
||||
}
|
||||
|
||||
const remote = remotes[0]; // Use first remote (usually 'origin')
|
||||
const remoteUrl = remote.url || null;
|
||||
console.log('Using remote:', remote.remote, 'URL:', remoteUrl);
|
||||
|
||||
if (!remoteUrl) {
|
||||
console.log('No remote URL found');
|
||||
return {
|
||||
defaultBranch: null,
|
||||
defaultBranchOid: null,
|
||||
currentBranch: null,
|
||||
currentBranchOid: null,
|
||||
fetchedAt: Date.now(),
|
||||
hasChanges: false,
|
||||
remoteUrl: null,
|
||||
};
|
||||
}
|
||||
|
||||
// Get credentials for authentication
|
||||
const credentials = findCredentialsForRepo(remoteUrl, settings.credentials);
|
||||
console.log('Credentials found:', !!credentials);
|
||||
|
||||
// Get current branch before fetch
|
||||
let currentBranch: string | null = null;
|
||||
try {
|
||||
const branch = await git.currentBranch({
|
||||
dir: cwd,
|
||||
fullname: false,
|
||||
});
|
||||
currentBranch = (branch && branch.trim() !== '') ? branch : null;
|
||||
console.log('Current branch:', currentBranch);
|
||||
} catch (error) {
|
||||
console.warn('Could not get current branch:', error);
|
||||
}
|
||||
|
||||
// Store OIDs before fetch
|
||||
let beforeDefaultOid: string | null = null;
|
||||
let beforeCurrentOid: string | null = null;
|
||||
|
||||
// Get default branch from local symbolic ref
|
||||
let defaultBranch: string | null = null;
|
||||
try {
|
||||
console.log('Reading default branch from local symbolic ref...');
|
||||
|
||||
// Read the symbolic ref file directly
|
||||
// The file contains something like: "ref: refs/remotes/origin/main"
|
||||
try {
|
||||
const symbolicRefContent = await git.resolveRef({
|
||||
dir: cwd,
|
||||
ref: `remotes/${remote.remote}/HEAD`,
|
||||
depth: 1,
|
||||
});
|
||||
// Remove "ref: " prefix and extract the branch name
|
||||
// Content looks like: "ref: refs/remotes/origin/main"
|
||||
const refValue = symbolicRefContent.replace(/^ref:\s*/, '').trim();
|
||||
const match = refValue.match(/refs\/remotes\/[^/]+\/(.+)/);
|
||||
if (match) {
|
||||
defaultBranch = match[1].trim();
|
||||
console.log('Default branch from local symbolic ref:', defaultBranch);
|
||||
} else {
|
||||
console.log('Could not get default branch from local symbolic ref value:', refValue);
|
||||
}
|
||||
} catch {
|
||||
console.log('No local symbolic ref found, will be set after fetch');
|
||||
}
|
||||
|
||||
// If we have a default branch, try to get its OID before fetch
|
||||
if (defaultBranch) {
|
||||
try {
|
||||
beforeDefaultOid = await git.resolveRef({
|
||||
dir: cwd,
|
||||
ref: `${remote.remote}/${defaultBranch}`,
|
||||
});
|
||||
console.log('Default branch OID before fetch:', beforeDefaultOid);
|
||||
} catch {
|
||||
console.log('Remote default branch not in local repo yet');
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Could not read default branch from local data:', error);
|
||||
}
|
||||
|
||||
// Get current branch OID before fetch
|
||||
if (currentBranch) {
|
||||
try {
|
||||
beforeCurrentOid = await git.resolveRef({
|
||||
dir: cwd,
|
||||
ref: `${remote.remote}/${currentBranch}`,
|
||||
});
|
||||
console.log('Current branch OID before fetch:', beforeCurrentOid);
|
||||
} catch {
|
||||
console.log('Remote current branch not in local repo yet');
|
||||
}
|
||||
}
|
||||
|
||||
// Perform fetch
|
||||
try {
|
||||
console.log('Fetching from remote...');
|
||||
await git.fetch({
|
||||
dir: cwd,
|
||||
remote: remote.remote,
|
||||
...(credentials && {
|
||||
onAuth: () => ({
|
||||
username: credentials.username,
|
||||
password: credentials.password,
|
||||
}),
|
||||
}),
|
||||
});
|
||||
console.log('Fetch completed successfully');
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch from remote:', error);
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Get OIDs after fetch
|
||||
let afterDefaultOid: string | null = null;
|
||||
let afterCurrentOid: string | null = null;
|
||||
|
||||
// Re-read default branch from symbolic ref in case it was just created by fetch
|
||||
if (!defaultBranch) {
|
||||
try {
|
||||
const symbolicRefContent = await git.resolveRef({
|
||||
dir: cwd,
|
||||
ref: `remotes/${remote.remote}/HEAD`,
|
||||
depth: 1,
|
||||
});
|
||||
// Remove "ref: " prefix and extract the branch name
|
||||
// Content looks like: "ref: refs/remotes/origin/main"
|
||||
const refValue = symbolicRefContent.replace(/^ref:\s*/, '').trim();
|
||||
const match = refValue.match(/refs\/remotes\/[^/]+\/(.+)/);
|
||||
if (match) {
|
||||
defaultBranch = match[1].trim();
|
||||
console.log('Default branch from local symbolic ref:', defaultBranch);
|
||||
}
|
||||
} catch {
|
||||
console.log('No local symbolic ref found, will be set after fetch');
|
||||
}
|
||||
}
|
||||
|
||||
if (defaultBranch) {
|
||||
try {
|
||||
afterDefaultOid = await git.resolveRef({
|
||||
dir: cwd,
|
||||
ref: `${remote.remote}/${defaultBranch}`,
|
||||
});
|
||||
console.log('Default branch OID after fetch:', afterDefaultOid);
|
||||
} catch {
|
||||
console.log('Could not resolve default branch after fetch');
|
||||
}
|
||||
}
|
||||
|
||||
if (currentBranch) {
|
||||
try {
|
||||
afterCurrentOid = await git.resolveRef({
|
||||
dir: cwd,
|
||||
ref: `${remote.remote}/${currentBranch}`,
|
||||
});
|
||||
console.log('Current branch OID after fetch:', afterCurrentOid);
|
||||
} catch {
|
||||
console.log('Could not resolve current branch after fetch');
|
||||
}
|
||||
}
|
||||
|
||||
// Detect changes
|
||||
const defaultBranchChanged = beforeDefaultOid !== null &&
|
||||
afterDefaultOid !== null &&
|
||||
beforeDefaultOid !== afterDefaultOid;
|
||||
|
||||
const currentBranchChanged = beforeCurrentOid !== null &&
|
||||
afterCurrentOid !== null &&
|
||||
beforeCurrentOid !== afterCurrentOid &&
|
||||
currentBranch !== defaultBranch; // Don't double-report if they're the same
|
||||
|
||||
const hasChanges = defaultBranchChanged || currentBranchChanged;
|
||||
|
||||
console.log('Changes detected:', {
|
||||
defaultBranchChanged,
|
||||
currentBranchChanged,
|
||||
hasChanges,
|
||||
});
|
||||
|
||||
const result = {
|
||||
defaultBranch,
|
||||
defaultBranchOid: afterDefaultOid,
|
||||
currentBranch,
|
||||
currentBranchOid: afterCurrentOid,
|
||||
fetchedAt: Date.now(),
|
||||
hasChanges,
|
||||
remoteUrl,
|
||||
};
|
||||
|
||||
console.log('=== GIT FETCH COMPLETE ===');
|
||||
console.log('Result:', result);
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.error('Error fetching from remote:', error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
enabled: !!projectId,
|
||||
refetchInterval: 60000, // Fetch every 60 seconds
|
||||
staleTime: 30000, // Consider data stale after 30 seconds
|
||||
retry: 1, // Only retry once on failure
|
||||
});
|
||||
|
||||
// Show toast notifications when changes are detected
|
||||
useEffect(() => {
|
||||
if (!query.data || !query.isSuccess || query.dataUpdatedAt === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentState = {
|
||||
defaultBranchOid: query.data.defaultBranchOid,
|
||||
currentBranchOid: query.data.currentBranchOid,
|
||||
dataUpdatedAt: query.dataUpdatedAt,
|
||||
};
|
||||
|
||||
// Initialize on first load or after component remount
|
||||
if (previousStateRef.current === null) {
|
||||
previousStateRef.current = currentState;
|
||||
return;
|
||||
}
|
||||
|
||||
const prevState = previousStateRef.current;
|
||||
|
||||
// Skip if this is the same data we've already seen (same dataUpdatedAt timestamp)
|
||||
// This prevents showing toasts when navigating back to a project with cached data
|
||||
if (prevState.dataUpdatedAt === currentState.dataUpdatedAt) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Detect default branch changes
|
||||
const defaultBranchChanged =
|
||||
prevState.defaultBranchOid !== null &&
|
||||
currentState.defaultBranchOid !== null &&
|
||||
prevState.defaultBranchOid !== currentState.defaultBranchOid;
|
||||
|
||||
// Detect current branch changes
|
||||
const currentBranchChanged =
|
||||
prevState.currentBranchOid !== null &&
|
||||
currentState.currentBranchOid !== null &&
|
||||
prevState.currentBranchOid !== currentState.currentBranchOid &&
|
||||
query.data.currentBranch !== query.data.defaultBranch;
|
||||
|
||||
// Show toast for default branch changes
|
||||
if (defaultBranchChanged && query.data.defaultBranch) {
|
||||
toast({
|
||||
title: 'Remote changes detected',
|
||||
description: `The ${query.data.defaultBranch} branch has new commits available.`,
|
||||
variant: 'default',
|
||||
});
|
||||
|
||||
// Invalidate git status to show new ahead/behind counts
|
||||
queryClient.invalidateQueries({ queryKey: ['git-status', projectId] });
|
||||
}
|
||||
|
||||
// Show toast for current branch changes (if different from default)
|
||||
if (currentBranchChanged && query.data.currentBranch) {
|
||||
toast({
|
||||
title: 'Remote changes detected',
|
||||
description: `The ${query.data.currentBranch} branch has ${query.data.currentBranchOid === null ? 'been deleted' : 'new commits available'}.`,
|
||||
variant: 'default',
|
||||
});
|
||||
|
||||
// Invalidate git status to show new ahead/behind counts
|
||||
queryClient.invalidateQueries({ queryKey: ['git-status', projectId] });
|
||||
}
|
||||
|
||||
// Update previous state
|
||||
previousStateRef.current = currentState;
|
||||
}, [query.data, query.isSuccess, query.dataUpdatedAt, toast, queryClient, projectId]);
|
||||
|
||||
return query;
|
||||
}
|
||||
@@ -38,6 +38,7 @@ interface GitStatus {
|
||||
branches: string[];
|
||||
ahead: number;
|
||||
behind: number;
|
||||
remoteBranchExists: boolean;
|
||||
}
|
||||
|
||||
export function useGitStatus(projectId: string | null) {
|
||||
@@ -59,6 +60,7 @@ export function useGitStatus(projectId: string | null) {
|
||||
branches: [],
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
remoteBranchExists: false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -80,6 +82,7 @@ export function useGitStatus(projectId: string | null) {
|
||||
branches: [],
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
remoteBranchExists: false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -200,6 +203,7 @@ export function useGitStatus(projectId: string | null) {
|
||||
// Calculate ahead/behind
|
||||
let ahead = 0;
|
||||
let behind = 0;
|
||||
let remoteBranchExists = false;
|
||||
try {
|
||||
if (currentBranch && remotes.length > 0) {
|
||||
const remote = remotes[0]; // Use first remote (usually 'origin')
|
||||
@@ -224,6 +228,9 @@ export function useGitStatus(projectId: string | null) {
|
||||
ref: currentBranch,
|
||||
});
|
||||
|
||||
// Remote branch exists!
|
||||
remoteBranchExists = true;
|
||||
|
||||
if (remoteRef && localRef && remoteRef !== localRef) {
|
||||
// Get commits between local and remote
|
||||
const localCommits = await git.log({
|
||||
@@ -247,11 +254,8 @@ export function useGitStatus(projectId: string | null) {
|
||||
behind = remoteOnlyCommits.length;
|
||||
}
|
||||
} catch {
|
||||
// Remote branch might not exist or other issues
|
||||
// If we can't find remote branch, assume we're ahead if we have commits
|
||||
if (totalCommits > 0) {
|
||||
ahead = totalCommits;
|
||||
}
|
||||
// Remote branch doesn't exist
|
||||
remoteBranchExists = false;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
@@ -269,6 +273,7 @@ export function useGitStatus(projectId: string | null) {
|
||||
branches,
|
||||
ahead,
|
||||
behind,
|
||||
remoteBranchExists,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error checking git status:', error);
|
||||
@@ -283,6 +288,7 @@ export function useGitStatus(projectId: string | null) {
|
||||
branches: [],
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
remoteBranchExists: false,
|
||||
};
|
||||
}
|
||||
},
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { generateLabelId, type Label, type LabelColorName } from '@/lib/labels';
|
||||
|
||||
/**
|
||||
* Hook for managing labels (creating, editing, deleting labels)
|
||||
*/
|
||||
export function useLabels() {
|
||||
const [labels, setLabels] = useLocalStorage<Label[]>('project-labels', []);
|
||||
|
||||
const createLabel = (name: string, color: LabelColorName): Label => {
|
||||
const newLabel: Label = {
|
||||
id: generateLabelId(),
|
||||
name,
|
||||
color,
|
||||
};
|
||||
setLabels([...labels, newLabel]);
|
||||
return newLabel;
|
||||
};
|
||||
|
||||
const updateLabel = (labelId: string, updates: Partial<Omit<Label, 'id'>>) => {
|
||||
setLabels(labels.map(label =>
|
||||
label.id === labelId ? { ...label, ...updates } : label
|
||||
));
|
||||
};
|
||||
|
||||
const deleteLabel = (labelId: string) => {
|
||||
setLabels(labels.filter(label => label.id !== labelId));
|
||||
};
|
||||
|
||||
const reorderLabels = (orderedIds: string[]) => {
|
||||
const reordered = orderedIds
|
||||
.map(id => labels.find(label => label.id === id))
|
||||
.filter((label): label is Label => label !== undefined);
|
||||
setLabels(reordered);
|
||||
};
|
||||
|
||||
const toggleLabelCollapsed = (labelId: string) => {
|
||||
setLabels(labels.map(label =>
|
||||
label.id === labelId ? { ...label, collapsed: !label.collapsed } : label
|
||||
));
|
||||
};
|
||||
|
||||
return {
|
||||
labels,
|
||||
createLabel,
|
||||
updateLabel,
|
||||
deleteLabel,
|
||||
reorderLabels,
|
||||
toggleLabelCollapsed,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { MCPClient } from '@/lib/MCPClient';
|
||||
import type { MCPServer } from '@/contexts/AISettingsContext';
|
||||
|
||||
/**
|
||||
* Hook to check the connection status of an MCP server.
|
||||
* Returns 'connected', 'offline', or 'checking'.
|
||||
*/
|
||||
export function useMCPServerStatus(server: MCPServer): 'connected' | 'offline' | 'checking' {
|
||||
const [status, setStatus] = useState<'connected' | 'offline' | 'checking'>('checking');
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
async function checkConnection() {
|
||||
setStatus('checking');
|
||||
|
||||
try {
|
||||
const client = new MCPClient(server);
|
||||
await client.connect();
|
||||
|
||||
// Try to list tools to verify the connection is working
|
||||
await client.listTools();
|
||||
|
||||
await client.close();
|
||||
|
||||
if (!cancelled) {
|
||||
setStatus('connected');
|
||||
}
|
||||
} catch {
|
||||
if (!cancelled) {
|
||||
setStatus('offline');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
checkConnection();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [server]); // Re-check when server config changes
|
||||
|
||||
return status;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useAISettings } from './useAISettings';
|
||||
import { discoverMCPTools } from '@/lib/MCPClient';
|
||||
import type OpenAI from 'openai';
|
||||
import type { MCPClient } from '@/lib/MCPClient';
|
||||
|
||||
interface UseMCPToolsResult {
|
||||
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
|
||||
clients: Record<string, MCPClient>;
|
||||
isLoading: boolean;
|
||||
error: Error | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to discover and manage MCP tools from configured servers.
|
||||
*/
|
||||
export function useMCPTools(): UseMCPToolsResult {
|
||||
const { settings } = useAISettings();
|
||||
const mcpServers = settings.mcpServers || {};
|
||||
|
||||
const { data, isLoading, error } = useQuery({
|
||||
queryKey: ['mcp-tools', mcpServers],
|
||||
queryFn: async () => {
|
||||
if (Object.keys(mcpServers).length === 0) {
|
||||
return { tools: {}, clients: {} };
|
||||
}
|
||||
return await discoverMCPTools(mcpServers);
|
||||
},
|
||||
staleTime: 5 * 60 * 1000, // Cache for 5 minutes
|
||||
retry: 1,
|
||||
});
|
||||
|
||||
return {
|
||||
tools: data?.tools || {},
|
||||
clients: data?.clients || {},
|
||||
isLoading,
|
||||
error: error as Error | null,
|
||||
};
|
||||
}
|
||||
Loaded 100 of 242 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user