mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-04 08:13:34 +00:00
Compare commits
99
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 | ||
|
|
18d088660f | ||
|
|
7e7ef35ff6 | ||
|
|
63d23f5510 |
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
|
||||
@@ -241,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`
|
||||
|
||||
+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', {
|
||||
|
||||
Generated
+33
-11
@@ -196,6 +196,7 @@
|
||||
"integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/code-frame": "^7.27.1",
|
||||
"@babel/generator": "^7.28.5",
|
||||
@@ -1831,6 +1832,7 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
@@ -1854,6 +1856,7 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
@@ -1875,6 +1878,7 @@
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz",
|
||||
"integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@dnd-kit/accessibility": "^3.1.1",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
@@ -5459,8 +5463,7 @@
|
||||
"resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz",
|
||||
"integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/cacheable-request": {
|
||||
"version": "6.0.3",
|
||||
@@ -5702,6 +5705,7 @@
|
||||
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.20.tgz",
|
||||
"integrity": "sha512-IPaCZN7PShZK/3t6Q87pfTkRm6oLTd4vztyoj+cbHUF1g3FfVb2tFIL79uCRKEfv16AhqDMBywP2VW3KIZUvcg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/prop-types": "*",
|
||||
"csstype": "^3.0.2"
|
||||
@@ -5713,6 +5717,7 @@
|
||||
"integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"peerDependencies": {
|
||||
"@types/react": "^18.0.0"
|
||||
}
|
||||
@@ -5817,6 +5822,7 @@
|
||||
"integrity": "sha512-oU/OtYVydhXnumd0BobL9rkJg7wFJ9bFFPmSmB/bf/XWN85hlViji59ko6bSKBXyseT9V8l+CN1nwmlbiN0G7Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@typescript-eslint/scope-manager": "8.31.1",
|
||||
"@typescript-eslint/types": "8.31.1",
|
||||
@@ -6176,6 +6182,7 @@
|
||||
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
|
||||
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"acorn": "bin/acorn"
|
||||
},
|
||||
@@ -6679,6 +6686,7 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"baseline-browser-mapping": "^2.8.19",
|
||||
"caniuse-lite": "^1.0.30001751",
|
||||
@@ -6947,6 +6955,7 @@
|
||||
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
|
||||
"integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"anymatch": "~3.1.2",
|
||||
"braces": "~3.0.2",
|
||||
@@ -7747,8 +7756,7 @@
|
||||
"resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz",
|
||||
"integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/dom-helpers": {
|
||||
"version": "5.2.1",
|
||||
@@ -7832,7 +7840,8 @@
|
||||
"version": "8.6.0",
|
||||
"resolved": "https://registry.npmjs.org/embla-carousel/-/embla-carousel-8.6.0.tgz",
|
||||
"integrity": "sha512-SjWyZBHJPbqxHOzckOfo8lHisEaJWmwd23XppYFYVh10bU66/Pn5tkVkbkCMZVdbUE5eTCI2nD8OyIP4Z+uwkA==",
|
||||
"license": "MIT"
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/embla-carousel-react": {
|
||||
"version": "8.6.0",
|
||||
@@ -8146,6 +8155,7 @@
|
||||
"integrity": "sha512-QldCVh/ztyKJJZLr4jXNUByx3gR+TDYZCRXEktiZoUR3PGy4qCmSbkxcIle8GEwGpb5JBZazlaJ/CxLidXdEbQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@eslint-community/eslint-utils": "^4.2.0",
|
||||
"@eslint-community/regexpp": "^4.12.1",
|
||||
@@ -8411,6 +8421,7 @@
|
||||
"resolved": "https://registry.npmjs.org/express/-/express-5.1.0.tgz",
|
||||
"integrity": "sha512-DT9ck5YIRU+8GYzzU5kT3eHGA5iL+1Zd0EutOmTE9Dtk+Tvuzd23VBU+ec7HPNSTxXYO55gPV/hq4pSBJDjFpA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"accepts": "^2.0.0",
|
||||
"body-parser": "^2.2.0",
|
||||
@@ -9633,6 +9644,7 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.27.6"
|
||||
},
|
||||
@@ -10416,6 +10428,7 @@
|
||||
"integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"cssstyle": "^4.2.1",
|
||||
"data-urls": "^5.0.0",
|
||||
@@ -10812,7 +10825,6 @@
|
||||
"integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"lz-string": "bin/bin.js"
|
||||
}
|
||||
@@ -12610,6 +12622,7 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"nanoid": "^3.3.8",
|
||||
"picocolors": "^1.1.1",
|
||||
@@ -12777,7 +12790,6 @@
|
||||
"integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"ansi-regex": "^5.0.1",
|
||||
"ansi-styles": "^5.0.0",
|
||||
@@ -12793,7 +12805,6 @@
|
||||
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
@@ -12804,7 +12815,6 @@
|
||||
"integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
@@ -12817,8 +12827,7 @@
|
||||
"resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
|
||||
"integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/prismjs": {
|
||||
"version": "1.30.0",
|
||||
@@ -13026,6 +13035,7 @@
|
||||
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
|
||||
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.1.0"
|
||||
},
|
||||
@@ -13052,6 +13062,7 @@
|
||||
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
|
||||
"integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.1.0",
|
||||
"scheduler": "^0.23.2"
|
||||
@@ -13077,6 +13088,7 @@
|
||||
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.56.1.tgz",
|
||||
"integrity": "sha512-qWAVokhSpshhcEuQDSANHx3jiAEFzu2HAaaQIzi/r9FNPm1ioAvuJSD4EuZzWd7Al7nTRKcKPnBKO7sRn+zavQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
},
|
||||
@@ -13125,6 +13137,7 @@
|
||||
"resolved": "https://registry.npmjs.org/react-markdown/-/react-markdown-10.1.0.tgz",
|
||||
"integrity": "sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/hast": "^3.0.0",
|
||||
"@types/mdast": "^4.0.0",
|
||||
@@ -13706,6 +13719,7 @@
|
||||
"integrity": "sha512-C5VvvgCCyfyotVITIAv+4efVytl5F7wt+/I2i9q9GZcEXW9BP52YYOXC58igUi+LFZVHukErIIqQSWwv/M3WRw==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/estree": "1.0.7"
|
||||
},
|
||||
@@ -14820,6 +14834,7 @@
|
||||
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.17.tgz",
|
||||
"integrity": "sha512-w33E2aCvSDP0tW9RZuNXadXlkHXqFzSkQew/aIa2i/Sj8fThxwovwlXHSPXTbAHwEIhBFXAedUhP2tueAKP8Og==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@alloc/quick-lru": "^5.2.0",
|
||||
"arg": "^5.0.2",
|
||||
@@ -15023,6 +15038,7 @@
|
||||
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
@@ -15318,6 +15334,7 @@
|
||||
"integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
|
||||
"devOptional": true,
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
@@ -15845,6 +15862,7 @@
|
||||
"integrity": "sha512-cZn6NDFE7wdTpINgs++ZJ4N49W2vRp8LCKrn3Ob1kYNtOo21vfDoaV5GzBfLU4MovSAB8uNRm4jgzVQZ+mBzPQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"esbuild": "^0.25.0",
|
||||
"fdir": "^6.4.4",
|
||||
@@ -15989,6 +16007,7 @@
|
||||
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
@@ -16459,6 +16478,7 @@
|
||||
"integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
@@ -16535,6 +16555,7 @@
|
||||
"integrity": "sha512-fS6iqSPZDs3dr/y7Od6y5nha8dW1YnbgtsyotCVvoFGKbERG++CVRFv1meyGDE1SNItQA8BrnCw7ScdAhRJ3XQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"rollup": "dist/bin/rollup"
|
||||
},
|
||||
@@ -16994,6 +17015,7 @@
|
||||
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
|
||||
"integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/colinhacks"
|
||||
}
|
||||
|
||||
+23
-5
@@ -146,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,14 +1,14 @@
|
||||
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';
|
||||
import { Dialog, DialogPortal, DialogOverlay } from '@/components/ui/dialog';
|
||||
import * as DialogPrimitive from '@radix-ui/react-dialog';
|
||||
|
||||
// Type guard to check if message has reasoning content
|
||||
function hasReasoningContent(message: AIMessage): message is AIMessage & { reasoning_content: string } {
|
||||
@@ -26,7 +26,6 @@ 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();
|
||||
@@ -50,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') {
|
||||
@@ -217,81 +65,13 @@ 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}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -355,32 +135,11 @@ export const AIMessageItem = memo(({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Image expansion dialog */}
|
||||
<Dialog open={!!expandedImageUrl} onOpenChange={(open) => !open && setExpandedImageUrl(null)}>
|
||||
<DialogPortal>
|
||||
<DialogOverlay className="bg-black/95" />
|
||||
<DialogPrimitive.Content
|
||||
className={cn(
|
||||
"fixed left-[50%] top-[50%] z-50 max-w-[95vw] max-h-[95vh] translate-x-[-50%] translate-y-[-50%] p-0 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"
|
||||
)}
|
||||
onPointerDownOutside={() => setExpandedImageUrl(null)}
|
||||
onEscapeKeyDown={() => setExpandedImageUrl(null)}
|
||||
>
|
||||
{expandedImageUrl && (
|
||||
<div className="relative flex items-center justify-center">
|
||||
<img
|
||||
src={expandedImageUrl}
|
||||
alt="Expanded image"
|
||||
className="max-w-full max-h-[95vh] w-auto h-auto object-contain rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
</Dialog>
|
||||
{/* Image expansion lightbox */}
|
||||
<ImageLightbox
|
||||
imageUrl={expandedImageUrl}
|
||||
onClose={() => setExpandedImageUrl(null)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -395,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">
|
||||
@@ -453,6 +212,18 @@ export const AIMessageItem = memo(({
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{assistantContent}
|
||||
|
||||
{/* Image expansion lightbox */}
|
||||
<ImageLightbox
|
||||
imageUrl={expandedImageUrl}
|
||||
onClose={() => setExpandedImageUrl(null)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
AIMessageItem.displayName = 'AIMessageItem';
|
||||
@@ -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}
|
||||
/>
|
||||
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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;
|
||||
@@ -49,6 +50,7 @@ const AppConfigSchema = z.object({
|
||||
fsPathTemplates: z.string().min(1),
|
||||
sentryDsn: z.string(),
|
||||
sentryEnabled: z.boolean(),
|
||||
systemPrompt: z.string(),
|
||||
}) satisfies z.ZodType<AppConfig>;
|
||||
|
||||
export function AppProvider(props: AppProviderProps) {
|
||||
@@ -155,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);
|
||||
}
|
||||
@@ -307,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,
|
||||
},
|
||||
@@ -314,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,
|
||||
},
|
||||
@@ -321,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,
|
||||
},
|
||||
@@ -328,6 +331,7 @@ 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,
|
||||
@@ -336,6 +340,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
} else if (selectedProvider.type === 'cloudflare') {
|
||||
await updateProjectSettings(selectedProviderId, {
|
||||
type: 'cloudflare',
|
||||
url: result.url,
|
||||
data: {
|
||||
projectName: cloudflareForm.projectName || undefined,
|
||||
},
|
||||
@@ -343,6 +348,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
} else if (selectedProvider.type === 'deno') {
|
||||
await updateProjectSettings(selectedProviderId, {
|
||||
type: 'deno',
|
||||
url: result.url,
|
||||
data: {
|
||||
projectName: denoDeployForm.projectName || undefined,
|
||||
},
|
||||
@@ -404,11 +410,14 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
|
||||
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}
|
||||
/>
|
||||
@@ -594,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 && (
|
||||
|
||||
@@ -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
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -488,6 +488,9 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
|
||||
console.log('Set nostr.repo config to:', result.naddr);
|
||||
|
||||
// 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();
|
||||
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -45,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]);
|
||||
@@ -56,12 +61,36 @@ export const ModelSelector = memo(function ModelSelector({
|
||||
// Create a Set of recently used model IDs for efficient lookup
|
||||
const recentlyUsedSet = useMemo(() => new Set(recentlyUsedModels), [recentlyUsedModels]);
|
||||
|
||||
// Determine if we should show the "Recently Used" section
|
||||
const shouldShowRecentlyUsed = useMemo(() => {
|
||||
// If no recently used models, don't show the section
|
||||
if (recentlyUsedModels.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// If there are 5 or more total provider models, always show recently used
|
||||
if (models.length >= 5) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// If less than 5 total provider models, check if all recently used models
|
||||
// are contained within the available provider models
|
||||
const availableModelIds = new Set(models.map(model => model.fullId));
|
||||
const allRecentlyUsedAreAvailable = recentlyUsedModels.every(model =>
|
||||
availableModelIds.has(model)
|
||||
);
|
||||
|
||||
// Hide recently used section if all recently used models are already available
|
||||
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) {
|
||||
// Skip models that are already shown in recently used
|
||||
if (recentlyUsedSet.has(model.fullId)) {
|
||||
// Only skip models that are in recently used if we're showing the recently used section
|
||||
if (shouldShowRecentlyUsed && recentlyUsedSet.has(model.fullId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -71,7 +100,7 @@ export const ModelSelector = memo(function ModelSelector({
|
||||
groups[model.provider].push(model);
|
||||
}
|
||||
return groups;
|
||||
}, [models, recentlyUsedSet]);
|
||||
}, [models, recentlyUsedSet, shouldShowRecentlyUsed]);
|
||||
|
||||
// Get provider display name and baseURL for a given provider ID
|
||||
const getProviderInfo = useMemo(() => {
|
||||
@@ -100,29 +129,6 @@ export const ModelSelector = memo(function ModelSelector({
|
||||
};
|
||||
}, [value, getProviderInfo, models]);
|
||||
|
||||
// Determine if we should show the "Recently Used" section
|
||||
const shouldShowRecentlyUsed = useMemo(() => {
|
||||
// If no recently used models, don't show the section
|
||||
if (recentlyUsedModels.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// If there are 5 or more total provider models, always show recently used
|
||||
if (models.length >= 5) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// If less than 5 total provider models, check if all recently used models
|
||||
// are contained within the available provider models
|
||||
const availableModelIds = new Set(models.map(model => model.fullId));
|
||||
const allRecentlyUsedAreAvailable = recentlyUsedModels.every(model =>
|
||||
availableModelIds.has(model)
|
||||
);
|
||||
|
||||
// Hide recently used section if all recently used models are already available
|
||||
return !allRecentlyUsedAreAvailable;
|
||||
}, [recentlyUsedModels, models]);
|
||||
|
||||
// Check if the current model is free
|
||||
const isCurrentModelFree = useMemo(() => {
|
||||
if (!value) return false;
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -66,8 +66,13 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
);
|
||||
|
||||
// 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
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
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';
|
||||
@@ -8,12 +8,14 @@ import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/
|
||||
import { usePlugins } from '@/hooks/usePlugins';
|
||||
import { usePluginGitInfo } from '@/hooks/usePluginGitInfo';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { DiscoverPluginsDialog } from '@/components/DiscoverPluginsDialog';
|
||||
|
||||
export function PluginsSection() {
|
||||
const { t } = useTranslation();
|
||||
const { toast } = useToast();
|
||||
const { plugins, skills, clonePlugin, syncPlugin, deletePlugin } = usePlugins();
|
||||
const [gitUrl, setGitUrl] = useState('');
|
||||
const [showDiscoverDialog, setShowDiscoverDialog] = useState(false);
|
||||
|
||||
const handleAddPlugin = async () => {
|
||||
if (!gitUrl.trim()) return;
|
||||
@@ -79,9 +81,20 @@ export function PluginsSection() {
|
||||
<div className="space-y-4">
|
||||
{/* 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')}
|
||||
@@ -160,6 +173,12 @@ export function PluginsSection() {
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
|
||||
{/* Discover Plugins Dialog */}
|
||||
<DiscoverPluginsDialog
|
||||
open={showDiscoverDialog}
|
||||
onOpenChange={setShowDiscoverDialog}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -40,6 +40,7 @@ import {
|
||||
import JSZip from 'jszip';
|
||||
import { Separator } from './ui/separator';
|
||||
import { DotAI } from '@/lib/DotAI';
|
||||
import { LabelSelector } from '@/components/labels/LabelSelector';
|
||||
|
||||
interface ProjectDetailsDialogProps {
|
||||
project: Project;
|
||||
@@ -244,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>
|
||||
@@ -262,7 +263,7 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
|
||||
<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(6)}</span>
|
||||
<span className="font-mono">${totalCost.toFixed(2)}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -317,6 +318,9 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Labels */}
|
||||
<LabelSelector projectId={project.id} />
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Export Project Button */}
|
||||
|
||||
@@ -1,28 +1,40 @@
|
||||
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, Search } 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);
|
||||
|
||||
@@ -31,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(
|
||||
@@ -48,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">
|
||||
@@ -60,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>
|
||||
@@ -75,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;
|
||||
@@ -95,10 +186,17 @@ export function ProjectSidebar({
|
||||
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()) {
|
||||
@@ -112,6 +210,69 @@ export function ProjectSidebar({
|
||||
);
|
||||
}, [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);
|
||||
@@ -206,6 +367,13 @@ 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>
|
||||
@@ -249,7 +417,84 @@ export function ProjectSidebar({
|
||||
<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">
|
||||
{/* 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
|
||||
@@ -258,6 +503,7 @@ export function ProjectSidebar({
|
||||
isSelected={selectedProject?.id === project.id}
|
||||
onSelect={onSelectProject}
|
||||
isFavorite={favorites.includes(project.id)}
|
||||
labelColor={getProjectLabelColor(project.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -288,6 +534,12 @@ export function ProjectSidebar({
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Labels Management Dialog */}
|
||||
<LabelsManageDialog
|
||||
open={labelsDialogOpen}
|
||||
onOpenChange={setLabelsDialogOpen}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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';
|
||||
@@ -12,6 +12,7 @@ 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;
|
||||
@@ -43,6 +44,7 @@ interface QuillyContentProps {
|
||||
|
||||
function QuillyContent({ error, onDismiss, onNewChat, onOpenModelSelector, onTryAgain, onRequestConsoleErrorHelp, provider }: QuillyContentProps) {
|
||||
const navigate = useNavigate();
|
||||
const { isOffline } = useOffline();
|
||||
|
||||
const renderBody = (error: Error | APIError | MalformedToolCallError | ProjectPreviewConsoleError): ErrorBody & { showCreditsButton?: boolean } => {
|
||||
// Handle Project Preview Console Errors
|
||||
@@ -183,15 +185,24 @@ function QuillyContent({ 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
|
||||
|
||||
@@ -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';
|
||||
@@ -16,6 +16,7 @@ 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';
|
||||
@@ -33,9 +34,11 @@ 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';
|
||||
@@ -47,6 +50,8 @@ 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
|
||||
|
||||
@@ -98,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] || '';
|
||||
@@ -166,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(),
|
||||
@@ -185,8 +190,56 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
tools.deploy_project = new DeployProjectTool(fs, cwd, user.signer, projectId);
|
||||
}
|
||||
|
||||
// Add generate_image tool if imageModel is configured
|
||||
if (settings.imageModel) {
|
||||
try {
|
||||
const { provider, model } = parseProviderModel(settings.imageModel, settings.providers);
|
||||
|
||||
// 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, handleFileChanged]);
|
||||
}, [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]);
|
||||
@@ -321,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,
|
||||
});
|
||||
|
||||
@@ -546,6 +601,87 @@ 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">
|
||||
|
||||
@@ -617,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 && (
|
||||
|
||||
@@ -708,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">
|
||||
|
||||
@@ -145,8 +145,8 @@ export function Terminal({ cwd, 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { AlertCircle } from 'lucide-react';
|
||||
interface ShakespeareDeployFormProps {
|
||||
host?: string;
|
||||
projectId: string;
|
||||
savedSubdomain?: string;
|
||||
onSubdomainChange: (subdomain: string) => void;
|
||||
onValidationChange?: (isValid: boolean) => void;
|
||||
}
|
||||
@@ -13,10 +14,16 @@ interface ShakespeareDeployFormProps {
|
||||
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('.');
|
||||
|
||||
@@ -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';
|
||||
@@ -22,6 +22,7 @@ export interface MCPServers {
|
||||
export interface AISettings {
|
||||
providers: AIProvider[];
|
||||
recentlyUsedModels: string[];
|
||||
imageModel?: string;
|
||||
mcpServers?: MCPServers;
|
||||
}
|
||||
|
||||
|
||||
@@ -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]);
|
||||
|
||||
@@ -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
|
||||
});
|
||||
}
|
||||
@@ -34,6 +34,7 @@ export function useGitFetch(projectId: string | null) {
|
||||
const previousStateRef = useRef<{
|
||||
defaultBranchOid: string | null;
|
||||
currentBranchOid: string | null;
|
||||
dataUpdatedAt: number;
|
||||
} | null>(null);
|
||||
|
||||
const query = useQuery({
|
||||
@@ -300,16 +301,17 @@ export function useGitFetch(projectId: string | null) {
|
||||
|
||||
// Show toast notifications when changes are detected
|
||||
useEffect(() => {
|
||||
if (!query.data || !query.isSuccess) {
|
||||
if (!query.data || !query.isSuccess || query.dataUpdatedAt === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentState = {
|
||||
defaultBranchOid: query.data.defaultBranchOid,
|
||||
currentBranchOid: query.data.currentBranchOid,
|
||||
dataUpdatedAt: query.dataUpdatedAt,
|
||||
};
|
||||
|
||||
// Skip on first load
|
||||
// Initialize on first load or after component remount
|
||||
if (previousStateRef.current === null) {
|
||||
previousStateRef.current = currentState;
|
||||
return;
|
||||
@@ -317,6 +319,12 @@ export function useGitFetch(projectId: string | null) {
|
||||
|
||||
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 &&
|
||||
@@ -356,7 +364,7 @@ export function useGitFetch(projectId: string | null) {
|
||||
|
||||
// Update previous state
|
||||
previousStateRef.current = currentState;
|
||||
}, [query.data, query.isSuccess, toast, queryClient, projectId]);
|
||||
}, [query.data, query.isSuccess, query.dataUpdatedAt, toast, queryClient, projectId]);
|
||||
|
||||
return query;
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -1,56 +1,79 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { z } from 'zod';
|
||||
import { useFS } from './useFS';
|
||||
import { useFSPaths } from './useFSPaths';
|
||||
|
||||
export interface ShakespeareProjectConfig {
|
||||
type: 'shakespeare';
|
||||
data: {
|
||||
subdomain?: string;
|
||||
};
|
||||
}
|
||||
const shakespeareProjectConfigSchema = z.object({
|
||||
type: z.literal('shakespeare'),
|
||||
url: z.string(),
|
||||
data: z.object({
|
||||
subdomain: z.string().optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
export interface NsiteProjectConfig {
|
||||
type: 'nsite';
|
||||
data: {
|
||||
nsec: string;
|
||||
};
|
||||
}
|
||||
const nsiteProjectConfigSchema = z.object({
|
||||
type: z.literal('nsite'),
|
||||
url: z.string(),
|
||||
data: z.object({
|
||||
nsec: z.string(),
|
||||
}),
|
||||
});
|
||||
|
||||
export interface NetlifyProjectConfig {
|
||||
type: 'netlify';
|
||||
data: {
|
||||
siteId?: string;
|
||||
};
|
||||
}
|
||||
const netlifyProjectConfigSchema = z.object({
|
||||
type: z.literal('netlify'),
|
||||
url: z.string(),
|
||||
data: z.object({
|
||||
siteId: z.string().optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
export interface VercelProjectConfig {
|
||||
type: 'vercel';
|
||||
data: {
|
||||
teamId?: string;
|
||||
projectId?: string;
|
||||
};
|
||||
}
|
||||
const vercelProjectConfigSchema = z.object({
|
||||
type: z.literal('vercel'),
|
||||
url: z.string(),
|
||||
data: z.object({
|
||||
teamId: z.string().optional(),
|
||||
projectId: z.string().optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
export interface CloudflareProjectConfig {
|
||||
type: 'cloudflare';
|
||||
data: {
|
||||
projectName?: string;
|
||||
};
|
||||
}
|
||||
const cloudflareProjectConfigSchema = z.object({
|
||||
type: z.literal('cloudflare'),
|
||||
url: z.string(),
|
||||
data: z.object({
|
||||
projectName: z.string().optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
export interface DenoDeployProjectConfig {
|
||||
type: 'deno';
|
||||
data: {
|
||||
projectName?: string;
|
||||
};
|
||||
}
|
||||
const denoDeployProjectConfigSchema = z.object({
|
||||
type: z.literal('deno'),
|
||||
url: z.string(),
|
||||
data: z.object({
|
||||
projectName: z.string().optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
export type ProjectProviderConfig = ShakespeareProjectConfig | NsiteProjectConfig | NetlifyProjectConfig | VercelProjectConfig | CloudflareProjectConfig | DenoDeployProjectConfig;
|
||||
const projectProviderConfigSchema = z.discriminatedUnion('type', [
|
||||
shakespeareProjectConfigSchema,
|
||||
nsiteProjectConfigSchema,
|
||||
netlifyProjectConfigSchema,
|
||||
vercelProjectConfigSchema,
|
||||
cloudflareProjectConfigSchema,
|
||||
denoDeployProjectConfigSchema,
|
||||
]);
|
||||
|
||||
export interface ProjectDeploySettings {
|
||||
providers: Record<string, ProjectProviderConfig>;
|
||||
currentProvider?: string;
|
||||
}
|
||||
const projectDeploySettingsSchema = z.object({
|
||||
providers: z.record(z.string(), projectProviderConfigSchema),
|
||||
currentProvider: z.string().optional(),
|
||||
});
|
||||
|
||||
export type ShakespeareProjectConfig = z.infer<typeof shakespeareProjectConfigSchema>;
|
||||
export type NsiteProjectConfig = z.infer<typeof nsiteProjectConfigSchema>;
|
||||
export type NetlifyProjectConfig = z.infer<typeof netlifyProjectConfigSchema>;
|
||||
export type VercelProjectConfig = z.infer<typeof vercelProjectConfigSchema>;
|
||||
export type CloudflareProjectConfig = z.infer<typeof cloudflareProjectConfigSchema>;
|
||||
export type DenoDeployProjectConfig = z.infer<typeof denoDeployProjectConfigSchema>;
|
||||
export type ProjectProviderConfig = z.infer<typeof projectProviderConfigSchema>;
|
||||
export type ProjectDeploySettings = z.infer<typeof projectDeploySettingsSchema>;
|
||||
|
||||
/**
|
||||
* Hook to manage project-specific deployment settings
|
||||
@@ -77,17 +100,14 @@ export function useProjectDeploySettings(projectId: string | null) {
|
||||
const content = await fs.fs.readFile(settingsPath, 'utf8');
|
||||
const parsed = JSON.parse(content as string);
|
||||
|
||||
// Handle migration from old format (flat Record) to new format (with providers key)
|
||||
if (parsed && typeof parsed === 'object' && !('providers' in parsed)) {
|
||||
// Old format: Record<string, ProjectProviderConfig>
|
||||
// Migrate to new format
|
||||
setSettings({ providers: parsed });
|
||||
} else {
|
||||
// New format or empty
|
||||
setSettings(parsed || { providers: {} });
|
||||
// Validate with Zod
|
||||
const validated = projectDeploySettingsSchema.parse(parsed);
|
||||
setSettings(validated);
|
||||
} catch (error) {
|
||||
// File doesn't exist, is invalid JSON, or doesn't match schema - use empty settings
|
||||
if (error instanceof Error && !error.message.includes('ENOENT')) {
|
||||
console.warn('Failed to load or validate deploy settings:', error);
|
||||
}
|
||||
} catch {
|
||||
// File doesn't exist or is invalid, use empty settings
|
||||
setSettings({ providers: {} });
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
|
||||
/** Map of project IDs to their assigned label IDs */
|
||||
type ProjectLabelsMap = Record<string, string[]>;
|
||||
|
||||
/**
|
||||
* Hook for managing project-label associations
|
||||
*/
|
||||
export function useProjectLabels() {
|
||||
const [projectLabels, setProjectLabels] = useLocalStorage<ProjectLabelsMap>('project-label-assignments', {});
|
||||
|
||||
const getProjectLabels = (projectId: string): string[] => {
|
||||
return projectLabels[projectId] || [];
|
||||
};
|
||||
|
||||
const addLabelToProject = (projectId: string, labelId: string) => {
|
||||
const currentLabels = projectLabels[projectId] || [];
|
||||
if (!currentLabels.includes(labelId)) {
|
||||
setProjectLabels({
|
||||
...projectLabels,
|
||||
[projectId]: [...currentLabels, labelId],
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const removeLabelFromProject = (projectId: string, labelId: string) => {
|
||||
const currentLabels = projectLabels[projectId] || [];
|
||||
const newLabels = currentLabels.filter(id => id !== labelId);
|
||||
if (newLabels.length === 0) {
|
||||
const { [projectId]: _, ...rest } = projectLabels;
|
||||
setProjectLabels(rest);
|
||||
} else {
|
||||
setProjectLabels({
|
||||
...projectLabels,
|
||||
[projectId]: newLabels,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const setProjectLabelsList = (projectId: string, labelIds: string[]) => {
|
||||
if (labelIds.length === 0) {
|
||||
const { [projectId]: _, ...rest } = projectLabels;
|
||||
setProjectLabels(rest);
|
||||
} else {
|
||||
setProjectLabels({
|
||||
...projectLabels,
|
||||
[projectId]: labelIds,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const getProjectsByLabel = (labelId: string): string[] => {
|
||||
return Object.entries(projectLabels)
|
||||
.filter(([_, labels]) => labels.includes(labelId))
|
||||
.map(([projectId]) => projectId);
|
||||
};
|
||||
|
||||
const hasAnyLabels = (): boolean => {
|
||||
return Object.keys(projectLabels).length > 0;
|
||||
};
|
||||
|
||||
const removeLabel = (labelId: string) => {
|
||||
const newProjectLabels: ProjectLabelsMap = {};
|
||||
for (const [projectId, labels] of Object.entries(projectLabels)) {
|
||||
const filtered = labels.filter(id => id !== labelId);
|
||||
if (filtered.length > 0) {
|
||||
newProjectLabels[projectId] = filtered;
|
||||
}
|
||||
}
|
||||
setProjectLabels(newProjectLabels);
|
||||
};
|
||||
|
||||
return {
|
||||
projectLabels,
|
||||
getProjectLabels,
|
||||
addLabelToProject,
|
||||
removeLabelFromProject,
|
||||
setProjectLabelsList,
|
||||
getProjectsByLabel,
|
||||
hasAnyLabels,
|
||||
removeLabel,
|
||||
};
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import { createAIClient } from '@/lib/ai-client';
|
||||
|
||||
interface ProviderModel {
|
||||
id: string;
|
||||
type?: "chat" | "image";
|
||||
name?: string;
|
||||
provider: string;
|
||||
fullId: string; // provider/model format
|
||||
@@ -20,7 +21,9 @@ interface ProviderModel {
|
||||
prompt: Decimal;
|
||||
/** Output/completion pricing per token */
|
||||
completion: Decimal;
|
||||
}
|
||||
};
|
||||
/** For "chat" type models - which output modalities are supported */
|
||||
modalities?: string[];
|
||||
}
|
||||
|
||||
interface ModelFetchResult {
|
||||
@@ -64,6 +67,10 @@ export function useProviderModels(): ModelFetchResult {
|
||||
fullId: `${provider.id}/${model.id}`,
|
||||
};
|
||||
|
||||
if ('type' in model && (model.type === 'chat' || model.type === 'image')) {
|
||||
providerModel.type = model.type;
|
||||
}
|
||||
|
||||
if ('name' in model && typeof model.name === 'string') {
|
||||
providerModel.name = model.name;
|
||||
}
|
||||
@@ -90,6 +97,13 @@ export function useProviderModels(): ModelFetchResult {
|
||||
};
|
||||
}
|
||||
|
||||
if ('architecture' in model && model.architecture && typeof model.architecture === 'object') {
|
||||
const { architecture } = model;
|
||||
if ('output_modalities' in architecture && Array.isArray(architecture.output_modalities)) {
|
||||
providerModel.modalities = architecture.output_modalities.filter((mod) => typeof mod === 'string');
|
||||
}
|
||||
}
|
||||
|
||||
return providerModel;
|
||||
});
|
||||
|
||||
|
||||
@@ -1,4 +1,25 @@
|
||||
import type { JSRuntimeFS, DirectoryEntry } from './JSRuntime';
|
||||
import { getParentDirectory } from './pathUtils';
|
||||
|
||||
/**
|
||||
* Error object returned from IPC handlers instead of throwing
|
||||
* to avoid Electron's noisy error logging for expected errors.
|
||||
*/
|
||||
interface IPCErrorResult {
|
||||
__error: true;
|
||||
code: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Type guard to check if an IPC result is an error object.
|
||||
*/
|
||||
function isIPCError(result: unknown): result is IPCErrorResult {
|
||||
return result !== null &&
|
||||
typeof result === 'object' &&
|
||||
'__error' in result &&
|
||||
(result as IPCErrorResult).__error === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Electron filesystem adapter that implements JSRuntimeFS interface
|
||||
@@ -7,9 +28,27 @@ import type { JSRuntimeFS, DirectoryEntry } from './JSRuntime';
|
||||
*
|
||||
* Note: This adapter should only be instantiated when running in Electron.
|
||||
*/
|
||||
/** Stat result with function methods matching the JSRuntimeFS interface */
|
||||
interface StatResult {
|
||||
isDirectory(): boolean;
|
||||
isFile(): boolean;
|
||||
isBlockDevice(): boolean;
|
||||
isCharacterDevice(): boolean;
|
||||
isSymbolicLink(): boolean;
|
||||
isFIFO(): boolean;
|
||||
isSocket(): boolean;
|
||||
size: number;
|
||||
mtimeMs: number;
|
||||
ctimeMs: number;
|
||||
atimeMs: number;
|
||||
mtime: Date;
|
||||
ctime: Date;
|
||||
atime: Date;
|
||||
}
|
||||
|
||||
export class ElectronFSAdapter implements JSRuntimeFS {
|
||||
// Cache for stat results to avoid repeated IPC calls
|
||||
private statCache = new Map<string, { result: Awaited<ReturnType<typeof this.electron.fs.stat>>; timestamp: number }>();
|
||||
private statCache = new Map<string, { result: StatResult; timestamp: number }>();
|
||||
private readonly STAT_CACHE_TTL = 1000; // 1 second TTL for stat cache
|
||||
|
||||
// Cache for ENOENT results to avoid repeated failed reads (especially for git objects)
|
||||
@@ -80,6 +119,23 @@ export class ElectronFSAdapter implements JSRuntimeFS {
|
||||
const encoding = typeof options === 'string' ? options : options?.encoding;
|
||||
const result = await this.electron.fs.readFile(path, encoding);
|
||||
|
||||
// Handle error objects returned from IPC (to avoid Electron's noisy error logging)
|
||||
if (isIPCError(result)) {
|
||||
const err = new Error(result.message);
|
||||
(err as NodeJS.ErrnoException).code = result.code;
|
||||
|
||||
// Cache ENOENT errors
|
||||
if (result.code === 'ENOENT') {
|
||||
this.enoentCache.add(path);
|
||||
if (this.enoentCache.size > this.ENOENT_CACHE_MAX_SIZE) {
|
||||
const entries = Array.from(this.enoentCache);
|
||||
entries.slice(0, 1000).forEach(entry => this.enoentCache.delete(entry));
|
||||
}
|
||||
}
|
||||
|
||||
throw err;
|
||||
}
|
||||
|
||||
// If no encoding, convert array to Uint8Array
|
||||
if (!encoding && Array.isArray(result)) {
|
||||
return new Uint8Array(result);
|
||||
@@ -117,7 +173,7 @@ export class ElectronFSAdapter implements JSRuntimeFS {
|
||||
this.statCache.delete(path);
|
||||
this.statCache.delete(`lstat:${path}`);
|
||||
this.enoentCache.delete(path); // File now exists
|
||||
const parentDir = path.substring(0, path.lastIndexOf('/'));
|
||||
const parentDir = getParentDirectory(path);
|
||||
if (parentDir) {
|
||||
this.statCache.delete(parentDir);
|
||||
this.statCache.delete(`lstat:${parentDir}`);
|
||||
@@ -138,19 +194,71 @@ export class ElectronFSAdapter implements JSRuntimeFS {
|
||||
// Use cached stat if available to avoid extra IPC call
|
||||
const cached = this.statCache.get(path);
|
||||
if (cached && Date.now() - cached.timestamp < this.STAT_CACHE_TTL) {
|
||||
if (cached.result.isFile) {
|
||||
// Note: cached.result has isFile as a function (from statResult), so we must call it
|
||||
if (cached.result.isFile()) {
|
||||
// This is a file, not a directory - throw ENOTDIR immediately
|
||||
const err = new Error(`ENOTDIR: not a directory, scandir '${path}'`);
|
||||
(err as NodeJS.ErrnoException).code = 'ENOTDIR';
|
||||
throw err;
|
||||
}
|
||||
} else {
|
||||
// No cached stat - do a stat check first to avoid unnecessary readdir IPC calls on files
|
||||
// This is important for performance since FileTree iterates all entries and calls readdir on each
|
||||
try {
|
||||
const statResult = await this.stat(path);
|
||||
if (statResult.isFile()) {
|
||||
const err = new Error(`ENOTDIR: not a directory, scandir '${path}'`);
|
||||
(err as NodeJS.ErrnoException).code = 'ENOTDIR';
|
||||
throw err;
|
||||
}
|
||||
} catch (statError) {
|
||||
// If stat fails with ENOENT, let readdir handle it
|
||||
if ((statError as NodeJS.ErrnoException).code !== 'ENOENT') {
|
||||
throw statError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const result = await this.electron.fs.readdir(path, options?.withFileTypes);
|
||||
|
||||
// Handle error objects returned from IPC (to avoid Electron's noisy error logging)
|
||||
if (isIPCError(result)) {
|
||||
const err = new Error(result.message);
|
||||
(err as NodeJS.ErrnoException).code = result.code;
|
||||
throw err;
|
||||
}
|
||||
|
||||
if (options?.withFileTypes) {
|
||||
const entries = result as Array<{ name: string; isDirectory: boolean; isFile: boolean }>;
|
||||
const now = Date.now();
|
||||
|
||||
// Cache the file type info for each child entry to speed up subsequent stat/readdir calls
|
||||
// This is a key optimization - FileTree calls readdir on all children, and we can fast-fail
|
||||
// files without hitting IPC
|
||||
for (const entry of entries) {
|
||||
const childPath = path.endsWith('/') ? `${path}${entry.name}` : `${path}/${entry.name}`;
|
||||
const nowDate = new Date(now);
|
||||
const statResult: StatResult = {
|
||||
isDirectory: () => entry.isDirectory,
|
||||
isFile: () => entry.isFile,
|
||||
isBlockDevice: () => false,
|
||||
isCharacterDevice: () => false,
|
||||
isSymbolicLink: () => false,
|
||||
isFIFO: () => false,
|
||||
isSocket: () => false,
|
||||
size: 0,
|
||||
mtimeMs: now,
|
||||
ctimeMs: now,
|
||||
atimeMs: now,
|
||||
mtime: nowDate,
|
||||
ctime: nowDate,
|
||||
atime: nowDate,
|
||||
};
|
||||
this.statCache.set(childPath, { result: statResult, timestamp: now });
|
||||
}
|
||||
|
||||
// Convert plain objects to DirectoryEntry format
|
||||
return (result as Array<{ name: string; isDirectory: boolean; isFile: boolean }>).map(entry => ({
|
||||
return entries.map(entry => ({
|
||||
name: entry.name,
|
||||
isDirectory: () => entry.isDirectory,
|
||||
isFile: () => entry.isFile,
|
||||
@@ -173,7 +281,7 @@ export class ElectronFSAdapter implements JSRuntimeFS {
|
||||
// Invalidate cache for this path and parent
|
||||
this.statCache.delete(path);
|
||||
this.statCache.delete(`lstat:${path}`);
|
||||
const parentDir = path.substring(0, path.lastIndexOf('/'));
|
||||
const parentDir = getParentDirectory(path);
|
||||
if (parentDir) {
|
||||
this.statCache.delete(parentDir);
|
||||
this.statCache.delete(`lstat:${parentDir}`);
|
||||
@@ -209,6 +317,14 @@ export class ElectronFSAdapter implements JSRuntimeFS {
|
||||
}
|
||||
|
||||
const result = await this.electron.fs.stat(path);
|
||||
|
||||
// Handle error objects returned from IPC (to avoid Electron's noisy error logging)
|
||||
if (isIPCError(result)) {
|
||||
const err = new Error(result.message);
|
||||
(err as NodeJS.ErrnoException).code = result.code;
|
||||
throw err;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const statResult = {
|
||||
isDirectory: () => result.isDirectory,
|
||||
@@ -270,6 +386,14 @@ export class ElectronFSAdapter implements JSRuntimeFS {
|
||||
}
|
||||
|
||||
const result = await this.electron.fs.lstat(path);
|
||||
|
||||
// Handle error objects returned from IPC (to avoid Electron's noisy error logging)
|
||||
if (isIPCError(result)) {
|
||||
const err = new Error(result.message);
|
||||
(err as NodeJS.ErrnoException).code = result.code;
|
||||
throw err;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const statResult = {
|
||||
isDirectory: () => result.isDirectory,
|
||||
@@ -309,10 +433,17 @@ export class ElectronFSAdapter implements JSRuntimeFS {
|
||||
try {
|
||||
const result = await this.electron.fs.unlink(path);
|
||||
|
||||
// Handle error objects returned from IPC (to avoid Electron's noisy error logging)
|
||||
if (isIPCError(result)) {
|
||||
const err = new Error(result.message);
|
||||
(err as NodeJS.ErrnoException).code = result.code;
|
||||
throw err;
|
||||
}
|
||||
|
||||
// Invalidate cache for this path and parent
|
||||
this.statCache.delete(path);
|
||||
this.statCache.delete(`lstat:${path}`);
|
||||
const parentDir = path.substring(0, path.lastIndexOf('/'));
|
||||
const parentDir = getParentDirectory(path);
|
||||
if (parentDir) {
|
||||
this.statCache.delete(parentDir);
|
||||
this.statCache.delete(`lstat:${parentDir}`);
|
||||
@@ -331,7 +462,7 @@ export class ElectronFSAdapter implements JSRuntimeFS {
|
||||
// Invalidate cache for this path and parent
|
||||
this.statCache.delete(path);
|
||||
this.statCache.delete(`lstat:${path}`);
|
||||
const parentDir = path.substring(0, path.lastIndexOf('/'));
|
||||
const parentDir = getParentDirectory(path);
|
||||
if (parentDir) {
|
||||
this.statCache.delete(parentDir);
|
||||
this.statCache.delete(`lstat:${parentDir}`);
|
||||
@@ -353,13 +484,13 @@ export class ElectronFSAdapter implements JSRuntimeFS {
|
||||
this.statCache.delete(newPath);
|
||||
this.statCache.delete(`lstat:${newPath}`);
|
||||
|
||||
const oldParent = oldPath.substring(0, oldPath.lastIndexOf('/'));
|
||||
const oldParent = getParentDirectory(oldPath);
|
||||
if (oldParent) {
|
||||
this.statCache.delete(oldParent);
|
||||
this.statCache.delete(`lstat:${oldParent}`);
|
||||
}
|
||||
|
||||
const newParent = newPath.substring(0, newPath.lastIndexOf('/'));
|
||||
const newParent = getParentDirectory(newPath);
|
||||
if (newParent) {
|
||||
this.statCache.delete(newParent);
|
||||
this.statCache.delete(`lstat:${newParent}`);
|
||||
|
||||
@@ -193,16 +193,17 @@ export class ProjectsManager {
|
||||
|
||||
/**
|
||||
* Copy a directory recursively from source to destination
|
||||
* @param skipGit - Whether to skip the .git directory (default: true)
|
||||
*/
|
||||
private async copyDirectory(sourcePath: string, destPath: string): Promise<void> {
|
||||
private async copyDirectory(sourcePath: string, destPath: string, skipGit = true): Promise<void> {
|
||||
// Ensure destination directory exists
|
||||
await this.fs.mkdir(destPath, { recursive: true });
|
||||
|
||||
const entries = await this.fs.readdir(sourcePath);
|
||||
|
||||
for (const entry of entries) {
|
||||
// Skip .git directory
|
||||
if (entry === '.git') continue;
|
||||
// Skip .git directory if skipGit is true
|
||||
if (skipGit && entry === '.git') continue;
|
||||
|
||||
const sourceFullPath = `${sourcePath}/${entry}`;
|
||||
const destFullPath = `${destPath}/${entry}`;
|
||||
@@ -212,7 +213,7 @@ export class ProjectsManager {
|
||||
|
||||
if (stat.isDirectory()) {
|
||||
// Recursively copy subdirectories
|
||||
await this.copyDirectory(sourceFullPath, destFullPath);
|
||||
await this.copyDirectory(sourceFullPath, destFullPath, skipGit);
|
||||
} else if (stat.isFile()) {
|
||||
// Copy file
|
||||
const content = await this.fs.readFile(sourceFullPath);
|
||||
@@ -726,6 +727,56 @@ export class ProjectsManager {
|
||||
};
|
||||
}
|
||||
|
||||
async duplicateProject(sourceId: string, newName?: string): Promise<Project> {
|
||||
// Validate that the source project exists
|
||||
const sourceProject = await this.getProject(sourceId);
|
||||
if (!sourceProject) {
|
||||
throw new Error(`Project with ID "${sourceId}" does not exist`);
|
||||
}
|
||||
|
||||
// Generate a unique ID for the new project
|
||||
const baseName = newName || `${sourceId}-copy`;
|
||||
const newId = await this.generateUniqueProjectId(baseName);
|
||||
|
||||
const sourcePath = `${this.dir}/${sourceId}`;
|
||||
const destPath = `${this.dir}/${newId}`;
|
||||
|
||||
try {
|
||||
// Create the destination directory
|
||||
await this.fs.mkdir(destPath, { recursive: true });
|
||||
|
||||
// Copy all files from source to destination (including .git)
|
||||
await this.copyDirectory(sourcePath, destPath, false);
|
||||
|
||||
// Get filesystem stats for timestamps
|
||||
const stats = await this.fs.stat(destPath);
|
||||
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||
|
||||
// Automatically request persistent storage after project duplication
|
||||
try {
|
||||
await ensurePersistentStorage();
|
||||
} catch (error) {
|
||||
// Don't fail project duplication if persistent storage request fails
|
||||
console.warn('Failed to request persistent storage after project duplication:', error);
|
||||
}
|
||||
|
||||
return {
|
||||
id: newId,
|
||||
name: this.formatProjectName(newId),
|
||||
path: destPath,
|
||||
lastModified: timestamp,
|
||||
};
|
||||
} catch (error) {
|
||||
// Clean up on error
|
||||
try {
|
||||
await this.deleteDirectory(destPath);
|
||||
} catch (cleanupError) {
|
||||
console.warn('Failed to clean up directory after duplication failure:', cleanupError);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private async deleteDirectory(dirPath: string): Promise<void> {
|
||||
const files = await this.fs.readdir(dirPath);
|
||||
|
||||
|
||||
@@ -63,7 +63,7 @@ export class SessionManager {
|
||||
private listeners: Partial<Record<keyof SessionManagerEvents, Set<(...args: unknown[]) => void>>> = {};
|
||||
private fs: JSRuntimeFS;
|
||||
private nostr: NPool;
|
||||
private getSettings: () => { providers: AIProvider[] };
|
||||
private getSettings: () => { providers: AIProvider[]; imageModel?: string };
|
||||
private getConfig: () => AppConfig;
|
||||
private getDefaultConfig: () => AppConfig;
|
||||
private getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>;
|
||||
@@ -72,7 +72,7 @@ export class SessionManager {
|
||||
constructor(
|
||||
fs: JSRuntimeFS,
|
||||
nostr: NPool,
|
||||
getSettings: () => { providers: AIProvider[] },
|
||||
getSettings: () => { providers: AIProvider[]; imageModel?: string },
|
||||
getConfig: () => AppConfig,
|
||||
getDefaultConfig: () => AppConfig,
|
||||
getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>,
|
||||
@@ -241,11 +241,12 @@ export class SessionManager {
|
||||
const maxSteps = session.maxSteps || 50;
|
||||
|
||||
// Main AI generation loop
|
||||
while (stepCount < maxSteps && session.isLoading) {
|
||||
session = this.sessions.get(projectId);
|
||||
if (!session) {
|
||||
throw new Error('Session not found');
|
||||
while (stepCount < maxSteps) {
|
||||
const currentSession = this.sessions.get(projectId);
|
||||
if (!currentSession || !currentSession.isLoading) {
|
||||
break;
|
||||
}
|
||||
session = currentSession;
|
||||
|
||||
stepCount++;
|
||||
|
||||
@@ -276,6 +277,21 @@ export class SessionManager {
|
||||
// Template metadata not available
|
||||
}
|
||||
|
||||
// Build model and provider info objects
|
||||
const modelInfo = {
|
||||
id: model,
|
||||
fullId: providerModel,
|
||||
};
|
||||
|
||||
const providerInfo = {
|
||||
id: provider.id,
|
||||
name: provider.name,
|
||||
baseURL: provider.baseURL,
|
||||
};
|
||||
|
||||
// Get imageModel from settings
|
||||
const settings = this.getSettings();
|
||||
|
||||
const systemPrompt = await makeSystemPrompt({
|
||||
cwd: `${config.fsPathProjects}/${projectId}`,
|
||||
fs: this.fs,
|
||||
@@ -288,6 +304,9 @@ export class SessionManager {
|
||||
repositoryUrl,
|
||||
template: config.systemPrompt,
|
||||
projectTemplate,
|
||||
model: modelInfo,
|
||||
provider: providerInfo,
|
||||
imageModel: settings.imageModel,
|
||||
});
|
||||
|
||||
// Helper function to filter out unsupported image formats (keep only JPG/JPEG/PNG)
|
||||
@@ -586,8 +605,22 @@ export class SessionManager {
|
||||
const rawArgs = functionToolCall.function.arguments;
|
||||
toolArgs = rawArgs ? JSON.parse(rawArgs) : {};
|
||||
}
|
||||
const content = await tool.execute(toolArgs);
|
||||
await this.addToolMessage(projectId, functionToolCall.id, content);
|
||||
const result = await tool.execute(toolArgs);
|
||||
await this.addToolMessage(projectId, functionToolCall.id, result.content);
|
||||
|
||||
// Update session cost if tool returned a cost
|
||||
if (result.cost !== undefined) {
|
||||
const updatedSession = this.sessions.get(projectId);
|
||||
if (updatedSession) {
|
||||
const currentCost = updatedSession.totalCost || 0;
|
||||
updatedSession.totalCost = currentCost + result.cost;
|
||||
this.sessions.set(projectId, updatedSession);
|
||||
this.emit('costUpdated', projectId, updatedSession.totalCost);
|
||||
|
||||
// Accumulate tool cost to project total
|
||||
await this.accumulateProjectCost(projectId, result.cost);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMsg = error instanceof Error ? error.message : 'Unknown error';
|
||||
await this.addToolMessage(projectId, functionToolCall.id, `Error with tool ${toolName}: ${errorMsg}`);
|
||||
|
||||
@@ -2,6 +2,7 @@ import { join, dirname, extname } from "path-browserify";
|
||||
|
||||
import type { Loader, Plugin } from "esbuild-wasm";
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
import { isAbsolutePath, normalizeToForwardSlashes } from '@/lib/pathUtils';
|
||||
|
||||
interface TsConfig {
|
||||
compilerOptions?: {
|
||||
@@ -35,21 +36,36 @@ export function fsPlugin(options: FsPluginOptions): Plugin {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if this looks like a bare module specifier (npm package)
|
||||
// Bare specifiers don't start with '.', '..', '/', or '@/' (our alias)
|
||||
// Examples: 'react', 'react/jsx-runtime', '@tanstack/react-query'
|
||||
const isBareSpecifier = !args.path.startsWith('.') &&
|
||||
!args.path.startsWith('/') &&
|
||||
!args.path.startsWith('@/') &&
|
||||
!isAbsolutePath(args.path);
|
||||
|
||||
let resolved: string;
|
||||
if (args.path.startsWith("/")) {
|
||||
resolved = args.path;
|
||||
// Handle absolute paths (Unix or Windows style)
|
||||
if (isAbsolutePath(args.path)) {
|
||||
resolved = normalizeToForwardSlashes(args.path);
|
||||
} else if (args.path.startsWith("@/")) {
|
||||
resolved = join(cwd, "src", args.path.slice(2));
|
||||
} else if (args.importer && (args.path.startsWith("./") || args.path.startsWith("../"))) {
|
||||
resolved = join(dirname(args.importer), args.path);
|
||||
} else if (args.importer && tsconfig?.compilerOptions?.baseUrl) {
|
||||
} else if (args.importer && tsconfig?.compilerOptions?.baseUrl && !isBareSpecifier) {
|
||||
// Only use baseUrl for non-bare specifiers (local project paths)
|
||||
// Don't try to resolve npm packages via baseUrl
|
||||
resolved = join(cwd, tsconfig.compilerOptions.baseUrl, args.path);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
// Normalize to forward slashes for consistent comparison
|
||||
resolved = normalizeToForwardSlashes(resolved);
|
||||
const normalizedCwd = normalizeToForwardSlashes(cwd);
|
||||
|
||||
// Security: prevent accessing files outside the project directory
|
||||
if (resolved.startsWith("/") && !resolved.startsWith(cwd)) {
|
||||
if (isAbsolutePath(resolved) && !resolved.startsWith(normalizedCwd)) {
|
||||
throw new Error(`Access to files outside the project directory is not allowed: ${resolved}`);
|
||||
}
|
||||
|
||||
|
||||
@@ -53,6 +53,7 @@ const mcpServerSchema: z.ZodType<MCPServer> = z.object({
|
||||
const aiSettingsSchema = z.object({
|
||||
providers: filteredArray(aiProviderSchema),
|
||||
recentlyUsedModels: filteredArray(providerModelSchema),
|
||||
imageModel: providerModelSchema.optional(),
|
||||
mcpServers: z.record(z.string(), mcpServerSchema).optional(),
|
||||
});
|
||||
|
||||
|
||||
+3
-2
@@ -187,6 +187,7 @@ describe('Git', () => {
|
||||
mockGit.clone = vi.fn().mockResolvedValue(undefined);
|
||||
mockGit.deleteRemote = vi.fn().mockResolvedValue(undefined);
|
||||
mockGit.addRemote = vi.fn().mockResolvedValue(undefined);
|
||||
mockGit.getRemoteInfo = vi.fn().mockResolvedValue({ refs: {} });
|
||||
|
||||
// Mock nip19 decode
|
||||
vi.mocked(nip19.decode).mockReturnValue({
|
||||
@@ -222,12 +223,12 @@ describe('Git', () => {
|
||||
url: nostrUrl,
|
||||
});
|
||||
|
||||
// Should attempt to clone from the first URL
|
||||
// Should attempt to clone from one of the URLs (implementation uses the last successfully checked URL)
|
||||
expect(mockGit.clone).toHaveBeenCalledWith({
|
||||
fs,
|
||||
http: expect.any(Object),
|
||||
dir: '/test',
|
||||
url: 'https://github.com/user/repo.git',
|
||||
url: expect.stringMatching(/^https:\/\/(github|gitlab)\.com\/user\/repo\.git$/),
|
||||
});
|
||||
|
||||
// Should delete the existing origin remote
|
||||
|
||||
+98
-57
@@ -1191,78 +1191,119 @@ export class Git {
|
||||
let lastError: Error | null = null;
|
||||
let cloneSuccessful = false;
|
||||
|
||||
// If we have state information, try to find a clone URL that contains the expected commit
|
||||
// Track the clone URL with the most recent commit timestamp
|
||||
let bestCloneUrl: string | undefined;
|
||||
let bestCloneTimestamp = 0;
|
||||
|
||||
// Loop through all clone URLs, checking remote info for each
|
||||
if (expectedCommit) {
|
||||
console.log(`Looking for repository with commit: ${expectedCommit}`);
|
||||
}
|
||||
|
||||
for (const cloneUrl of repo.httpsCloneUrls) {
|
||||
try {
|
||||
console.log(`Checking remote info for: ${cloneUrl}`);
|
||||
for (const cloneUrl of repo.httpsCloneUrls) {
|
||||
try {
|
||||
console.log(`Checking remote info for: ${cloneUrl}`);
|
||||
|
||||
// Get remote repository information to check if it has the expected commit
|
||||
const remoteInfo = await Promise.race([
|
||||
git.getRemoteInfo({
|
||||
// Get remote repository information
|
||||
const remoteInfo = await Promise.race([
|
||||
git.getRemoteInfo({
|
||||
http: this.http,
|
||||
url: cloneUrl,
|
||||
}),
|
||||
new Promise<never>((_, reject) =>
|
||||
setTimeout(() => reject(new Error('Remote info timeout')), 10000)
|
||||
)
|
||||
]);
|
||||
|
||||
// Track this remote's most recent commit timestamp
|
||||
// We use the current time as a proxy since we can't easily get commit timestamps
|
||||
// from remote info without cloning. The first successful remote will be our fallback.
|
||||
const timestamp = Date.now();
|
||||
if (!bestCloneUrl || timestamp > bestCloneTimestamp) {
|
||||
bestCloneUrl = cloneUrl;
|
||||
bestCloneTimestamp = timestamp;
|
||||
}
|
||||
|
||||
// Check if the expected commit exists in any of the remote refs
|
||||
const hasExpectedCommit = expectedCommit && Object.values(remoteInfo.refs || {}).includes(expectedCommit);
|
||||
|
||||
if (hasExpectedCommit && expectedCommit) {
|
||||
console.log(`Found expected commit ${expectedCommit} in ${cloneUrl}`);
|
||||
|
||||
// Clone from this URL since it has the expected commit
|
||||
await Promise.race([
|
||||
git.clone({
|
||||
fs: this.fs,
|
||||
http: this.http,
|
||||
...options,
|
||||
url: cloneUrl,
|
||||
}),
|
||||
new Promise<never>((_, reject) =>
|
||||
setTimeout(() => reject(new Error('Remote info timeout')), 10000)
|
||||
setTimeout(() => reject(new Error('Clone timeout')), 30000)
|
||||
)
|
||||
]);
|
||||
|
||||
// Check if the expected commit exists in any of the remote refs
|
||||
const hasExpectedCommit = Object.values(remoteInfo.refs).includes(expectedCommit);
|
||||
// Verify the cloned repository has the expected commit
|
||||
try {
|
||||
await git.readCommit({
|
||||
fs: this.fs,
|
||||
dir: options.dir,
|
||||
oid: expectedCommit,
|
||||
});
|
||||
|
||||
if (hasExpectedCommit) {
|
||||
console.log(`Found expected commit ${expectedCommit} in ${cloneUrl}`);
|
||||
|
||||
// Clone from this URL since it has the expected commit
|
||||
await Promise.race([
|
||||
git.clone({
|
||||
fs: this.fs,
|
||||
http: this.http,
|
||||
...options,
|
||||
url: cloneUrl,
|
||||
}),
|
||||
new Promise<never>((_, reject) =>
|
||||
setTimeout(() => reject(new Error('Clone timeout')), 30000)
|
||||
)
|
||||
]);
|
||||
|
||||
// Verify the cloned repository has the expected commit
|
||||
try {
|
||||
await git.readCommit({
|
||||
fs: this.fs,
|
||||
dir: options.dir,
|
||||
oid: expectedCommit,
|
||||
});
|
||||
|
||||
// If we have an expected branch, check out to it
|
||||
if (expectedBranch) {
|
||||
try {
|
||||
await git.checkout({
|
||||
fs: this.fs,
|
||||
dir: options.dir,
|
||||
ref: expectedBranch,
|
||||
});
|
||||
} catch (checkoutError) {
|
||||
console.warn(`Failed to checkout branch ${expectedBranch}:`, checkoutError);
|
||||
// Continue anyway, the clone was successful
|
||||
}
|
||||
// If we have an expected branch, check out to it
|
||||
if (expectedBranch) {
|
||||
try {
|
||||
await git.checkout({
|
||||
fs: this.fs,
|
||||
dir: options.dir,
|
||||
ref: expectedBranch,
|
||||
});
|
||||
} catch (checkoutError) {
|
||||
console.warn(`Failed to checkout branch ${expectedBranch}:`, checkoutError);
|
||||
// Continue anyway, the clone was successful
|
||||
}
|
||||
|
||||
cloneSuccessful = true;
|
||||
break;
|
||||
} catch (commitError) {
|
||||
console.warn(`Cloned repository doesn't contain expected commit ${expectedCommit}:`, commitError);
|
||||
// Continue to try other URLs
|
||||
}
|
||||
|
||||
cloneSuccessful = true;
|
||||
break;
|
||||
} catch (commitError) {
|
||||
console.warn(`Cloned repository doesn't contain expected commit ${expectedCommit}:`, commitError);
|
||||
// Continue to try other URLs
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`Failed to check/clone from ${cloneUrl}:`, error);
|
||||
lastError = error instanceof Error ? error : new Error('Unknown error');
|
||||
continue;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`Failed to check/clone from ${cloneUrl}:`, error);
|
||||
lastError = error instanceof Error ? error : new Error('Unknown error');
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// If we didn't find the expected commit, clone from the best URL we found
|
||||
if (!cloneSuccessful && bestCloneUrl) {
|
||||
if (expectedCommit) {
|
||||
console.log(`Expected commit ${expectedCommit} not found, cloning from: ${bestCloneUrl}`);
|
||||
} else {
|
||||
console.log(`Cloning from: ${bestCloneUrl}`);
|
||||
}
|
||||
|
||||
try {
|
||||
await Promise.race([
|
||||
git.clone({
|
||||
fs: this.fs,
|
||||
http: this.http,
|
||||
...options,
|
||||
url: bestCloneUrl,
|
||||
}),
|
||||
new Promise<never>((_, reject) =>
|
||||
setTimeout(() => reject(new Error('Clone timeout')), 30000)
|
||||
)
|
||||
]);
|
||||
|
||||
cloneSuccessful = true;
|
||||
} catch (error) {
|
||||
console.warn(`Failed to clone from ${bestCloneUrl}:`, error);
|
||||
lastError = error instanceof Error ? error : new Error('Unknown error');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1476,7 +1517,7 @@ export class Git {
|
||||
// Delete any local remote refs that don't exist in the Repository State
|
||||
for (const localRemoteRef of localRemoteRefs) {
|
||||
const fullRef = this.localRefToRemoteRef(remoteName, localRemoteRef);
|
||||
|
||||
|
||||
if (!expectedRemoteRefs.has(fullRef)) {
|
||||
try {
|
||||
await git.deleteRef({
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
/** Predefined label colors */
|
||||
export const LABEL_COLORS = [
|
||||
{ name: 'red', bg: 'bg-red-500', text: 'text-red-500', hover: 'hover:bg-red-500/20' },
|
||||
{ name: 'orange', bg: 'bg-orange-500', text: 'text-orange-500', hover: 'hover:bg-orange-500/20' },
|
||||
{ name: 'amber', bg: 'bg-amber-500', text: 'text-amber-500', hover: 'hover:bg-amber-500/20' },
|
||||
{ name: 'yellow', bg: 'bg-yellow-500', text: 'text-yellow-500', hover: 'hover:bg-yellow-500/20' },
|
||||
{ name: 'lime', bg: 'bg-lime-500', text: 'text-lime-500', hover: 'hover:bg-lime-500/20' },
|
||||
{ name: 'green', bg: 'bg-green-500', text: 'text-green-500', hover: 'hover:bg-green-500/20' },
|
||||
{ name: 'emerald', bg: 'bg-emerald-500', text: 'text-emerald-500', hover: 'hover:bg-emerald-500/20' },
|
||||
{ name: 'teal', bg: 'bg-teal-500', text: 'text-teal-500', hover: 'hover:bg-teal-500/20' },
|
||||
{ name: 'cyan', bg: 'bg-cyan-500', text: 'text-cyan-500', hover: 'hover:bg-cyan-500/20' },
|
||||
{ name: 'sky', bg: 'bg-sky-500', text: 'text-sky-500', hover: 'hover:bg-sky-500/20' },
|
||||
{ name: 'blue', bg: 'bg-blue-500', text: 'text-blue-500', hover: 'hover:bg-blue-500/20' },
|
||||
{ name: 'indigo', bg: 'bg-indigo-500', text: 'text-indigo-500', hover: 'hover:bg-indigo-500/20' },
|
||||
{ name: 'violet', bg: 'bg-violet-500', text: 'text-violet-500', hover: 'hover:bg-violet-500/20' },
|
||||
{ name: 'purple', bg: 'bg-purple-500', text: 'text-purple-500', hover: 'hover:bg-purple-500/20' },
|
||||
{ name: 'fuchsia', bg: 'bg-fuchsia-500', text: 'text-fuchsia-500', hover: 'hover:bg-fuchsia-500/20' },
|
||||
{ name: 'pink', bg: 'bg-pink-500', text: 'text-pink-500', hover: 'hover:bg-pink-500/20' },
|
||||
{ name: 'rose', bg: 'bg-rose-500', text: 'text-rose-500', hover: 'hover:bg-rose-500/20' },
|
||||
{ name: 'gray', bg: 'bg-gray-500', text: 'text-gray-500', hover: 'hover:bg-gray-500/20' },
|
||||
] as const;
|
||||
|
||||
export type LabelColorName = typeof LABEL_COLORS[number]['name'];
|
||||
|
||||
export interface Label {
|
||||
id: string;
|
||||
name: string;
|
||||
color: LabelColorName;
|
||||
collapsed?: boolean;
|
||||
}
|
||||
|
||||
/** Get the color config for a label color name */
|
||||
export function getLabelColor(colorName: LabelColorName) {
|
||||
return LABEL_COLORS.find(c => c.name === colorName) || LABEL_COLORS[0];
|
||||
}
|
||||
|
||||
/** Generate a unique label ID */
|
||||
export function generateLabelId(): string {
|
||||
return `label-${Date.now()}-${Math.random().toString(36).substring(2, 7)}`;
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* Cross-platform path utilities for handling both Unix and Windows path separators.
|
||||
* These utilities ensure consistent behavior across different operating systems.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Get the parent directory of a path, handling both forward and back slashes.
|
||||
* This is particularly important for Windows paths in Electron.
|
||||
*
|
||||
* @param path - The file or directory path
|
||||
* @returns The parent directory path, or empty string if at root
|
||||
*/
|
||||
export function getParentDirectory(path: string): string {
|
||||
// Find the last occurrence of either separator
|
||||
const lastForwardSlash = path.lastIndexOf('/');
|
||||
const lastBackSlash = path.lastIndexOf('\\');
|
||||
const lastSeparator = Math.max(lastForwardSlash, lastBackSlash);
|
||||
|
||||
if (lastSeparator === -1) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return path.substring(0, lastSeparator);
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a path to use forward slashes consistently.
|
||||
* This is useful for the VFS which uses Unix-style paths internally.
|
||||
*
|
||||
* @param path - The path to normalize
|
||||
* @returns The path with all backslashes converted to forward slashes
|
||||
*/
|
||||
export function normalizeToForwardSlashes(path: string): string {
|
||||
return path.replace(/\\/g, '/');
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a path to use the native separator for the current platform.
|
||||
* On Windows, uses backslashes; on Unix-like systems, uses forward slashes.
|
||||
*
|
||||
* @param path - The path to normalize
|
||||
* @returns The path with separators appropriate for the current platform
|
||||
*/
|
||||
export function normalizeToNativeSeparator(path: string): string {
|
||||
const isWindows = typeof navigator !== 'undefined'
|
||||
? navigator.platform?.toLowerCase().includes('win')
|
||||
: false;
|
||||
|
||||
if (isWindows) {
|
||||
return path.replace(/\//g, '\\');
|
||||
}
|
||||
return path.replace(/\\/g, '/');
|
||||
}
|
||||
|
||||
/**
|
||||
* Join path segments with forward slashes, regardless of platform.
|
||||
* This is useful for VFS paths which always use forward slashes.
|
||||
*
|
||||
* @param segments - Path segments to join
|
||||
* @returns The joined path with forward slashes
|
||||
*/
|
||||
export function joinWithForwardSlashes(...segments: string[]): string {
|
||||
return segments
|
||||
.filter(Boolean)
|
||||
.map(s => s.replace(/^[/\\]+|[/\\]+$/g, '')) // Trim leading/trailing slashes
|
||||
.join('/');
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a path is absolute on any platform.
|
||||
* Recognizes:
|
||||
* - Unix absolute paths starting with /
|
||||
* - Windows absolute paths starting with \ or drive letter (C:\)
|
||||
*
|
||||
* @param path - The path to check
|
||||
* @returns True if the path is absolute
|
||||
*/
|
||||
export function isAbsolutePath(path: string): boolean {
|
||||
return path.startsWith('/') || path.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the file name from a path, handling both separators.
|
||||
*
|
||||
* @param path - The file path
|
||||
* @returns The file name
|
||||
*/
|
||||
export function getBasename(path: string): string {
|
||||
const lastForwardSlash = path.lastIndexOf('/');
|
||||
const lastBackSlash = path.lastIndexOf('\\');
|
||||
const lastSeparator = Math.max(lastForwardSlash, lastBackSlash);
|
||||
|
||||
if (lastSeparator === -1) {
|
||||
return path;
|
||||
}
|
||||
|
||||
return path.substring(lastSeparator + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Expand tilde (~) in paths to the home directory.
|
||||
* Works with both Unix (~/) and Windows (~\) style paths.
|
||||
*
|
||||
* @param path - The path that may contain tilde
|
||||
* @param homedir - The user's home directory
|
||||
* @returns The expanded path
|
||||
*/
|
||||
export function expandTildePath(path: string, homedir: string): string {
|
||||
if (path === '~') {
|
||||
return homedir;
|
||||
}
|
||||
if (path.startsWith('~/')) {
|
||||
return homedir + path.slice(1);
|
||||
}
|
||||
if (path.startsWith('~\\')) {
|
||||
return homedir + path.slice(1);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
+7
-5
@@ -3,6 +3,7 @@
|
||||
*/
|
||||
|
||||
import { normalize } from "path-browserify";
|
||||
import { normalizeToForwardSlashes } from "./pathUtils";
|
||||
|
||||
/**
|
||||
* Check if the given path is an absolute path
|
||||
@@ -38,11 +39,12 @@ export function isWriteAllowed(
|
||||
}
|
||||
|
||||
// For absolute paths, apply restrictions
|
||||
const absolutePath = normalize(path);
|
||||
// Normalize to forward slashes for consistent comparison (handles both Unix and Windows paths)
|
||||
const absolutePath = normalizeToForwardSlashes(normalize(path));
|
||||
|
||||
// Get configured paths with defaults
|
||||
const tmpPath = options?.tmpPath || '/tmp';
|
||||
const projectsPath = options?.projectsPath || '/projects';
|
||||
// Get configured paths with defaults and normalize them
|
||||
const tmpPath = normalizeToForwardSlashes(options?.tmpPath || '/tmp');
|
||||
const projectsPath = normalizeToForwardSlashes(options?.projectsPath || '/projects');
|
||||
|
||||
// Allow writes to tmp directory and its subdirectories
|
||||
if (absolutePath.startsWith(tmpPath + '/') || absolutePath === tmpPath) {
|
||||
@@ -56,7 +58,7 @@ export function isWriteAllowed(
|
||||
|
||||
// If we have a current working directory, allow writes within that directory tree
|
||||
if (cwd) {
|
||||
const normalizedCwd = normalize(cwd);
|
||||
const normalizedCwd = normalizeToForwardSlashes(normalize(cwd));
|
||||
if (absolutePath.startsWith(normalizedCwd + '/') || absolutePath === normalizedCwd) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -73,6 +73,15 @@ describe('makeSystemPrompt', () => {
|
||||
cwd: '/projects/test-project',
|
||||
config: testConfig,
|
||||
defaultConfig: testConfig,
|
||||
model: {
|
||||
id: 'gpt-4',
|
||||
fullId: 'openai/gpt-4',
|
||||
},
|
||||
provider: {
|
||||
id: 'openai',
|
||||
name: 'OpenAI',
|
||||
baseURL: 'https://api.openai.com/v1',
|
||||
},
|
||||
};
|
||||
|
||||
// Mock getAllSkills to return empty array by default
|
||||
@@ -607,4 +616,65 @@ Skills: {{ skills.length }}`;
|
||||
expect(result).not.toContain('**(CURRENT TEMPLATE)**');
|
||||
});
|
||||
});
|
||||
|
||||
describe('model and provider information', () => {
|
||||
it('should include model and provider information in the system prompt', async () => {
|
||||
const result = await makeSystemPrompt(baseOpts);
|
||||
|
||||
expect(result).toContain('**AI Model**: openai/gpt-4');
|
||||
});
|
||||
|
||||
it('should include model information with different provider', async () => {
|
||||
const model = {
|
||||
id: 'claude-3-opus',
|
||||
fullId: 'anthropic/claude-3-opus',
|
||||
};
|
||||
|
||||
const provider = {
|
||||
id: 'anthropic',
|
||||
name: 'Anthropic',
|
||||
baseURL: 'https://api.anthropic.com/v1',
|
||||
};
|
||||
|
||||
const result = await makeSystemPrompt({
|
||||
...baseOpts,
|
||||
model,
|
||||
provider,
|
||||
});
|
||||
|
||||
expect(result).toContain('**AI Model**: anthropic/claude-3-opus');
|
||||
});
|
||||
|
||||
it('should make model and provider objects accessible in custom templates', async () => {
|
||||
const model = {
|
||||
id: 'claude-3-opus',
|
||||
fullId: 'anthropic/claude-3-opus',
|
||||
};
|
||||
|
||||
const provider = {
|
||||
id: 'anthropic',
|
||||
name: 'Anthropic',
|
||||
baseURL: 'https://api.anthropic.com/v1',
|
||||
};
|
||||
|
||||
const customTemplate = `Model ID: {{ model.id }}
|
||||
Model Full ID: {{ model.fullId }}
|
||||
Provider Name: {{ provider.name }}
|
||||
Provider ID: {{ provider.id }}
|
||||
Provider Base URL: {{ provider.baseURL }}`;
|
||||
|
||||
const result = await makeSystemPrompt({
|
||||
...baseOpts,
|
||||
model,
|
||||
provider,
|
||||
template: customTemplate,
|
||||
});
|
||||
|
||||
expect(result).toContain('Model ID: claude-3-opus');
|
||||
expect(result).toContain('Model Full ID: anthropic/claude-3-opus');
|
||||
expect(result).toContain('Provider Name: Anthropic');
|
||||
expect(result).toContain('Provider ID: anthropic');
|
||||
expect(result).toContain('Provider Base URL: https://api.anthropic.com/v1');
|
||||
});
|
||||
});
|
||||
});
|
||||
+50
-1
@@ -8,6 +8,17 @@ import { JSRuntimeFS } from "./JSRuntime";
|
||||
import { getAllSkills } from "./plugins";
|
||||
import type { AppConfig } from "@/contexts/AppContext";
|
||||
|
||||
export interface ModelInfo {
|
||||
id: string;
|
||||
fullId: string;
|
||||
}
|
||||
|
||||
export interface ProviderInfo {
|
||||
id: string;
|
||||
name: string;
|
||||
baseURL: string;
|
||||
}
|
||||
|
||||
export interface MakeSystemPromptOpts {
|
||||
tools: OpenAI.Chat.Completions.ChatCompletionTool[];
|
||||
mode: "init" | "agent";
|
||||
@@ -20,6 +31,9 @@ export interface MakeSystemPromptOpts {
|
||||
repositoryUrl?: string;
|
||||
template?: string;
|
||||
projectTemplate?: { name: string; description: string; url: string };
|
||||
model: ModelInfo;
|
||||
provider: ProviderInfo;
|
||||
imageModel?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -32,10 +46,12 @@ export const defaultSystemPrompt = `{% if mode === "init" %}You are Shakespeare,
|
||||
|
||||
You are operating within **Shakespeare**, an AI-powered website builder that allows users to create custom applications through natural language conversation.
|
||||
|
||||
- **AI Model**: {{ model.fullId }}
|
||||
- **Current Date**: {{ date }}
|
||||
- **Current Page**: {{ location.href }}
|
||||
- **Current Working Directory**: {{ cwd }}
|
||||
- **Repository URL**: {% if repositoryUrl %}{{ repositoryUrl }}{% else %}none{% endif %}
|
||||
- **Deployed URL**: {% if deployedUrl %}{{ deployedUrl }}{% else %}not deployed{% endif %}
|
||||
{% if projectTemplate %}- **Project Template**: {{ projectTemplate.name }}{% endif %}
|
||||
|
||||
Users can add or remove templates in Settings > AI (\`{{ location.origin }}/settings/ai\`).
|
||||
@@ -172,6 +188,17 @@ You have access to the following tools:
|
||||
- **{{ tool.function.name }}**: {{ tool.function.description or 'No description available' }}{% endif %}{% endfor %}{% else %}
|
||||
There are no tools available to you.{% endif %}
|
||||
|
||||
## Image Generation
|
||||
|
||||
Shakespeare supports AI-powered image generation. Users can configure an image model in **Settings > AI** under the "Advanced" section.
|
||||
|
||||
{% if imageModel %}- **Configured Image Model**: {{ imageModel }}{% else %}- **Image Model Status**: Not configured{% endif %}
|
||||
|
||||
**Important Notes:**
|
||||
- Not all models support image generation. If users experience issues with image generation, they should try selecting a different image model in Settings > AI
|
||||
- The generate_image tool will only be available once a compatible image model is configured
|
||||
- When generating images for projects, prefer "jpeg" or "webp" output formats with compression set between 70-90. You must supply these parameters when calling the generate_image tool to ensure optimal image quality and file size for web usage.
|
||||
|
||||
## Skills
|
||||
|
||||
{% if skills and skills.length > 0 %}You have access to the following skills. **Skills MUST be used whenever applicable** by calling the \`skill\` tool with the skill name.
|
||||
@@ -226,7 +253,7 @@ Note: the badge should be displayed at its natural size. It is recommended to om
|
||||
{{ AGENTS }}{% endif %}`;
|
||||
|
||||
export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise<string> {
|
||||
const { tools, mode, fs, cwd, config, defaultConfig, user, metadata, repositoryUrl, template, projectTemplate } = opts;
|
||||
const { tools, mode, fs, cwd, config, defaultConfig, user, metadata, repositoryUrl, template, projectTemplate, model, provider, imageModel } = opts;
|
||||
|
||||
// Add current date
|
||||
const date = new Date().toLocaleDateString("en-US", {
|
||||
@@ -265,6 +292,24 @@ export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise<stri
|
||||
// AGENTS.md not found, continue
|
||||
}
|
||||
|
||||
// Get deployed URL if it exists
|
||||
let deployedUrl: string | undefined;
|
||||
try {
|
||||
const deployConfigPath = join(cwd, '.git/shakespeare/deploy.json');
|
||||
const deployConfigText = await fs.readFile(deployConfigPath, 'utf8');
|
||||
const deployConfig = JSON.parse(deployConfigText);
|
||||
|
||||
// Get the current provider's URL
|
||||
if (deployConfig.currentProvider && deployConfig.providers) {
|
||||
const currentProviderConfig = deployConfig.providers[deployConfig.currentProvider];
|
||||
if (currentProviderConfig?.url) {
|
||||
deployedUrl = currentProviderConfig.url;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Deploy config not found or invalid, continue
|
||||
}
|
||||
|
||||
// Build URLs for Edit with Shakespeare
|
||||
let badgeUrl: string | undefined;
|
||||
let editUrl: string | undefined;
|
||||
@@ -281,6 +326,7 @@ export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise<stri
|
||||
date,
|
||||
cwd,
|
||||
repositoryUrl,
|
||||
deployedUrl,
|
||||
config,
|
||||
defaultConfig,
|
||||
user: user
|
||||
@@ -308,6 +354,9 @@ export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise<stri
|
||||
README: readmeText,
|
||||
AGENTS: agentsText,
|
||||
projectTemplate,
|
||||
model,
|
||||
provider,
|
||||
imageModel,
|
||||
};
|
||||
|
||||
// Render the template with the context
|
||||
|
||||
+11
-7
@@ -5,8 +5,9 @@ import type { JSRuntimeFS } from './JSRuntime';
|
||||
* @param fs - The filesystem instance
|
||||
* @param dirPath - The directory path to clean
|
||||
* @param maxAgeMs - Maximum age in milliseconds (files older than this will be removed)
|
||||
* @param rootPath - The root directory being cleaned (should never be deleted)
|
||||
*/
|
||||
async function cleanupDirectory(fs: JSRuntimeFS, dirPath: string, maxAgeMs: number): Promise<void> {
|
||||
async function cleanupDirectory(fs: JSRuntimeFS, dirPath: string, maxAgeMs: number, rootPath: string): Promise<void> {
|
||||
const now = Date.now();
|
||||
|
||||
try {
|
||||
@@ -34,11 +35,14 @@ async function cleanupDirectory(fs: JSRuntimeFS, dirPath: string, maxAgeMs: numb
|
||||
if (fileAge > maxAgeMs) {
|
||||
if (entry.isDirectory()) {
|
||||
// Recursively clean subdirectory first, then remove it
|
||||
await cleanupDirectory(fs, fullPath, maxAgeMs);
|
||||
await cleanupDirectory(fs, fullPath, maxAgeMs, rootPath);
|
||||
try {
|
||||
// Try to remove the directory (will only succeed if empty)
|
||||
await fs.rmdir(fullPath);
|
||||
console.log(`Removed old directory: ${fullPath}`);
|
||||
// Never delete the root cleanup directory itself, only its contents
|
||||
if (fullPath !== rootPath) {
|
||||
// Try to remove the directory (will only succeed if empty)
|
||||
await fs.rmdir(fullPath);
|
||||
console.log(`Removed old directory: ${fullPath}`);
|
||||
}
|
||||
} catch {
|
||||
// Directory might not be empty, that's okay
|
||||
}
|
||||
@@ -49,7 +53,7 @@ async function cleanupDirectory(fs: JSRuntimeFS, dirPath: string, maxAgeMs: numb
|
||||
}
|
||||
} else if (entry.isDirectory()) {
|
||||
// Directory is not old enough to remove, but clean its contents
|
||||
await cleanupDirectory(fs, fullPath, maxAgeMs);
|
||||
await cleanupDirectory(fs, fullPath, maxAgeMs, rootPath);
|
||||
}
|
||||
} catch (error) {
|
||||
// Log error but continue with other files
|
||||
@@ -72,7 +76,7 @@ export async function cleanupTmpDirectory(fs: JSRuntimeFS, tmpPath = '/tmp'): Pr
|
||||
console.log(`Starting ${tmpPath} directory cleanup...`);
|
||||
|
||||
try {
|
||||
await cleanupDirectory(fs, tmpPath, ONE_HOUR_MS);
|
||||
await cleanupDirectory(fs, tmpPath, ONE_HOUR_MS, tmpPath);
|
||||
console.log(`Completed ${tmpPath} directory cleanup`);
|
||||
} catch (error) {
|
||||
console.error(`Error during ${tmpPath} cleanup:`, error);
|
||||
|
||||
@@ -75,12 +75,12 @@ describe('BuildProjectTool', () => {
|
||||
domParser: expect.any(DOMParser),
|
||||
});
|
||||
|
||||
expect(result).toContain('✅ Successfully built project!');
|
||||
expect(result).toContain('📁 Output: /test/project/dist');
|
||||
expect(result).toContain('📦 Files generated: 3');
|
||||
expect(result).toContain('📄 index.html');
|
||||
expect(result).toContain('📄 main.js');
|
||||
expect(result).toContain('📄 main.css');
|
||||
expect(result.content).toContain('✅ Successfully built project!');
|
||||
expect(result.content).toContain('📁 Output: /test/project/dist');
|
||||
expect(result.content).toContain('📦 Files generated: 3');
|
||||
expect(result.content).toContain('📄 index.html');
|
||||
expect(result.content).toContain('📄 main.js');
|
||||
expect(result.content).toContain('📄 main.css');
|
||||
});
|
||||
|
||||
it('should clean existing dist directory before building', async () => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Tool } from "./Tool";
|
||||
import type { Tool, ToolResult } from "./Tool";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import { buildProject } from "../build";
|
||||
|
||||
@@ -15,7 +15,7 @@ export class BuildProjectTool implements Tool<void> {
|
||||
this.esmUrl = esmUrl;
|
||||
}
|
||||
|
||||
async execute(): Promise<string> {
|
||||
async execute(): Promise<ToolResult> {
|
||||
try {
|
||||
// Build and write the project files
|
||||
const result = await buildProject({
|
||||
@@ -28,7 +28,9 @@ export class BuildProjectTool implements Tool<void> {
|
||||
const fileCount = Object.keys(result.files).length;
|
||||
const fileList = Object.keys(result.files).map(file => ` 📄 ${file}`).join('\n');
|
||||
|
||||
return `✅ Successfully built project!\n\n📁 Output: ${result.outputPath}\n📦 Files generated: ${fileCount}\n\n${fileList}\n\n🚀 Your project is ready for deployment!`;
|
||||
return {
|
||||
content: `✅ Successfully built project!\n\n📁 Output: ${result.outputPath}\n📦 Files generated: ${fileCount}\n\n${fileList}\n\n🚀 Your project is ready for deployment!`
|
||||
};
|
||||
} catch (error) {
|
||||
throw new Error(`❌ Build failed: ${String(error)}`);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { z } from 'zod';
|
||||
import type { Tool, ToolResult } from './Tool';
|
||||
import type { AISettingsContextType } from '@/contexts/AISettingsContext';
|
||||
|
||||
interface ConfigureImageGenerationParams {
|
||||
modelId: string;
|
||||
}
|
||||
|
||||
interface ProviderModel {
|
||||
id: string;
|
||||
name?: string;
|
||||
provider: string;
|
||||
fullId: string;
|
||||
description?: string;
|
||||
contextLength?: number;
|
||||
modalities?: string[];
|
||||
}
|
||||
|
||||
export class ConfigureImageGenerationTool implements Tool<ConfigureImageGenerationParams> {
|
||||
readonly description = 'Configure the AI model to use for image generation. The modelId must be a complete model identifier in the format "provider/model" (e.g., "openrouter/openai/gpt-image-1", "openai/dall-e-3", or "shakespeare/gpt-image-1"). You can optionally call view_available_models first to see available image models, but any valid model ID from a configured provider will work. Prefer gpt-image-1 as the first choice, followed by gemini-3-pro-image, unless the user has specific requirements.';
|
||||
|
||||
readonly inputSchema = z.object({
|
||||
modelId: z.string().describe('The complete model identifier in "provider/model" format (e.g., "openrouter/openai/gpt-image-1", "openai/dall-e-3").'),
|
||||
});
|
||||
|
||||
constructor(
|
||||
private aiSettings: AISettingsContextType,
|
||||
private models: ProviderModel[],
|
||||
) {}
|
||||
|
||||
async execute(args: ConfigureImageGenerationParams): Promise<ToolResult> {
|
||||
const { modelId } = args;
|
||||
|
||||
// Validate model ID format
|
||||
if (!modelId.includes('/')) {
|
||||
return { content: 'ERROR: Invalid model ID format. The modelId must be in "provider/model" format (e.g., "openrouter/openai/gpt-image-1" or "openai/dall-e-3").' };
|
||||
}
|
||||
|
||||
// Check if model exists in available models (optional - provides helpful info if available)
|
||||
const model = this.models.find(m => m.fullId === modelId);
|
||||
|
||||
// Update the settings
|
||||
this.aiSettings.updateSettings({ imageModel: modelId });
|
||||
|
||||
let response = `✅ Successfully configured image generation!\n\n`;
|
||||
response += `**Image Model**: ${modelId}\n`;
|
||||
|
||||
if (model?.name) {
|
||||
response += `**Name**: ${model.name}\n`;
|
||||
}
|
||||
|
||||
if (model?.description) {
|
||||
response += `**Description**: ${model.description}\n`;
|
||||
}
|
||||
|
||||
response += `\nThe generate_image tool is now available and ready to use. You can generate images by calling the generate_image tool with a detailed text prompt.`;
|
||||
|
||||
return { content: response };
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { Tool } from "./Tool";
|
||||
import type { Tool, ToolResult } from "./Tool";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import { ShakespeareAdapter } from "../deploy";
|
||||
import type { NostrSigner } from "@nostrify/nostrify";
|
||||
@@ -28,7 +28,7 @@ export class DeployProjectTool implements Tool<DeployProjectParams> {
|
||||
this.projectId = projectId;
|
||||
}
|
||||
|
||||
async execute(args: DeployProjectParams): Promise<string> {
|
||||
async execute(args: DeployProjectParams): Promise<ToolResult> {
|
||||
try {
|
||||
// Use provided deployServer or default to shakespeare.wtf
|
||||
const deployServer = args.deployServer || "shakespeare.wtf";
|
||||
@@ -59,7 +59,9 @@ export class DeployProjectTool implements Tool<DeployProjectParams> {
|
||||
projectPath: this.cwd,
|
||||
});
|
||||
|
||||
return `✅ Successfully deployed project!\n\n🌐 Live URL: ${result.url}\n\n🚀 Your project is now live and accessible to anyone with the URL!`;
|
||||
return {
|
||||
content: `✅ Successfully deployed project!\n\n🌐 Live URL: ${result.url}\n\n🚀 Your project is now live and accessible to anyone with the URL!`
|
||||
};
|
||||
} catch (error) {
|
||||
throw new Error(`❌ Deployment failed: ${String(error)}`);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,305 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { GenerateImageTool } from './GenerateImageTool';
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
// Mock the createAIClient function
|
||||
vi.mock('@/lib/ai-client', () => ({
|
||||
createAIClient: vi.fn(),
|
||||
}));
|
||||
|
||||
import { createAIClient } from '@/lib/ai-client';
|
||||
|
||||
describe('GenerateImageTool', () => {
|
||||
let mockFS: JSRuntimeFS;
|
||||
let mockProvider: AIProvider;
|
||||
let mockOpenAI: {
|
||||
images: { generate: ReturnType<typeof vi.fn> };
|
||||
chat: { completions: { create: ReturnType<typeof vi.fn> } };
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
mockFS = {
|
||||
writeFile: vi.fn(),
|
||||
mkdir: vi.fn(),
|
||||
stat: vi.fn().mockRejectedValue(new Error('ENOENT')), // Directory doesn't exist by default
|
||||
} as unknown as JSRuntimeFS;
|
||||
|
||||
mockProvider = {
|
||||
id: 'openai',
|
||||
name: 'OpenAI',
|
||||
baseURL: 'https://api.openai.com/v1',
|
||||
apiKey: 'test-key',
|
||||
};
|
||||
|
||||
// Create mock OpenAI client
|
||||
mockOpenAI = {
|
||||
images: {
|
||||
generate: vi.fn(),
|
||||
},
|
||||
chat: {
|
||||
completions: {
|
||||
create: vi.fn(),
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// Mock createAIClient to return our mock
|
||||
(createAIClient as ReturnType<typeof vi.fn>).mockReturnValue(mockOpenAI);
|
||||
});
|
||||
|
||||
it('should have correct description', () => {
|
||||
const tool = new GenerateImageTool(
|
||||
mockFS,
|
||||
'/tmp',
|
||||
mockProvider,
|
||||
'dall-e-3',
|
||||
'image',
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
|
||||
expect(tool.description).toBe(
|
||||
'Generate an image from a text prompt and save it to the virtual filesystem'
|
||||
);
|
||||
});
|
||||
|
||||
it('should validate prompt parameter', () => {
|
||||
const tool = new GenerateImageTool(
|
||||
mockFS,
|
||||
'/tmp',
|
||||
mockProvider,
|
||||
'dall-e-3',
|
||||
'image',
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
|
||||
const result = tool.inputSchema.safeParse({ prompt: 'a beautiful sunset' });
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('should reject missing prompt', () => {
|
||||
const tool = new GenerateImageTool(
|
||||
mockFS,
|
||||
'/tmp',
|
||||
mockProvider,
|
||||
'dall-e-3',
|
||||
'image',
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
|
||||
const result = tool.inputSchema.safeParse({});
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it('should generate image with standard OpenAI provider using image mode', async () => {
|
||||
const tool = new GenerateImageTool(
|
||||
mockFS,
|
||||
'/tmp',
|
||||
mockProvider,
|
||||
'dall-e-3',
|
||||
'image',
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
|
||||
// Mock the image generation API response with b64_json
|
||||
const mockImageData = new Uint8Array([1, 2, 3, 4]);
|
||||
const base64Data = btoa(String.fromCharCode(...mockImageData));
|
||||
|
||||
mockOpenAI.images.generate.mockResolvedValue({
|
||||
data: [{ b64_json: base64Data }],
|
||||
});
|
||||
|
||||
const result = await tool.execute({ prompt: 'a beautiful sunset' });
|
||||
|
||||
expect(result.content).toMatch(/^Generated image: \/tmp\/generated-\d+\.png$/);
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||
expect.stringMatching(/^\/tmp\/generated-\d+\.png$/),
|
||||
expect.any(Uint8Array)
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle models with chat mode for image generation', async () => {
|
||||
const openRouterProvider: AIProvider = {
|
||||
id: 'openrouter',
|
||||
name: 'OpenRouter',
|
||||
baseURL: 'https://openrouter.ai/api/v1',
|
||||
apiKey: 'test-key',
|
||||
};
|
||||
|
||||
const tool = new GenerateImageTool(
|
||||
mockFS,
|
||||
'/tmp',
|
||||
openRouterProvider,
|
||||
'flux-1.1-pro',
|
||||
'chat', // Use chat mode for image generation
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
|
||||
// Create a data URI with base64 encoded image data
|
||||
const mockImageData = new Uint8Array([1, 2, 3, 4]);
|
||||
const base64Data = btoa(String.fromCharCode(...mockImageData));
|
||||
const dataUri = `data:image/png;base64,${base64Data}`;
|
||||
|
||||
mockOpenAI.chat.completions.create.mockResolvedValue({
|
||||
choices: [
|
||||
{
|
||||
message: {
|
||||
images: [
|
||||
{
|
||||
type: 'image_url',
|
||||
image_url: { url: dataUri },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const result = await tool.execute({ prompt: 'a beautiful sunset' });
|
||||
|
||||
expect(result.content).toMatch(/^Generated image: \/tmp\/generated-\d+\.png$/);
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||
expect.stringMatching(/^\/tmp\/generated-\d+\.png$/),
|
||||
expect.any(Uint8Array)
|
||||
);
|
||||
});
|
||||
|
||||
it('should throw error when no image data is returned', async () => {
|
||||
const tool = new GenerateImageTool(
|
||||
mockFS,
|
||||
'/tmp',
|
||||
mockProvider,
|
||||
'dall-e-3',
|
||||
'image',
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
|
||||
mockOpenAI.images.generate.mockResolvedValue({
|
||||
data: [],
|
||||
});
|
||||
|
||||
await expect(tool.execute({ prompt: 'test' })).rejects.toThrow(
|
||||
'No image data returned from the API'
|
||||
);
|
||||
});
|
||||
|
||||
it('should throw error when chat mode returns invalid response', async () => {
|
||||
const openRouterProvider: AIProvider = {
|
||||
id: 'openrouter',
|
||||
name: 'OpenRouter',
|
||||
baseURL: 'https://openrouter.ai/api/v1',
|
||||
apiKey: 'test-key',
|
||||
};
|
||||
|
||||
const tool = new GenerateImageTool(
|
||||
mockFS,
|
||||
'/tmp',
|
||||
openRouterProvider,
|
||||
'flux-1.1-pro',
|
||||
'chat', // Use chat mode
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
|
||||
mockOpenAI.chat.completions.create.mockResolvedValue({
|
||||
choices: [
|
||||
{
|
||||
message: {
|
||||
content: 'Invalid response',
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await expect(tool.execute({ prompt: 'test' })).rejects.toThrow(
|
||||
'Failed to generate image: Invalid response format from the API'
|
||||
);
|
||||
});
|
||||
|
||||
it('should determine file extension from data URI for chat mode', async () => {
|
||||
const openRouterProvider: AIProvider = {
|
||||
id: 'openrouter',
|
||||
name: 'OpenRouter',
|
||||
baseURL: 'https://openrouter.ai/api/v1',
|
||||
apiKey: 'test-key',
|
||||
};
|
||||
|
||||
const tool = new GenerateImageTool(
|
||||
mockFS,
|
||||
'/tmp',
|
||||
openRouterProvider,
|
||||
'flux-1.1-pro',
|
||||
'chat', // Use chat mode
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
|
||||
// Create a data URI with JPEG format
|
||||
const mockImageData = new Uint8Array([1, 2, 3, 4]);
|
||||
const base64Data = btoa(String.fromCharCode(...mockImageData));
|
||||
const dataUri = `data:image/jpeg;base64,${base64Data}`;
|
||||
|
||||
mockOpenAI.chat.completions.create.mockResolvedValue({
|
||||
choices: [
|
||||
{
|
||||
message: {
|
||||
images: [
|
||||
{
|
||||
type: 'image_url',
|
||||
image_url: { url: dataUri },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const result = await tool.execute({ prompt: 'a beautiful sunset' });
|
||||
|
||||
expect(result.content).toMatch(/^Generated image: \/tmp\/generated-\d+\.jpeg$/);
|
||||
});
|
||||
|
||||
it('should throw error when chat mode returns invalid data URI', async () => {
|
||||
const openRouterProvider: AIProvider = {
|
||||
id: 'openrouter',
|
||||
name: 'OpenRouter',
|
||||
baseURL: 'https://openrouter.ai/api/v1',
|
||||
apiKey: 'test-key',
|
||||
};
|
||||
|
||||
const tool = new GenerateImageTool(
|
||||
mockFS,
|
||||
'/tmp',
|
||||
openRouterProvider,
|
||||
'flux-1.1-pro',
|
||||
'chat', // Use chat mode
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
|
||||
mockOpenAI.chat.completions.create.mockResolvedValue({
|
||||
choices: [
|
||||
{
|
||||
message: {
|
||||
images: [
|
||||
{
|
||||
type: 'image_url',
|
||||
image_url: { url: 'https://example.com/image.png' },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await expect(tool.execute({ prompt: 'test' })).rejects.toThrow(
|
||||
'Invalid data URI format'
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,184 @@
|
||||
import { z } from 'zod';
|
||||
import type { Tool, ToolResult } from './Tool';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
import type { NUser } from '@nostrify/react/login';
|
||||
import { createAIClient } from '@/lib/ai-client';
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
import { proxyUrl } from '../proxyUrl';
|
||||
|
||||
interface GenerateImageParams {
|
||||
prompt: string;
|
||||
output_format?: "png" | "jpeg" | "webp";
|
||||
output_compression?: number;
|
||||
size?: "auto" | "1024x1024" | "1536x1024" | "1024x1536" | "256x256" | "512x512" | "1792x1024" | "1024x1792";
|
||||
}
|
||||
|
||||
export type ImageGenerationMode = 'chat' | 'image';
|
||||
|
||||
export class GenerateImageTool implements Tool<GenerateImageParams> {
|
||||
readonly description = 'Generate an image from a text prompt and save it to the virtual filesystem';
|
||||
|
||||
readonly inputSchema = z.object({
|
||||
prompt: z.string().describe('A detailed text description of the image to generate'),
|
||||
output_format: z.enum(["png", "jpeg", "webp"]).optional().describe('Output format for the image (e.g., "png", "jpeg", "webp"). Support varies by model - leave blank if unsure'),
|
||||
output_compression: z.number().min(1).max(100).optional().describe('Compression quality for the image (0 to 100). Only applicable for "jpeg" and "webp" formats'),
|
||||
size: z.enum(["auto", "1024x1024", "1536x1024", "1024x1536", "256x256", "512x512", "1792x1024", "1024x1792"]).optional().describe('Size of the generated image (e.g., "1024x1024", "1536x1024"). Support varies by model - leave blank if unsure'),
|
||||
});
|
||||
|
||||
constructor(
|
||||
private fs: JSRuntimeFS,
|
||||
private tmpPath: string,
|
||||
private provider: AIProvider,
|
||||
private model: string,
|
||||
private mode: ImageGenerationMode,
|
||||
private user?: NUser,
|
||||
private corsProxy?: string,
|
||||
) {}
|
||||
|
||||
async execute(args: GenerateImageParams): Promise<ToolResult> {
|
||||
const { prompt, output_format, output_compression, size } = args;
|
||||
|
||||
try {
|
||||
const client = createAIClient(this.provider, this.user, this.corsProxy);
|
||||
|
||||
let cost: number | undefined;
|
||||
let imageData: Uint8Array;
|
||||
let extension = output_format ?? 'png';
|
||||
|
||||
// Use chat completions endpoint for models that support image output modality
|
||||
if (this.mode === 'chat') {
|
||||
const response = await client.chat.completions.create({
|
||||
model: this.model,
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
content: prompt,
|
||||
},
|
||||
],
|
||||
modalities: ['image'] as never[], // Type assertion needed as OpenAI SDK doesn't have this typed
|
||||
});
|
||||
|
||||
// Default extension for chat models is png (output_format is ignored)
|
||||
extension = 'png';
|
||||
|
||||
// Extract cost from response
|
||||
const { usage } = response;
|
||||
if (usage && 'cost' in usage && typeof usage.cost === 'number') {
|
||||
cost = usage.cost;
|
||||
}
|
||||
|
||||
// Extract image data URI from response
|
||||
const message = response.choices[0]?.message;
|
||||
if (!message) {
|
||||
throw new Error('No message returned from the API');
|
||||
}
|
||||
|
||||
const result = z.object({
|
||||
images: z.object({
|
||||
type: z.literal('image_url'),
|
||||
image_url: z.object({
|
||||
url: z.string(),
|
||||
}),
|
||||
}).array().min(1),
|
||||
}).safeParse(message);
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error('Invalid response format from the API');
|
||||
}
|
||||
|
||||
const dataUri = result.data.images[0].image_url.url;
|
||||
|
||||
// Parse data URI: data:image/png;base64,iVBORw0KGgoAAAANS...
|
||||
const dataUriMatch = dataUri.match(/^data:image\/([^;]+);base64,(.+)$/);
|
||||
if (!dataUriMatch) {
|
||||
throw new Error('Invalid data URI format');
|
||||
}
|
||||
|
||||
if (dataUriMatch[1] === "png" || dataUriMatch[1] === "jpeg" || dataUriMatch[1] === "webp") {
|
||||
extension = dataUriMatch[1];
|
||||
}
|
||||
|
||||
const base64Data = dataUriMatch[2];
|
||||
|
||||
// Decode base64 to bytes
|
||||
const binaryString = atob(base64Data);
|
||||
imageData = new Uint8Array(binaryString.length);
|
||||
for (let i = 0; i < binaryString.length; i++) {
|
||||
imageData[i] = binaryString.charCodeAt(i);
|
||||
}
|
||||
} else {
|
||||
// Standard OpenAI image generation
|
||||
const response = await client.images.generate({
|
||||
model: this.model,
|
||||
prompt,
|
||||
output_format,
|
||||
output_compression,
|
||||
size,
|
||||
});
|
||||
|
||||
// Extract cost from response
|
||||
const { usage } = response;
|
||||
if (usage && 'cost' in usage && typeof usage.cost === 'number') {
|
||||
cost = usage.cost;
|
||||
}
|
||||
|
||||
const firstImage = response.data?.[0];
|
||||
if (!firstImage) {
|
||||
throw new Error('No image data returned from the API');
|
||||
}
|
||||
|
||||
// Check if we got b64_json or url
|
||||
if (firstImage.b64_json) {
|
||||
// Decode base64 to bytes
|
||||
const binaryString = atob(firstImage.b64_json);
|
||||
imageData = new Uint8Array(binaryString.length);
|
||||
for (let i = 0; i < binaryString.length; i++) {
|
||||
imageData[i] = binaryString.charCodeAt(i);
|
||||
}
|
||||
} else if (firstImage.url) {
|
||||
// Fetch the image from the URL
|
||||
const imageUrl = this.corsProxy ? proxyUrl(this.corsProxy, firstImage.url) : firstImage.url;
|
||||
const imageResponse = await fetch(imageUrl);
|
||||
|
||||
if (!imageResponse.ok) {
|
||||
throw new Error(`Failed to fetch image from URL: ${imageResponse.status} ${imageResponse.statusText}`);
|
||||
}
|
||||
|
||||
const arrayBuffer = await imageResponse.arrayBuffer();
|
||||
imageData = new Uint8Array(arrayBuffer);
|
||||
|
||||
// Try to determine extension from content-type header
|
||||
const contentType = imageResponse.headers.get('content-type');
|
||||
if (contentType) {
|
||||
const match = contentType.match(/image\/([^;]+)/);
|
||||
if (match && (match[1] === 'png' || match[1] === 'jpeg' || match[1] === 'webp')) {
|
||||
extension = match[1];
|
||||
}
|
||||
}
|
||||
} else {
|
||||
throw new Error('No base64 image data or URL returned from the API');
|
||||
}
|
||||
}
|
||||
|
||||
// Generate unique filename
|
||||
const timestamp = Date.now();
|
||||
const filename = `generated-${timestamp}.${extension}`;
|
||||
const filepath = `${this.tmpPath}/${filename}`;
|
||||
|
||||
// Ensure tmp directory exists
|
||||
try {
|
||||
await this.fs.stat(this.tmpPath);
|
||||
} catch {
|
||||
await this.fs.mkdir(this.tmpPath, { recursive: true });
|
||||
}
|
||||
|
||||
// Write image to VFS
|
||||
await this.fs.writeFile(filepath, imageData);
|
||||
|
||||
return { content: `Generated image: ${filepath}`, cost };
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
throw new Error(`Failed to generate image: ${errorMessage}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -76,8 +76,8 @@ describe('GitCommitTool', () => {
|
||||
dir: '/test/project',
|
||||
message: 'Add new feature',
|
||||
});
|
||||
expect(result).toContain('✅ Successfully committed 2 files (abcd123)');
|
||||
expect(result).toContain('Add new feature');
|
||||
expect(result.content).toContain('✅ Successfully committed 2 files (abcd123)');
|
||||
expect(result.content).toContain('Add new feature');
|
||||
});
|
||||
|
||||
it('should handle empty commit message', async () => {
|
||||
@@ -121,8 +121,8 @@ describe('GitCommitTool', () => {
|
||||
expect(mockGitInstance.commit).toHaveBeenCalledWith(expect.objectContaining({
|
||||
message: specialMessage,
|
||||
}));
|
||||
expect(result).toContain('✅ Successfully committed');
|
||||
expect(result).toContain(specialMessage);
|
||||
expect(result.content).toContain('✅ Successfully committed');
|
||||
expect(result.content).toContain(specialMessage);
|
||||
});
|
||||
|
||||
it('should handle multiline commit message', async () => {
|
||||
@@ -136,8 +136,8 @@ describe('GitCommitTool', () => {
|
||||
const result = await tool.execute({ message: multilineMessage });
|
||||
|
||||
expect(mockGitInstance.commit).toHaveBeenCalled();
|
||||
expect(result).toContain('✅ Successfully committed');
|
||||
expect(result).toContain('Add new feature');
|
||||
expect(result.content).toContain('✅ Successfully committed');
|
||||
expect(result.content).toContain('Add new feature');
|
||||
});
|
||||
|
||||
it('should handle no changes to commit', async () => {
|
||||
@@ -152,7 +152,7 @@ describe('GitCommitTool', () => {
|
||||
|
||||
const result = await tool.execute({ message: 'Update documentation' });
|
||||
|
||||
expect(result).toContain('ℹ️ No changes to commit. Working tree is clean.');
|
||||
expect(result.content).toContain('ℹ️ No changes to commit. Working tree is clean.');
|
||||
expect(mockGitInstance.commit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -165,10 +165,10 @@ describe('GitCommitTool', () => {
|
||||
|
||||
const result = await tool.execute({ message: 'Update documentation' });
|
||||
|
||||
expect(result).toContain('📝 Commit: "Update documentation"');
|
||||
expect(result).toContain('🔗 Hash:');
|
||||
expect(result).toContain('🌿 Branch:');
|
||||
expect(result).toContain('📊 Changes:');
|
||||
expect(result.content).toContain('📝 Commit: "Update documentation"');
|
||||
expect(result.content).toContain('🔗 Hash:');
|
||||
expect(result.content).toContain('🌿 Branch:');
|
||||
expect(result.content).toContain('📊 Changes:');
|
||||
});
|
||||
|
||||
|
||||
@@ -183,7 +183,7 @@ describe('GitCommitTool', () => {
|
||||
const longMessage = 'A'.repeat(1000); // Very long commit message
|
||||
const result = await tool.execute({ message: longMessage });
|
||||
|
||||
expect(result).toContain('✅ Successfully committed');
|
||||
expect(result.content).toContain('✅ Successfully committed');
|
||||
});
|
||||
|
||||
it('should error when HEAD is detached (currentBranch returns null)', async () => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { z } from "zod";
|
||||
import { Git } from "../git";
|
||||
|
||||
import type { Tool } from "./Tool";
|
||||
import type { Tool, ToolResult } from "./Tool";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
|
||||
interface GitCommitParams {
|
||||
@@ -25,7 +25,7 @@ export class GitCommitTool implements Tool<GitCommitParams> {
|
||||
this.cwd = cwd;
|
||||
}
|
||||
|
||||
async execute(args: GitCommitParams): Promise<string> {
|
||||
async execute(args: GitCommitParams): Promise<ToolResult> {
|
||||
const { message } = args;
|
||||
|
||||
try {
|
||||
@@ -75,7 +75,7 @@ export class GitCommitTool implements Tool<GitCommitParams> {
|
||||
});
|
||||
|
||||
if (changedFiles.length === 0) {
|
||||
return `ℹ️ No changes to commit. Working tree is clean.`;
|
||||
return { content: `ℹ️ No changes to commit. Working tree is clean.` };
|
||||
}
|
||||
|
||||
// Add all changed files to staging
|
||||
@@ -133,7 +133,7 @@ export class GitCommitTool implements Tool<GitCommitParams> {
|
||||
if (modifiedFiles > 0) details += ` • ${modifiedFiles} file${modifiedFiles !== 1 ? 's' : ''} modified\n`;
|
||||
if (deletedFiles > 0) details += ` • ${deletedFiles} file${deletedFiles !== 1 ? 's' : ''} deleted\n`;
|
||||
|
||||
return `${summary}\n\n${details}`;
|
||||
return { content: `${summary}\n\n${details}` };
|
||||
} catch (error) {
|
||||
throw new Error(`❌ Error committing changes: ${String(error)}`);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Tool } from './Tool';
|
||||
import type { Tool, ToolResult } from './Tool';
|
||||
import type { MCPClient } from '@/lib/MCPClient';
|
||||
|
||||
/**
|
||||
@@ -19,8 +19,9 @@ export class MCPTool implements Tool<Record<string, unknown>> {
|
||||
this.originalToolName = originalToolName;
|
||||
}
|
||||
|
||||
async execute(args: Record<string, unknown>): Promise<string> {
|
||||
return await this.client.callTool(this.originalToolName, args);
|
||||
async execute(args: Record<string, unknown>): Promise<ToolResult> {
|
||||
const content = await this.client.callTool(this.originalToolName, args);
|
||||
return { content };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { z } from "zod";
|
||||
import { NPool, NRelay1, type NostrEvent } from '@nostrify/nostrify';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
import type { Tool } from "./Tool";
|
||||
import type { Tool, ToolResult } from "./Tool";
|
||||
|
||||
interface NostrFetchEventParams {
|
||||
identifier: string;
|
||||
@@ -26,7 +26,7 @@ export class NostrFetchEventTool implements Tool<NostrFetchEventParams> {
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
// Reject nsec for security reasons
|
||||
if (decoded.type === 'nsec') {
|
||||
ctx.addIssue({
|
||||
@@ -36,7 +36,7 @@ export class NostrFetchEventTool implements Tool<NostrFetchEventParams> {
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
// Accept npub, nprofile, naddr, note, nevent
|
||||
if (!['npub', 'nprofile', 'naddr', 'note', 'nevent'].includes(decoded.type)) {
|
||||
ctx.addIssue({
|
||||
@@ -52,7 +52,7 @@ export class NostrFetchEventTool implements Tool<NostrFetchEventParams> {
|
||||
),
|
||||
});
|
||||
|
||||
async execute(args: NostrFetchEventParams): Promise<string> {
|
||||
async execute(args: NostrFetchEventParams): Promise<ToolResult> {
|
||||
const { identifier } = args;
|
||||
|
||||
const decoded = nip19.decode(identifier);
|
||||
@@ -169,12 +169,12 @@ export class NostrFetchEventTool implements Tool<NostrFetchEventParams> {
|
||||
// Special handling for specific kinds
|
||||
if (event.kind === 30817) {
|
||||
// Kind 30817 is a NIP document, return just the content
|
||||
return event.content;
|
||||
return { content: event.content };
|
||||
}
|
||||
|
||||
|
||||
// For other kinds, return the full event JSON
|
||||
return JSON.stringify(event, null, 2);
|
||||
|
||||
return { content: JSON.stringify(event, null, 2) };
|
||||
|
||||
} catch (error) {
|
||||
throw new Error(`Error fetching event: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
} finally {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { Tool } from "./Tool";
|
||||
import type { Tool, ToolResult } from "./Tool";
|
||||
import { KindGenerator, type KindRange } from "../KindGenerator";
|
||||
import { NIPsClient } from "../NIPsClient";
|
||||
|
||||
@@ -26,7 +26,7 @@ export class NostrGenerateKindTool implements Tool<NostrGenerateKindParams> {
|
||||
});
|
||||
}
|
||||
|
||||
async execute(args: NostrGenerateKindParams): Promise<string> {
|
||||
async execute(args: NostrGenerateKindParams): Promise<ToolResult> {
|
||||
const { range } = args;
|
||||
|
||||
try {
|
||||
@@ -39,7 +39,9 @@ export class NostrGenerateKindTool implements Tool<NostrGenerateKindParams> {
|
||||
|
||||
const rangeInfo = KindGenerator.getKindRangeInfo(range);
|
||||
|
||||
return `Generated unused kind: ${availableKind}\n\nRange: ${rangeInfo.name} (${rangeInfo.min}-${rangeInfo.max})\nDescription: ${rangeInfo.description}\n\nThis kind number is currently not used by any official NIP.`;
|
||||
return {
|
||||
content: `Generated unused kind: ${availableKind}\n\nRange: ${rangeInfo.name} (${rangeInfo.min}-${rangeInfo.max})\nDescription: ${rangeInfo.description}\n\nThis kind number is currently not used by any official NIP.`
|
||||
};
|
||||
} catch (error) {
|
||||
throw new Error(`Error generating kind: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
|
||||
@@ -78,7 +78,7 @@ describe('NostrPublishEventsTool', () => {
|
||||
events: [{}],
|
||||
});
|
||||
|
||||
const parsed = JSON.parse(result);
|
||||
const parsed = JSON.parse(result.content);
|
||||
expect(parsed.success).toBe(true);
|
||||
expect(parsed.pubkey).toBeDefined();
|
||||
expect(parsed.events_published).toBe(2); // kind 0 + 1 user event
|
||||
@@ -95,7 +95,7 @@ describe('NostrPublishEventsTool', () => {
|
||||
],
|
||||
});
|
||||
|
||||
const parsed = JSON.parse(result);
|
||||
const parsed = JSON.parse(result.content);
|
||||
expect(parsed.success).toBe(true);
|
||||
expect(parsed.events_published).toBe(3); // kind 0 + 2 user events
|
||||
expect(parsed.events[1].kind).toBe(1);
|
||||
@@ -110,7 +110,7 @@ describe('NostrPublishEventsTool', () => {
|
||||
relays: customRelays,
|
||||
});
|
||||
|
||||
const parsed = JSON.parse(result);
|
||||
const parsed = JSON.parse(result.content);
|
||||
expect(parsed.relays).toEqual(customRelays);
|
||||
});
|
||||
|
||||
@@ -120,7 +120,7 @@ describe('NostrPublishEventsTool', () => {
|
||||
events: [{ kind: 1, content: longContent }],
|
||||
});
|
||||
|
||||
const parsed = JSON.parse(result);
|
||||
const parsed = JSON.parse(result.content);
|
||||
expect(parsed.events[1].content).toHaveLength(103); // 100 chars + '...'
|
||||
expect(parsed.events[1].content).toMatch(/^a+\.\.\.$/);
|
||||
});
|
||||
@@ -143,7 +143,7 @@ describe('NostrPublishEventsTool', () => {
|
||||
events: [{ kind: 1, content: 'test', created_at: customTime }],
|
||||
});
|
||||
|
||||
const parsed = JSON.parse(result);
|
||||
const parsed = JSON.parse(result.content);
|
||||
expect(parsed.success).toBe(true);
|
||||
});
|
||||
|
||||
@@ -155,7 +155,7 @@ describe('NostrPublishEventsTool', () => {
|
||||
],
|
||||
});
|
||||
|
||||
const parsed = JSON.parse(result);
|
||||
const parsed = JSON.parse(result.content);
|
||||
expect(parsed.success).toBe(true);
|
||||
expect(parsed.events_published).toBe(2); // Only the 2 user events, no fallback
|
||||
expect(parsed.events[0].kind).toBe(0); // User's kind 0
|
||||
@@ -170,7 +170,7 @@ describe('NostrPublishEventsTool', () => {
|
||||
],
|
||||
});
|
||||
|
||||
const parsed = JSON.parse(result);
|
||||
const parsed = JSON.parse(result.content);
|
||||
expect(parsed.success).toBe(true);
|
||||
expect(parsed.events_published).toBe(3); // Fallback kind 0 + 2 user events
|
||||
expect(parsed.events[0].kind).toBe(0); // Fallback profile event
|
||||
|
||||
@@ -2,7 +2,7 @@ import { z } from "zod";
|
||||
import { NPool, NRelay1, type NostrEvent } from '@nostrify/nostrify';
|
||||
import { generateSecretKey, getPublicKey, finalizeEvent } from 'nostr-tools';
|
||||
|
||||
import type { Tool } from "./Tool";
|
||||
import type { Tool, ToolResult } from "./Tool";
|
||||
|
||||
interface NostrPublishEventsParams {
|
||||
events: Array<{
|
||||
@@ -29,7 +29,7 @@ export class NostrPublishEventsTool implements Tool<NostrPublishEventsParams> {
|
||||
relays: z.array(z.string().url()).optional().describe('Optional array of relay URLs to publish to (default: hardcoded relay list)'),
|
||||
});
|
||||
|
||||
async execute(args: NostrPublishEventsParams): Promise<string> {
|
||||
async execute(args: NostrPublishEventsParams): Promise<ToolResult> {
|
||||
const { events: partialEvents, relays } = args;
|
||||
|
||||
// Default relays if none provided
|
||||
@@ -114,7 +114,7 @@ export class NostrPublishEventsTool implements Tool<NostrPublishEventsParams> {
|
||||
})),
|
||||
};
|
||||
|
||||
return JSON.stringify(summary, null, 2);
|
||||
return { content: JSON.stringify(summary, null, 2) };
|
||||
} catch (error) {
|
||||
throw new Error(`Error publishing events: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
} finally {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { Tool } from "./Tool";
|
||||
import type { Tool, ToolResult } from "./Tool";
|
||||
import { NostrbookClient } from "../NostrbookClient";
|
||||
import { HTTPError } from "../HTTPError";
|
||||
|
||||
@@ -23,12 +23,12 @@ export class NostrReadKindTool implements Tool<NostrReadKindParams> {
|
||||
});
|
||||
}
|
||||
|
||||
async execute(args: NostrReadKindParams): Promise<string> {
|
||||
async execute(args: NostrReadKindParams): Promise<ToolResult> {
|
||||
const { kind } = args;
|
||||
|
||||
try {
|
||||
const text = await this.nostrbookClient.readKind(kind);
|
||||
return text;
|
||||
return { content: text };
|
||||
} catch (error) {
|
||||
if (error instanceof HTTPError && error.response.status === 404) {
|
||||
throw new Error(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { Tool } from "./Tool";
|
||||
import type { Tool, ToolResult } from "./Tool";
|
||||
import { NIPsClient } from "../NIPsClient";
|
||||
import { HTTPError } from "../HTTPError";
|
||||
|
||||
@@ -30,12 +30,12 @@ export class NostrReadNipTool implements Tool<NostrReadNipParams> {
|
||||
});
|
||||
}
|
||||
|
||||
async execute(args: NostrReadNipParams): Promise<string> {
|
||||
async execute(args: NostrReadNipParams): Promise<ToolResult> {
|
||||
const { nip } = args;
|
||||
|
||||
try {
|
||||
const text = await this.nipsClient.readNip(nip);
|
||||
return text;
|
||||
return { content: text };
|
||||
} catch (error) {
|
||||
if (error instanceof HTTPError && error.response.status === 404) {
|
||||
throw new Error(
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Tool } from "./Tool";
|
||||
import type { Tool, ToolResult } from "./Tool";
|
||||
import { NIPsClient } from "../NIPsClient";
|
||||
|
||||
export class NostrReadNipsIndexTool implements Tool<void> {
|
||||
@@ -12,10 +12,10 @@ export class NostrReadNipsIndexTool implements Tool<void> {
|
||||
});
|
||||
}
|
||||
|
||||
async execute(): Promise<string> {
|
||||
async execute(): Promise<ToolResult> {
|
||||
try {
|
||||
const text = await this.nipsClient.readIndex();
|
||||
return text;
|
||||
return { content: text };
|
||||
} catch (error) {
|
||||
throw new Error(`Error reading NIPs index: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { Tool } from "./Tool";
|
||||
import type { Tool, ToolResult } from "./Tool";
|
||||
import { NostrbookClient } from "../NostrbookClient";
|
||||
|
||||
interface NostrReadProtocolParams {
|
||||
@@ -22,12 +22,12 @@ export class NostrReadProtocolTool implements Tool<NostrReadProtocolParams> {
|
||||
});
|
||||
}
|
||||
|
||||
async execute(args: NostrReadProtocolParams): Promise<string> {
|
||||
async execute(args: NostrReadProtocolParams): Promise<ToolResult> {
|
||||
const { doc } = args;
|
||||
|
||||
try {
|
||||
const text = await this.nostrbookClient.readProtocol(doc);
|
||||
return text;
|
||||
return { content: text };
|
||||
} catch (error) {
|
||||
throw new Error(`Error reading protocol doc "${doc}": ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { Tool } from "./Tool";
|
||||
import type { Tool, ToolResult } from "./Tool";
|
||||
import { NostrbookClient } from "../NostrbookClient";
|
||||
import { HTTPError } from "../HTTPError";
|
||||
|
||||
@@ -23,12 +23,12 @@ export class NostrReadTagTool implements Tool<NostrReadTagParams> {
|
||||
});
|
||||
}
|
||||
|
||||
async execute(args: NostrReadTagParams): Promise<string> {
|
||||
async execute(args: NostrReadTagParams): Promise<ToolResult> {
|
||||
const { tag } = args;
|
||||
|
||||
try {
|
||||
const text = await this.nostrbookClient.readTag(tag);
|
||||
return text;
|
||||
return { content: text };
|
||||
} catch (error) {
|
||||
if (error instanceof HTTPError && error.response.status === 404) {
|
||||
throw new Error(
|
||||
|
||||
@@ -70,8 +70,8 @@ describe('NpmAddPackageTool', () => {
|
||||
expect.stringContaining('"lodash": "^4.17.21"'),
|
||||
'utf8'
|
||||
);
|
||||
expect(result).toContain('✅ Successfully added [email protected]');
|
||||
expect(result).toContain('Updated: package.json');
|
||||
expect(result.content).toContain('✅ Successfully added [email protected]');
|
||||
expect(result.content).toContain('Updated: package.json');
|
||||
});
|
||||
|
||||
it('should add package with specific version', async () => {
|
||||
@@ -105,7 +105,7 @@ describe('NpmAddPackageTool', () => {
|
||||
expect.stringContaining('"lodash": "^4.17.20"'),
|
||||
'utf8'
|
||||
);
|
||||
expect(result).toContain('✅ Successfully added [email protected]');
|
||||
expect(result.content).toContain('✅ Successfully added [email protected]');
|
||||
});
|
||||
|
||||
it('should add dev dependency', async () => {
|
||||
@@ -146,7 +146,7 @@ describe('NpmAddPackageTool', () => {
|
||||
expect(writtenPackageJson.devDependencies.typescript).toBe('^5.0.0');
|
||||
expect(writtenPackageJson.dependencies?.typescript).toBeUndefined();
|
||||
|
||||
expect(result).toContain('Development dependency');
|
||||
expect(result.content).toContain('Development dependency');
|
||||
});
|
||||
|
||||
it('should move package from dependencies to devDependencies', async () => {
|
||||
@@ -183,7 +183,7 @@ describe('NpmAddPackageTool', () => {
|
||||
expect(writtenPackageJson.devDependencies.typescript).toBe('^5.0.0');
|
||||
// dependencies object should be empty or not contain typescript
|
||||
expect(writtenPackageJson.dependencies?.typescript).toBeUndefined();
|
||||
expect(result).toContain('✅ Successfully added');
|
||||
expect(result.content).toContain('✅ Successfully added');
|
||||
});
|
||||
|
||||
it('should handle package already installed', async () => {
|
||||
@@ -202,7 +202,7 @@ describe('NpmAddPackageTool', () => {
|
||||
// Should not fetch from registry when no version specified and package already installed
|
||||
expect(mockFetch).not.toHaveBeenCalled();
|
||||
expect(mockFS.writeFile).not.toHaveBeenCalled();
|
||||
expect(result).toContain('ℹ️ Package lodash is already installed in dependencies with version ^4.17.21.');
|
||||
expect(result.content).toContain('ℹ️ Package lodash is already installed in dependencies with version ^4.17.21.');
|
||||
});
|
||||
|
||||
it('should handle package already installed with specific version', async () => {
|
||||
@@ -230,7 +230,7 @@ describe('NpmAddPackageTool', () => {
|
||||
const result = await tool.execute({ name: 'lodash', version: '4.17.21' });
|
||||
|
||||
expect(mockFS.writeFile).not.toHaveBeenCalled();
|
||||
expect(result).toContain('ℹ️ Package [email protected] is already installed in dependencies.');
|
||||
expect(result.content).toContain('ℹ️ Package [email protected] is already installed in dependencies.');
|
||||
});
|
||||
|
||||
it('should handle missing package.json', async () => {
|
||||
@@ -295,7 +295,7 @@ describe('NpmAddPackageTool', () => {
|
||||
const dependencyKeys = Object.keys(writtenPackageJson.dependencies);
|
||||
|
||||
expect(dependencyKeys).toEqual(['axios', 'lodash', 'zlib']);
|
||||
expect(result).toContain('✅ Successfully added');
|
||||
expect(result.content).toContain('✅ Successfully added');
|
||||
});
|
||||
|
||||
it('should update package-lock.json when it exists', async () => {
|
||||
@@ -354,7 +354,7 @@ describe('NpmAddPackageTool', () => {
|
||||
license: 'MIT'
|
||||
});
|
||||
|
||||
expect(result).toContain('Updated: package.json, package-lock.json');
|
||||
expect(result.content).toContain('Updated: package.json, package-lock.json');
|
||||
});
|
||||
|
||||
it('should update package-lock.json for dev dependencies', async () => {
|
||||
@@ -413,7 +413,7 @@ describe('NpmAddPackageTool', () => {
|
||||
engines: { node: '>=14.17' }
|
||||
});
|
||||
|
||||
expect(result).toContain('Updated: package.json, package-lock.json');
|
||||
expect(result.content).toContain('Updated: package.json, package-lock.json');
|
||||
});
|
||||
|
||||
it('should move package between dependency types in package-lock.json', async () => {
|
||||
@@ -487,7 +487,7 @@ describe('NpmAddPackageTool', () => {
|
||||
dev: true
|
||||
});
|
||||
|
||||
expect(result).toContain('✅ Successfully added');
|
||||
expect(result.content).toContain('✅ Successfully added');
|
||||
});
|
||||
|
||||
it('should handle corrupted package-lock.json gracefully', async () => {
|
||||
@@ -516,8 +516,8 @@ describe('NpmAddPackageTool', () => {
|
||||
// Should not throw error, just log warning and continue
|
||||
const result = await tool.execute({ name: 'lodash' });
|
||||
|
||||
expect(result).toContain('✅ Successfully added [email protected]');
|
||||
expect(result).toContain('Updated: package.json'); // Should not mention package-lock.json
|
||||
expect(result.content).toContain('✅ Successfully added [email protected]');
|
||||
expect(result.content).toContain('Updated: package.json'); // Should not mention package-lock.json
|
||||
expect(mockFS.writeFile).toHaveBeenCalledTimes(1); // Only package.json should be written
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { Tool } from "./Tool";
|
||||
import type { Tool, ToolResult } from "./Tool";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
|
||||
interface NpmAddPackageParams {
|
||||
@@ -66,7 +66,7 @@ export class NpmAddPackageTool implements Tool<NpmAddPackageParams> {
|
||||
this.cwd = cwd;
|
||||
}
|
||||
|
||||
async execute(args: NpmAddPackageParams): Promise<string> {
|
||||
async execute(args: NpmAddPackageParams): Promise<ToolResult> {
|
||||
const { name, version, dev = false } = args;
|
||||
|
||||
try {
|
||||
@@ -95,7 +95,7 @@ export class NpmAddPackageTool implements Tool<NpmAddPackageParams> {
|
||||
// If no version is specified and package is already installed, it's a no-op
|
||||
if (!version && packageJson[dependencyKey]?.[name]) {
|
||||
const currentVersion = packageJson[dependencyKey][name];
|
||||
return `ℹ️ Package ${name} is already installed in ${dependencyKey} with version ${currentVersion}.`;
|
||||
return { content: `ℹ️ Package ${name} is already installed in ${dependencyKey} with version ${currentVersion}.` };
|
||||
}
|
||||
|
||||
// Determine version to use and fetch package metadata
|
||||
@@ -121,7 +121,7 @@ export class NpmAddPackageTool implements Tool<NpmAddPackageParams> {
|
||||
if (packageJson[dependencyKey]?.[name]) {
|
||||
const currentVersion = packageJson[dependencyKey][name];
|
||||
if (currentVersion === `^${targetVersion}`) {
|
||||
return `ℹ️ Package ${name}@${targetVersion} is already installed in ${dependencyKey}.`;
|
||||
return { content: `ℹ️ Package ${name}@${targetVersion} is already installed in ${dependencyKey}.` };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,7 +164,9 @@ export class NpmAddPackageTool implements Tool<NpmAddPackageParams> {
|
||||
// Update package-lock.json if it exists
|
||||
await this.updatePackageLock(name, targetVersion, packageMetadata, dev);
|
||||
|
||||
return `✅ Successfully added ${name}@${targetVersion} to ${dependencyKey}\n\n📦 Package: ${name}\n🏷️ Version: ^${targetVersion}\n📁 Type: ${dev ? 'Development dependency' : 'Production dependency'}\n📄 Updated: package.json${await this.packageLockExists() ? ', package-lock.json' : ''}`;
|
||||
return {
|
||||
content: `✅ Successfully added ${name}@${targetVersion} to ${dependencyKey}\n\n📦 Package: ${name}\n🏷️ Version: ^${targetVersion}\n📁 Type: ${dev ? 'Development dependency' : 'Production dependency'}\n📄 Updated: package.json${await this.packageLockExists() ? ', package-lock.json' : ''}`
|
||||
};
|
||||
} catch (error) {
|
||||
throw new Error(`❌ Error adding package ${name}: ${String(error)}`);
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ describe('NpmRemovePackageTool', () => {
|
||||
|
||||
expect(writtenPackageJson.dependencies.lodash).toBeUndefined();
|
||||
expect(writtenPackageJson.dependencies.axios).toBe('^1.0.0');
|
||||
expect(result).toContain('✅ Successfully removed lodash from dependencies');
|
||||
expect(result.content).toContain('✅ Successfully removed lodash from dependencies');
|
||||
});
|
||||
|
||||
it('should successfully remove package from devDependencies', async () => {
|
||||
@@ -77,7 +77,7 @@ describe('NpmRemovePackageTool', () => {
|
||||
expect(writtenPackageJson.devDependencies.typescript).toBeUndefined();
|
||||
expect(writtenPackageJson.devDependencies.eslint).toBe('^8.0.0');
|
||||
expect(writtenPackageJson.dependencies.react).toBe('^18.0.0');
|
||||
expect(result).toContain('✅ Successfully removed typescript from devDependencies');
|
||||
expect(result.content).toContain('✅ Successfully removed typescript from devDependencies');
|
||||
});
|
||||
|
||||
it('should remove empty dependencies object', async () => {
|
||||
@@ -97,7 +97,7 @@ describe('NpmRemovePackageTool', () => {
|
||||
const writtenPackageJson = JSON.parse(writtenContent);
|
||||
|
||||
expect(writtenPackageJson.dependencies).toBeUndefined();
|
||||
expect(result).toContain('✅ Successfully removed');
|
||||
expect(result.content).toContain('✅ Successfully removed');
|
||||
});
|
||||
|
||||
it('should remove empty devDependencies object', async () => {
|
||||
@@ -121,7 +121,7 @@ describe('NpmRemovePackageTool', () => {
|
||||
|
||||
expect(writtenPackageJson.devDependencies).toBeUndefined();
|
||||
expect(writtenPackageJson.dependencies.react).toBe('^18.0.0');
|
||||
expect(result).toContain('✅ Successfully removed');
|
||||
expect(result.content).toContain('✅ Successfully removed');
|
||||
});
|
||||
|
||||
it('should handle package not found', async () => {
|
||||
@@ -138,7 +138,7 @@ describe('NpmRemovePackageTool', () => {
|
||||
const result = await tool.execute({ name: 'nonexistent-package' });
|
||||
|
||||
expect(mockFS.writeFile).not.toHaveBeenCalled();
|
||||
expect(result).toContain('ℹ️ Package nonexistent-package was not found');
|
||||
expect(result.content).toContain('ℹ️ Package nonexistent-package was not found');
|
||||
});
|
||||
|
||||
it('should handle missing package.json', async () => {
|
||||
@@ -173,7 +173,7 @@ describe('NpmRemovePackageTool', () => {
|
||||
const dependencyKeys = Object.keys(writtenPackageJson.dependencies);
|
||||
|
||||
expect(dependencyKeys).toEqual(['axios', 'zlib']);
|
||||
expect(result).toContain('✅ Successfully removed');
|
||||
expect(result.content).toContain('✅ Successfully removed');
|
||||
});
|
||||
|
||||
it('should include version information in success message', async () => {
|
||||
@@ -189,7 +189,7 @@ describe('NpmRemovePackageTool', () => {
|
||||
|
||||
const result = await tool.execute({ name: 'lodash' });
|
||||
|
||||
expect(result).toContain('🏷️ Version: ^4.17.21');
|
||||
expect(result).toContain('📁 Removed from: dependencies');
|
||||
expect(result.content).toContain('🏷️ Version: ^4.17.21');
|
||||
expect(result.content).toContain('📁 Removed from: dependencies');
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { Tool } from "./Tool";
|
||||
import type { Tool, ToolResult } from "./Tool";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
|
||||
interface NpmRemovePackageParams {
|
||||
@@ -28,7 +28,7 @@ export class NpmRemovePackageTool implements Tool<NpmRemovePackageParams> {
|
||||
this.cwd = cwd;
|
||||
}
|
||||
|
||||
async execute(args: NpmRemovePackageParams): Promise<string> {
|
||||
async execute(args: NpmRemovePackageParams): Promise<ToolResult> {
|
||||
const { name } = args;
|
||||
|
||||
try {
|
||||
@@ -75,7 +75,7 @@ export class NpmRemovePackageTool implements Tool<NpmRemovePackageParams> {
|
||||
}
|
||||
|
||||
if (!foundIn) {
|
||||
return `ℹ️ Package ${name} was not found in package.json dependencies or devDependencies.`;
|
||||
return { content: `ℹ️ Package ${name} was not found in package.json dependencies or devDependencies.` };
|
||||
}
|
||||
|
||||
// Sort remaining dependencies alphabetically
|
||||
@@ -99,7 +99,9 @@ export class NpmRemovePackageTool implements Tool<NpmRemovePackageParams> {
|
||||
const updatedContent = JSON.stringify(packageJson, null, 2) + '\n';
|
||||
await this.fs.writeFile(packageJsonPath, updatedContent, "utf8");
|
||||
|
||||
return `✅ Successfully removed ${name} from ${foundIn} in package.json\n\n📦 Package: ${name}\n🏷️ Version: ${removedVersion}\n📁 Removed from: ${foundIn}\n\n⚠️ **Next step**: Run \`npm install\` to update node_modules and package-lock.json`;
|
||||
return {
|
||||
content: `✅ Successfully removed ${name} from ${foundIn} in package.json\n\n📦 Package: ${name}\n🏷️ Version: ${removedVersion}\n📁 Removed from: ${foundIn}\n\n⚠️ **Next step**: Run \`npm install\` to update node_modules and package-lock.json`
|
||||
};
|
||||
} catch (error) {
|
||||
throw new Error(`❌ Error removing package ${name}: ${String(error)}`);
|
||||
}
|
||||
|
||||
@@ -16,31 +16,31 @@ describe('ReadConsoleMessagesTool', () => {
|
||||
const tool = new ReadConsoleMessagesTool();
|
||||
const result = await tool.execute({});
|
||||
|
||||
expect(result).toContain('Found 4 console messages');
|
||||
expect(result).toContain('[LOG] App started');
|
||||
expect(result).toContain('[WARN] Deprecated API used');
|
||||
expect(result).toContain('[ERROR] Network request failed');
|
||||
expect(result).toContain('[INFO] User logged in');
|
||||
expect(result.content).toContain('Found 4 console messages');
|
||||
expect(result.content).toContain('[LOG] App started');
|
||||
expect(result.content).toContain('[WARN] Deprecated API used');
|
||||
expect(result.content).toContain('[ERROR] Network request failed');
|
||||
expect(result.content).toContain('[INFO] User logged in');
|
||||
});
|
||||
|
||||
it('should filter messages by level', async () => {
|
||||
const tool = new ReadConsoleMessagesTool();
|
||||
const result = await tool.execute({ filter: 'error' });
|
||||
|
||||
expect(result).toContain('Found 1 console message (level: error)');
|
||||
expect(result).toContain('[ERROR] Network request failed');
|
||||
expect(result).not.toContain('[LOG] App started');
|
||||
expect(result.content).toContain('Found 1 console message (level: error)');
|
||||
expect(result.content).toContain('[ERROR] Network request failed');
|
||||
expect(result.content).not.toContain('[LOG] App started');
|
||||
});
|
||||
|
||||
it('should limit number of messages', async () => {
|
||||
const tool = new ReadConsoleMessagesTool();
|
||||
const result = await tool.execute({ limit: 2 });
|
||||
|
||||
expect(result).toContain('Found 2 console messages');
|
||||
expect(result.content).toContain('Found 2 console messages');
|
||||
// Should get the last 2 messages
|
||||
expect(result).toContain('[ERROR] Network request failed');
|
||||
expect(result).toContain('[INFO] User logged in');
|
||||
expect(result).not.toContain('[LOG] App started');
|
||||
expect(result.content).toContain('[ERROR] Network request failed');
|
||||
expect(result.content).toContain('[INFO] User logged in');
|
||||
expect(result.content).not.toContain('[LOG] App started');
|
||||
});
|
||||
|
||||
it('should handle no messages found', async () => {
|
||||
@@ -48,14 +48,14 @@ describe('ReadConsoleMessagesTool', () => {
|
||||
const tool = new ReadConsoleMessagesTool();
|
||||
const result = await tool.execute({});
|
||||
|
||||
expect(result).toBe('No console messages found.');
|
||||
expect(result.content).toBe('No console messages found.');
|
||||
});
|
||||
|
||||
it('should handle no messages found with filter', async () => {
|
||||
const tool = new ReadConsoleMessagesTool();
|
||||
const result = await tool.execute({ filter: 'debug' });
|
||||
|
||||
expect(result).toBe('No console messages found for level: debug.');
|
||||
expect(result.content).toBe('No console messages found for level: debug.');
|
||||
});
|
||||
|
||||
it('should handle all filter levels', async () => {
|
||||
@@ -63,16 +63,16 @@ describe('ReadConsoleMessagesTool', () => {
|
||||
|
||||
// Test each filter level
|
||||
const errorResult = await tool.execute({ filter: 'error' });
|
||||
expect(errorResult).toContain('[ERROR] Network request failed');
|
||||
expect(errorResult.content).toContain('[ERROR] Network request failed');
|
||||
|
||||
const warnResult = await tool.execute({ filter: 'warn' });
|
||||
expect(warnResult).toContain('[WARN] Deprecated API used');
|
||||
expect(warnResult.content).toContain('[WARN] Deprecated API used');
|
||||
|
||||
const logResult = await tool.execute({ filter: 'log' });
|
||||
expect(logResult).toContain('[LOG] App started');
|
||||
expect(logResult.content).toContain('[LOG] App started');
|
||||
|
||||
const infoResult = await tool.execute({ filter: 'info' });
|
||||
expect(infoResult).toContain('[INFO] User logged in');
|
||||
expect(infoResult.content).toContain('[INFO] User logged in');
|
||||
});
|
||||
|
||||
it('should format messages correctly', async () => {
|
||||
@@ -82,7 +82,7 @@ describe('ReadConsoleMessagesTool', () => {
|
||||
const tool = new ReadConsoleMessagesTool();
|
||||
const result = await tool.execute({});
|
||||
|
||||
expect(result).toContain('[ERROR] Test error with special chars: <>&"');
|
||||
expect(result.content).toContain('[ERROR] Test error with special chars: <>&"');
|
||||
});
|
||||
|
||||
it('should handle limit correctly', async () => {
|
||||
@@ -90,11 +90,11 @@ describe('ReadConsoleMessagesTool', () => {
|
||||
|
||||
// Limit should return only the most recent messages
|
||||
const limitedResult = await tool.execute({ limit: 2 });
|
||||
expect(limitedResult).toContain('Found 2 console messages');
|
||||
expect(limitedResult.content).toContain('Found 2 console messages');
|
||||
|
||||
// Default limit (50) should return all messages when total is less than 50
|
||||
const allResult = await tool.execute({});
|
||||
expect(allResult).toContain('Found 4 console messages');
|
||||
expect(allResult.content).toContain('Found 4 console messages');
|
||||
});
|
||||
|
||||
it('should show truncation note when messages exceed limit', async () => {
|
||||
@@ -108,12 +108,12 @@ describe('ReadConsoleMessagesTool', () => {
|
||||
|
||||
// Default limit is 50
|
||||
const result = await tool.execute({});
|
||||
expect(result).toContain('(showing last 50 of 60)');
|
||||
expect(result).toContain('Message 60'); // Most recent
|
||||
expect(result).not.toContain('Message 10'); // Too old
|
||||
expect(result.content).toContain('(showing last 50 of 60)');
|
||||
expect(result.content).toContain('Message 60'); // Most recent
|
||||
expect(result.content).not.toContain('Message 10'); // Too old
|
||||
|
||||
// Custom limit
|
||||
const limitedResult = await tool.execute({ limit: 10 });
|
||||
expect(limitedResult).toContain('(showing last 10 of 60)');
|
||||
expect(limitedResult.content).toContain('(showing last 10 of 60)');
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { z } from 'zod';
|
||||
import { Tool } from './Tool';
|
||||
import { Tool, ToolResult } from './Tool';
|
||||
import { getConsoleMessages } from '@/lib/consoleMessages';
|
||||
|
||||
export interface ReadConsoleMessagesParams {
|
||||
@@ -23,7 +23,7 @@ export class ReadConsoleMessagesTool implements Tool<ReadConsoleMessagesParams>
|
||||
),
|
||||
});
|
||||
|
||||
async execute(params: ReadConsoleMessagesParams): Promise<string> {
|
||||
async execute(params: ReadConsoleMessagesParams): Promise<ToolResult> {
|
||||
const { filter = 'all', limit = 50 } = params;
|
||||
|
||||
let messages = getConsoleMessages()
|
||||
@@ -33,7 +33,7 @@ export class ReadConsoleMessagesTool implements Tool<ReadConsoleMessagesParams>
|
||||
messages = messages.slice(-limit);
|
||||
|
||||
if (messages.length === 0) {
|
||||
return `No console messages found${filter !== 'all' ? ` for level: ${filter}` : ''}.`;
|
||||
return { content: `No console messages found${filter !== 'all' ? ` for level: ${filter}` : ''}.` };
|
||||
}
|
||||
|
||||
const formatted = messages
|
||||
@@ -44,6 +44,8 @@ export class ReadConsoleMessagesTool implements Tool<ReadConsoleMessagesParams>
|
||||
const totalAvailable = getConsoleMessages().filter(msg => filter === 'all' || msg.level === filter).length;
|
||||
const truncatedNote = totalAvailable > messages.length ? ` (showing last ${messages.length} of ${totalAvailable})` : '';
|
||||
|
||||
return `Found ${messages.length} console message${messages.length !== 1 ? 's' : ''}${suffix}${truncatedNote}:\n\n${formatted}`;
|
||||
return {
|
||||
content: `Found ${messages.length} console message${messages.length !== 1 ? 's' : ''}${suffix}${truncatedNote}:\n\n${formatted}`
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -77,14 +77,14 @@ describe("ReadWebpageTool", () => {
|
||||
url: "https://example.com/article",
|
||||
});
|
||||
|
||||
expect(result).toContain("# Test Article");
|
||||
expect(result).toContain("**Source:** https://example.com/article");
|
||||
expect(result).toContain("Main Article Title");
|
||||
expect(result).toContain("**bold text**");
|
||||
expect(result).toContain("*italic text*");
|
||||
expect(result).toContain("## Subsection");
|
||||
expect(result).toContain("* First item");
|
||||
expect(result).toContain("* Second item");
|
||||
expect(result.content).toContain("# Test Article");
|
||||
expect(result.content).toContain("**Source:** https://example.com/article");
|
||||
expect(result.content).toContain("Main Article Title");
|
||||
expect(result.content).toContain("**bold text**");
|
||||
expect(result.content).toContain("*italic text*");
|
||||
expect(result.content).toContain("## Subsection");
|
||||
expect(result.content).toContain("* First item");
|
||||
expect(result.content).toContain("* Second item");
|
||||
});
|
||||
|
||||
it("should handle articles with metadata", async () => {
|
||||
@@ -122,8 +122,8 @@ describe("ReadWebpageTool", () => {
|
||||
url: "https://example.com/article-with-metadata",
|
||||
});
|
||||
|
||||
expect(result).toContain("# Article with Metadata");
|
||||
expect(result).toContain("**Source:** https://example.com/article-with-metadata");
|
||||
expect(result.content).toContain("# Article with Metadata");
|
||||
expect(result.content).toContain("**Source:** https://example.com/article-with-metadata");
|
||||
});
|
||||
|
||||
it("should handle code blocks properly", async () => {
|
||||
@@ -158,9 +158,9 @@ function hello() {
|
||||
url: "https://example.com/code-example",
|
||||
});
|
||||
|
||||
expect(result).toContain("```");
|
||||
expect(result).toContain("function hello()");
|
||||
expect(result).toContain("`code`");
|
||||
expect(result.content).toContain("```");
|
||||
expect(result.content).toContain("function hello()");
|
||||
expect(result.content).toContain("`code`");
|
||||
});
|
||||
|
||||
it("should handle HTTP errors", async () => {
|
||||
@@ -223,8 +223,8 @@ function hello() {
|
||||
url: "https://example.com/minimal-content",
|
||||
});
|
||||
|
||||
expect(result).toContain("# Untitled");
|
||||
expect(result).toContain("**Source:** https://example.com/minimal-content");
|
||||
expect(result.content).toContain("# Untitled");
|
||||
expect(result.content).toContain("**Source:** https://example.com/minimal-content");
|
||||
});
|
||||
|
||||
it("should handle invalid URLs", async () => {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Readability } from "@mozilla/readability";
|
||||
import TurndownService from "turndown";
|
||||
import { z } from "zod";
|
||||
|
||||
import type { Tool } from "./Tool";
|
||||
import type { Tool, ToolResult } from "./Tool";
|
||||
|
||||
interface ReadWebpageParams {
|
||||
url: string;
|
||||
@@ -54,7 +54,7 @@ export class ReadWebpageTool implements Tool<ReadWebpageParams> {
|
||||
});
|
||||
}
|
||||
|
||||
async execute(args: ReadWebpageParams): Promise<string> {
|
||||
async execute(args: ReadWebpageParams): Promise<ToolResult> {
|
||||
const { url } = args;
|
||||
|
||||
try {
|
||||
@@ -111,7 +111,7 @@ export class ReadWebpageTool implements Tool<ReadWebpageParams> {
|
||||
markdown,
|
||||
].filter(Boolean).join("\n");
|
||||
|
||||
return result;
|
||||
return { content: result };
|
||||
|
||||
} catch (error) {
|
||||
if (error instanceof TypeError && error.message.includes("fetch")) {
|
||||
|
||||
@@ -51,19 +51,19 @@ describe('ShellTool', () => {
|
||||
|
||||
it('should return error for empty command', async () => {
|
||||
const result = await shellTool.execute({ command: '' });
|
||||
expect(result).toBe('Error: Empty command');
|
||||
expect(result.content).toBe('Error: Empty command');
|
||||
});
|
||||
|
||||
it('should return error for whitespace-only command', async () => {
|
||||
const result = await shellTool.execute({ command: ' ' });
|
||||
expect(result).toBe('Error: Empty command');
|
||||
expect(result.content).toBe('Error: Empty command');
|
||||
});
|
||||
|
||||
it('should return error for unknown command', async () => {
|
||||
const result = await shellTool.execute({ command: 'unknowncommand' });
|
||||
expect(result).toContain("Command 'unknowncommand' not found");
|
||||
expect(result).toContain('Available commands:');
|
||||
expect(result).toContain('cat');
|
||||
expect(result.content).toContain("Command 'unknowncommand' not found");
|
||||
expect(result.content).toContain('Available commands:');
|
||||
expect(result.content).toContain('cat');
|
||||
});
|
||||
|
||||
it('should execute cat command successfully', async () => {
|
||||
@@ -76,7 +76,7 @@ describe('ShellTool', () => {
|
||||
|
||||
const result = await shellTool.execute({ command: 'cat test.txt' });
|
||||
|
||||
expect(result).toBe(fileContent);
|
||||
expect(result.content).toBe(fileContent);
|
||||
});
|
||||
|
||||
it('should parse commands with arguments correctly', async () => {
|
||||
@@ -90,7 +90,7 @@ describe('ShellTool', () => {
|
||||
|
||||
const result = await shellTool.execute({ command: 'cat file1.txt file2.txt' });
|
||||
|
||||
expect(result).toBe('File 1\nFile 2\n');
|
||||
expect(result.content).toBe('File 1\nFile 2\n');
|
||||
});
|
||||
|
||||
it('should handle quoted arguments', async () => {
|
||||
@@ -143,27 +143,27 @@ describe('ShellTool', () => {
|
||||
|
||||
const result = await shellTool.execute({ command: 'cat nonexistent.txt' });
|
||||
|
||||
expect(result).toContain('No such file or directory');
|
||||
expect(result).toContain('Exit code: 1');
|
||||
expect(result.content).toContain('No such file or directory');
|
||||
expect(result.content).toContain('Exit code: 1');
|
||||
});
|
||||
|
||||
it('should show stderr output', async () => {
|
||||
const result = await shellTool.execute({ command: 'cat' });
|
||||
|
||||
expect(result).toContain('missing file operand');
|
||||
expect(result).toContain('Exit code: 1');
|
||||
expect(result.content).toContain('missing file operand');
|
||||
expect(result.content).toContain('Exit code: 1');
|
||||
});
|
||||
|
||||
it('should execute echo command', async () => {
|
||||
const result = await shellTool.execute({ command: 'echo hello world' });
|
||||
|
||||
expect(result).toBe('hello world\n');
|
||||
expect(result.content).toBe('hello world\n');
|
||||
});
|
||||
|
||||
it('should execute pwd command', async () => {
|
||||
const result = await shellTool.execute({ command: 'pwd' });
|
||||
|
||||
expect(result).toBe(testCwd);
|
||||
expect(result.content).toBe(testCwd);
|
||||
});
|
||||
|
||||
it('should handle cd command and update working directory', async () => {
|
||||
@@ -174,7 +174,7 @@ describe('ShellTool', () => {
|
||||
|
||||
const result = await shellTool.execute({ command: 'cd subdir' });
|
||||
|
||||
expect(result).toBe('(no output)');
|
||||
expect(result.content).toBe('(no output)');
|
||||
expect(shellTool.getCurrentWorkingDirectory()).toBe('/test/dir/subdir');
|
||||
});
|
||||
|
||||
@@ -182,7 +182,7 @@ describe('ShellTool', () => {
|
||||
it('should redirect output to file with > operator', async () => {
|
||||
const result = await shellTool.execute({ command: 'echo "hello world" > test.txt' });
|
||||
|
||||
expect(result).toBe('(no output)');
|
||||
expect(result.content).toBe('(no output)');
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith('/test/dir/test.txt', 'hello world\n', 'utf8');
|
||||
});
|
||||
|
||||
@@ -191,7 +191,7 @@ describe('ShellTool', () => {
|
||||
|
||||
const result = await shellTool.execute({ command: 'echo "new line" >> test.txt' });
|
||||
|
||||
expect(result).toBe('(no output)');
|
||||
expect(result.content).toBe('(no output)');
|
||||
expect(mockFS.readFile).toHaveBeenCalledWith('/test/dir/test.txt', 'utf8');
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith('/test/dir/test.txt', 'existing content\nnew line\n', 'utf8');
|
||||
});
|
||||
@@ -201,21 +201,21 @@ describe('ShellTool', () => {
|
||||
|
||||
const result = await shellTool.execute({ command: 'echo "first line" >> newfile.txt' });
|
||||
|
||||
expect(result).toBe('(no output)');
|
||||
expect(result.content).toBe('(no output)');
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith('/test/dir/newfile.txt', 'first line\n', 'utf8');
|
||||
});
|
||||
|
||||
it('should handle quoted filenames in redirection', async () => {
|
||||
const result = await shellTool.execute({ command: 'echo test > "file with spaces.txt"' });
|
||||
|
||||
expect(result).toBe('(no output)');
|
||||
expect(result.content).toBe('(no output)');
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith('/test/dir/file with spaces.txt', 'test\n', 'utf8');
|
||||
});
|
||||
|
||||
it('should handle absolute paths in redirection', async () => {
|
||||
const result = await shellTool.execute({ command: 'echo test > /tmp/absolute.txt' });
|
||||
|
||||
expect(result).toBe('(no output)');
|
||||
expect(result.content).toBe('(no output)');
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith('/tmp/absolute.txt', 'test\n', 'utf8');
|
||||
});
|
||||
|
||||
@@ -224,8 +224,8 @@ describe('ShellTool', () => {
|
||||
|
||||
const result = await shellTool.execute({ command: 'echo test > /readonly/file.txt' });
|
||||
|
||||
expect(result).toContain('Redirection error: Permission denied');
|
||||
expect(result).toContain('Exit code: 1');
|
||||
expect(result.content).toContain('Redirection error: Permission denied');
|
||||
expect(result.content).toContain('Exit code: 1');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -233,8 +233,8 @@ describe('ShellTool', () => {
|
||||
it('should execute commands with && operator (success case)', async () => {
|
||||
const result = await shellTool.execute({ command: 'pwd && echo hello' });
|
||||
|
||||
expect(result).toContain(testCwd);
|
||||
expect(result).toContain('hello');
|
||||
expect(result.content).toContain(testCwd);
|
||||
expect(result.content).toContain('hello');
|
||||
});
|
||||
|
||||
it('should execute commands with && operator (failure case)', async () => {
|
||||
@@ -242,15 +242,15 @@ describe('ShellTool', () => {
|
||||
|
||||
const result = await shellTool.execute({ command: 'cat nonexistent.txt && echo should not run' });
|
||||
|
||||
expect(result).toContain('No such file or directory');
|
||||
expect(result).not.toContain('should not run');
|
||||
expect(result.content).toContain('No such file or directory');
|
||||
expect(result.content).not.toContain('should not run');
|
||||
});
|
||||
|
||||
it('should execute commands with || operator (success case)', async () => {
|
||||
const result = await shellTool.execute({ command: 'pwd || echo fallback' });
|
||||
|
||||
expect(result).toContain(testCwd);
|
||||
expect(result).not.toContain('fallback');
|
||||
expect(result.content).toContain(testCwd);
|
||||
expect(result.content).not.toContain('fallback');
|
||||
});
|
||||
|
||||
it('should execute commands with || operator (failure case)', async () => {
|
||||
@@ -258,36 +258,36 @@ describe('ShellTool', () => {
|
||||
|
||||
const result = await shellTool.execute({ command: 'cat nonexistent.txt || echo fallback' });
|
||||
|
||||
expect(result).toContain('No such file or directory');
|
||||
expect(result).toContain('fallback');
|
||||
expect(result.content).toContain('No such file or directory');
|
||||
expect(result.content).toContain('fallback');
|
||||
});
|
||||
|
||||
it('should execute commands with ; operator', async () => {
|
||||
const result = await shellTool.execute({ command: 'echo first; echo second' });
|
||||
|
||||
expect(result).toContain('first');
|
||||
expect(result).toContain('second');
|
||||
expect(result.content).toContain('first');
|
||||
expect(result.content).toContain('second');
|
||||
});
|
||||
|
||||
it('should execute commands with pipe operator', async () => {
|
||||
const result = await shellTool.execute({ command: 'echo "hello world" | cat' });
|
||||
|
||||
expect(result).toContain('hello world');
|
||||
expect(result.content).toContain('hello world');
|
||||
});
|
||||
|
||||
it('should handle complex compound commands', async () => {
|
||||
const result = await shellTool.execute({ command: 'echo "line1\nline2\nline3" | head -n 2' });
|
||||
|
||||
expect(result).toContain('line1');
|
||||
expect(result).toContain('line2');
|
||||
expect(result).not.toContain('line3');
|
||||
expect(result.content).toContain('line1');
|
||||
expect(result.content).toContain('line2');
|
||||
expect(result.content).not.toContain('line3');
|
||||
});
|
||||
|
||||
it('should parse quoted strings in compound commands', async () => {
|
||||
const result = await shellTool.execute({ command: 'echo "hello && world" && echo success' });
|
||||
|
||||
expect(result).toContain('hello && world');
|
||||
expect(result).toContain('success');
|
||||
expect(result.content).toContain('hello && world');
|
||||
expect(result.content).toContain('success');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,12 @@
|
||||
import { z } from "zod";
|
||||
import type { Tool } from "./Tool";
|
||||
import { join } from "path-browserify";
|
||||
import type { Tool, ToolResult } from "./Tool";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand } from "../commands/ShellCommand";
|
||||
import { Git } from "../git";
|
||||
import { stripAnsiCodes } from "../ansiToHtml";
|
||||
import type { NostrSigner } from "@nostrify/nostrify";
|
||||
import { isAbsolutePath } from "../pathUtils";
|
||||
import {
|
||||
CatCommand,
|
||||
CdCommand,
|
||||
@@ -323,32 +325,35 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
}
|
||||
}
|
||||
|
||||
async execute(args: ShellToolParams): Promise<string> {
|
||||
async execute(args: ShellToolParams): Promise<ToolResult> {
|
||||
const { command: commandStr } = args;
|
||||
|
||||
if (!commandStr.trim()) {
|
||||
return "Error: Empty command";
|
||||
return { content: "Error: Empty command" };
|
||||
}
|
||||
|
||||
// Check if running in Electron - if so, use real shell execution
|
||||
if (window.electron?.shell) {
|
||||
return this.executeRealShell(commandStr);
|
||||
const content = await this.executeRealShell(commandStr);
|
||||
return { content };
|
||||
}
|
||||
|
||||
// Parse compound commands
|
||||
const commands = this.parseCompoundCommand(commandStr);
|
||||
|
||||
if (commands.length === 0) {
|
||||
return "Error: No command specified";
|
||||
return { content: "Error: No command specified" };
|
||||
}
|
||||
|
||||
// If it's a simple command (no operators), use the optimized single command execution
|
||||
if (commands.length === 1) {
|
||||
return this.executeSimpleCommand(commands[0].command);
|
||||
const content = await this.executeSimpleCommand(commands[0].command);
|
||||
return { content };
|
||||
}
|
||||
|
||||
// Execute compound commands
|
||||
return this.executeCompoundCommands(commands);
|
||||
const content = await this.executeCompoundCommands(commands);
|
||||
return { content };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -430,7 +435,7 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
*/
|
||||
private async handleRedirection(output: string, redirectType: '>' | '>>', redirectFile: string): Promise<void> {
|
||||
// Resolve the file path relative to current working directory
|
||||
const filePath = redirectFile.startsWith('/') ? redirectFile : `${this.cwd}/${redirectFile}`;
|
||||
const filePath = isAbsolutePath(redirectFile) ? redirectFile : join(this.cwd, redirectFile);
|
||||
|
||||
if (redirectType === '>') {
|
||||
// Overwrite the file
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { z } from 'zod';
|
||||
import type { Tool } from './Tool';
|
||||
import type { Tool, ToolResult } from './Tool';
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
import { findSkill, readSkillContent } from '../plugins';
|
||||
|
||||
@@ -24,7 +24,7 @@ export class SkillTool implements Tool<SkillParams> {
|
||||
this.projectPath = projectPath;
|
||||
}
|
||||
|
||||
async execute(args: SkillParams): Promise<string> {
|
||||
async execute(args: SkillParams): Promise<ToolResult> {
|
||||
const { name } = args;
|
||||
|
||||
try {
|
||||
@@ -38,7 +38,8 @@ export class SkillTool implements Tool<SkillParams> {
|
||||
// Read and return the skill content
|
||||
const content = await readSkillContent(this.fs, skill);
|
||||
|
||||
return `# Skill: ${skill.name}
|
||||
return {
|
||||
content: `# Skill: ${skill.name}
|
||||
|
||||
**Source**: ${skill.plugin === 'project' ? 'Project' : `Plugin: ${skill.plugin}`}
|
||||
**Description**: ${skill.description}
|
||||
@@ -46,7 +47,8 @@ export class SkillTool implements Tool<SkillParams> {
|
||||
|
||||
---
|
||||
|
||||
${content}`;
|
||||
${content}`
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
throw error;
|
||||
|
||||
@@ -119,7 +119,7 @@ describe('TextEditorStrReplaceTool', () => {
|
||||
new_str: 'hello universe'
|
||||
});
|
||||
|
||||
expect(result).toContain('String successfully replaced in src/test.ts');
|
||||
expect(result.content).toContain('String successfully replaced in src/test.ts');
|
||||
expect(mockFS.getFileContent('/project/src/test.ts')).toContain('hello universe');
|
||||
expect(mockFS.getFileContent('/project/src/test.ts')).not.toContain('hello world');
|
||||
});
|
||||
@@ -150,7 +150,7 @@ describe('TextEditorStrReplaceTool', () => {
|
||||
new_str: 'modified'
|
||||
});
|
||||
|
||||
expect(result).toContain('String successfully replaced');
|
||||
expect(result.content).toContain('String successfully replaced');
|
||||
expect(mockFS.getFileContent('/tmp/temp-file.txt')).toBe('modified content');
|
||||
});
|
||||
|
||||
@@ -162,7 +162,7 @@ describe('TextEditorStrReplaceTool', () => {
|
||||
normalize_whitespace: true
|
||||
});
|
||||
|
||||
expect(result).toContain('String successfully replaced');
|
||||
expect(result.content).toContain('String successfully replaced');
|
||||
expect(mockFS.getFileContent('/project/src/test.ts')).toContain('const greeting = "hello universe";');
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import { join } from "path-browserify";
|
||||
import { z } from "zod";
|
||||
|
||||
import type { Tool } from "./Tool";
|
||||
import type { Tool, ToolResult } from "./Tool";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import { isAbsolutePath, isWriteAllowed, createWriteAccessDeniedError } from "../security";
|
||||
|
||||
@@ -38,7 +38,7 @@ export class TextEditorStrReplaceTool implements Tool<TextEditorStrReplaceParams
|
||||
this.onFileChanged = options?.onFileChanged;
|
||||
}
|
||||
|
||||
async execute(args: TextEditorStrReplaceParams): Promise<string> {
|
||||
async execute(args: TextEditorStrReplaceParams): Promise<ToolResult> {
|
||||
const { path, old_str, new_str, normalize_whitespace = true } = args;
|
||||
|
||||
// Check write permissions
|
||||
@@ -184,7 +184,7 @@ export class TextEditorStrReplaceTool implements Tool<TextEditorStrReplaceParams
|
||||
successMessage += ` (${occurrences} occurrences found, only first occurrence replaced)`;
|
||||
}
|
||||
|
||||
return successMessage;
|
||||
return { content: successMessage };
|
||||
} catch (error) {
|
||||
throw new Error(String(error));
|
||||
}
|
||||
|
||||
@@ -192,22 +192,22 @@ describe('TextEditorViewTool', () => {
|
||||
it('should handle viewing current directory', async () => {
|
||||
const result = await tool.execute({ path: '.' });
|
||||
|
||||
expect(result).toContain('src/');
|
||||
expect(result).toContain('package.json');
|
||||
expect(result).toContain('.gitignore');
|
||||
expect(result).toContain('.git/'); // .git directory should now be visible
|
||||
expect(result.content).toContain('src/');
|
||||
expect(result.content).toContain('package.json');
|
||||
expect(result.content).toContain('.gitignore');
|
||||
expect(result.content).toContain('.git/'); // .git directory should now be visible
|
||||
});
|
||||
|
||||
it('should handle viewing subdirectory', async () => {
|
||||
const result = await tool.execute({ path: 'src' });
|
||||
|
||||
expect(result).toContain('index.ts');
|
||||
expect(result.content).toContain('index.ts');
|
||||
});
|
||||
|
||||
it('should handle viewing a file', async () => {
|
||||
const result = await tool.execute({ path: 'src/index.ts' });
|
||||
|
||||
expect(result).toBe('console.log("hello");');
|
||||
expect(result.content).toBe('console.log("hello");');
|
||||
});
|
||||
|
||||
it('should handle line filtering', async () => {
|
||||
@@ -217,19 +217,19 @@ describe('TextEditorViewTool', () => {
|
||||
end_line: 1
|
||||
});
|
||||
|
||||
expect(result).toBe('console.log("hello");');
|
||||
expect(result.content).toBe('console.log("hello");');
|
||||
});
|
||||
|
||||
it('should handle absolute paths', async () => {
|
||||
const result = await tool.execute({ path: '/tmp/uploaded-file.txt' });
|
||||
|
||||
expect(result).toBe('This is an uploaded file');
|
||||
expect(result.content).toBe('This is an uploaded file');
|
||||
});
|
||||
|
||||
it('should handle absolute directory paths', async () => {
|
||||
const result = await tool.execute({ path: '/tmp' });
|
||||
|
||||
expect(result).toContain('uploaded-file.txt');
|
||||
expect(result.content).toContain('uploaded-file.txt');
|
||||
});
|
||||
|
||||
it('should handle absolute paths with line filtering', async () => {
|
||||
@@ -239,97 +239,97 @@ describe('TextEditorViewTool', () => {
|
||||
end_line: 1
|
||||
});
|
||||
|
||||
expect(result).toBe('This is an uploaded file');
|
||||
expect(result.content).toBe('This is an uploaded file');
|
||||
});
|
||||
|
||||
it('should detect binary files by extension and show placeholder', async () => {
|
||||
const result = await tool.execute({ path: 'logo.png' });
|
||||
|
||||
expect(result).toContain('[Binary file: PNG file');
|
||||
expect(result).toContain('This appears to be a binary file and cannot be displayed as text.');
|
||||
expect(result).not.toContain('BINARY_CONTENT_PNG');
|
||||
expect(result.content).toContain('[Binary file: PNG file');
|
||||
expect(result.content).toContain('This appears to be a binary file and cannot be displayed as text.');
|
||||
expect(result.content).not.toContain('BINARY_CONTENT_PNG');
|
||||
});
|
||||
|
||||
it('should detect PDF files as binary', async () => {
|
||||
const result = await tool.execute({ path: 'document.pdf' });
|
||||
|
||||
expect(result).toContain('[Binary file: PDF file');
|
||||
expect(result).toContain('This appears to be a binary file and cannot be displayed as text.');
|
||||
expect(result.content).toContain('[Binary file: PDF file');
|
||||
expect(result.content).toContain('This appears to be a binary file and cannot be displayed as text.');
|
||||
});
|
||||
|
||||
it('should detect binary files with absolute paths', async () => {
|
||||
const result = await tool.execute({ path: '/tmp/image.jpg' });
|
||||
|
||||
expect(result).toContain('[Binary file: JPG file');
|
||||
expect(result).toContain('This appears to be a binary file and cannot be displayed as text.');
|
||||
expect(result.content).toContain('[Binary file: JPG file');
|
||||
expect(result.content).toContain('This appears to be a binary file and cannot be displayed as text.');
|
||||
});
|
||||
|
||||
it('should show only project directories when viewing /projects', async () => {
|
||||
const result = await tool.execute({ path: '/projects' });
|
||||
|
||||
// Should show the project directories
|
||||
expect(result).toContain('project1/');
|
||||
expect(result).toContain('project2/');
|
||||
expect(result.content).toContain('project1/');
|
||||
expect(result.content).toContain('project2/');
|
||||
|
||||
// Should NOT show the contents of the project directories (depth 1 only)
|
||||
expect(result).not.toContain('package.json');
|
||||
expect(result).not.toContain('src/');
|
||||
expect(result).not.toContain('index.ts');
|
||||
expect(result).not.toContain('main.ts');
|
||||
expect(result.content).not.toContain('package.json');
|
||||
expect(result.content).not.toContain('src/');
|
||||
expect(result.content).not.toContain('index.ts');
|
||||
expect(result.content).not.toContain('main.ts');
|
||||
});
|
||||
|
||||
it('should show only project directories when viewing /projects/', async () => {
|
||||
const result = await tool.execute({ path: '/projects/' });
|
||||
|
||||
// Should show the project directories
|
||||
expect(result).toContain('project1/');
|
||||
expect(result).toContain('project2/');
|
||||
expect(result.content).toContain('project1/');
|
||||
expect(result.content).toContain('project2/');
|
||||
|
||||
// Should NOT show the contents of the project directories (depth 1 only)
|
||||
expect(result).not.toContain('package.json');
|
||||
expect(result).not.toContain('src/');
|
||||
expect(result).not.toContain('index.ts');
|
||||
expect(result).not.toContain('main.ts');
|
||||
expect(result.content).not.toContain('package.json');
|
||||
expect(result.content).not.toContain('src/');
|
||||
expect(result.content).not.toContain('index.ts');
|
||||
expect(result.content).not.toContain('main.ts');
|
||||
});
|
||||
|
||||
it('should show .git directory but not traverse its contents when viewing project root', async () => {
|
||||
const result = await tool.execute({ path: '/project' });
|
||||
|
||||
// Should show the .git directory
|
||||
expect(result).toContain('.git/');
|
||||
expect(result.content).toContain('.git/');
|
||||
|
||||
// Should show "..." under .git instead of its contents
|
||||
expect(result).toContain('...');
|
||||
expect(result.content).toContain('...');
|
||||
|
||||
// Should NOT show .git file contents
|
||||
expect(result).not.toContain('config');
|
||||
expect(result).not.toContain('HEAD');
|
||||
expect(result).not.toContain('repositoryformatversion');
|
||||
expect(result.content).not.toContain('config');
|
||||
expect(result.content).not.toContain('HEAD');
|
||||
expect(result.content).not.toContain('repositoryformatversion');
|
||||
|
||||
// Should still show other directory contents normally
|
||||
expect(result).toContain('src/');
|
||||
expect(result).toContain('package.json');
|
||||
expect(result.content).toContain('src/');
|
||||
expect(result.content).toContain('package.json');
|
||||
});
|
||||
|
||||
it('should show .git contents when explicitly viewing .git directory', async () => {
|
||||
const result = await tool.execute({ path: '/project/.git' });
|
||||
|
||||
// Should show the .git file contents when explicitly requested
|
||||
expect(result).toContain('config');
|
||||
expect(result).toContain('HEAD');
|
||||
expect(result.content).toContain('config');
|
||||
expect(result.content).toContain('HEAD');
|
||||
|
||||
// Should NOT show "..." when explicitly viewing .git
|
||||
expect(result).not.toContain('...');
|
||||
expect(result.content).not.toContain('...');
|
||||
});
|
||||
|
||||
it('should show .git contents when explicitly viewing .git with relative path', async () => {
|
||||
const result = await tool.execute({ path: '.git' });
|
||||
|
||||
// Should show the .git file contents when explicitly requested
|
||||
expect(result).toContain('config');
|
||||
expect(result).toContain('HEAD');
|
||||
expect(result.content).toContain('config');
|
||||
expect(result.content).toContain('HEAD');
|
||||
|
||||
// Should NOT show "..." when explicitly viewing .git
|
||||
expect(result).not.toContain('...');
|
||||
expect(result.content).not.toContain('...');
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import { join } from "path-browserify";
|
||||
import { z } from "zod";
|
||||
|
||||
import type { Tool } from "./Tool";
|
||||
import type { Tool, ToolResult } from "./Tool";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
|
||||
interface TextEditorViewParams {
|
||||
@@ -35,7 +35,7 @@ export class TextEditorViewTool implements Tool<TextEditorViewParams> {
|
||||
this.projectsPath = options?.projectsPath || '/projects';
|
||||
}
|
||||
|
||||
async execute(args: TextEditorViewParams): Promise<string> {
|
||||
async execute(args: TextEditorViewParams): Promise<ToolResult> {
|
||||
const { path, start_line, end_line } = args;
|
||||
|
||||
try {
|
||||
@@ -58,7 +58,7 @@ export class TextEditorViewTool implements Tool<TextEditorViewParams> {
|
||||
const normalizedPath = absolutePath.replace(/\/$/, ''); // Remove trailing slash
|
||||
if (normalizedPath === this.projectsPath) {
|
||||
const tree = await this.generateDirectoryTree(absolutePath, "", 1); // Only show immediate children
|
||||
return tree;
|
||||
return { content: tree };
|
||||
}
|
||||
|
||||
// Check if we're starting from a .git directory
|
||||
@@ -67,7 +67,7 @@ export class TextEditorViewTool implements Tool<TextEditorViewParams> {
|
||||
// If it's a directory, generate a tree-like listing
|
||||
// Note: start_line and end_line are ignored for directories
|
||||
const tree = await this.generateDirectoryTree(absolutePath, "", 3, 0, isGitRoot);
|
||||
return tree;
|
||||
return { content: tree };
|
||||
}
|
||||
|
||||
// If it's a file, check if it's binary first
|
||||
@@ -75,7 +75,9 @@ export class TextEditorViewTool implements Tool<TextEditorViewParams> {
|
||||
const stats = await this.fs.stat(absolutePath);
|
||||
const fileSize = this.formatFileSize(stats.size || 0);
|
||||
const fileExtension = this.getFileExtension(absolutePath);
|
||||
return `[Binary file: ${fileExtension.toUpperCase()} file, ${fileSize}]\n\nThis appears to be a binary file and cannot be displayed as text.`;
|
||||
return {
|
||||
content: `[Binary file: ${fileExtension.toUpperCase()} file, ${fileSize}]\n\nThis appears to be a binary file and cannot be displayed as text.`
|
||||
};
|
||||
}
|
||||
|
||||
// If it's a text file, read and return its contents
|
||||
@@ -108,7 +110,7 @@ export class TextEditorViewTool implements Tool<TextEditorViewParams> {
|
||||
content = lines.slice(startIdx, endIdx).join('\n');
|
||||
}
|
||||
|
||||
return content;
|
||||
return { content };
|
||||
} catch (error) {
|
||||
throw new Error(String(error));
|
||||
}
|
||||
|
||||
@@ -122,7 +122,7 @@ describe('TextEditorWriteTool', () => {
|
||||
file_text: 'console.log("test");'
|
||||
});
|
||||
|
||||
expect(result).toContain('File successfully written to src/test.ts');
|
||||
expect(result.content).toContain('File successfully written to src/test.ts');
|
||||
expect(mockFS.hasFile('/project/src/test.ts')).toBe(true);
|
||||
expect(mockFS.getFileContent('/project/src/test.ts')).toBe('console.log("test");');
|
||||
});
|
||||
@@ -140,7 +140,7 @@ describe('TextEditorWriteTool', () => {
|
||||
file_text: 'temporary content'
|
||||
});
|
||||
|
||||
expect(result).toContain('File successfully written to /tmp/temp-file.txt');
|
||||
expect(result.content).toContain('File successfully written to /tmp/temp-file.txt');
|
||||
expect(mockFS.hasFile('/tmp/temp-file.txt')).toBe(true);
|
||||
expect(mockFS.getFileContent('/tmp/temp-file.txt')).toBe('temporary content');
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { join, dirname } from "path-browserify";
|
||||
import { z } from "zod";
|
||||
|
||||
import type { Tool } from "./Tool";
|
||||
import type { Tool, ToolResult } from "./Tool";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import { isAbsolutePath, isWriteAllowed, createWriteAccessDeniedError } from "../security";
|
||||
|
||||
@@ -34,7 +34,7 @@ export class TextEditorWriteTool implements Tool<TextEditorWriteParams> {
|
||||
this.onFileChanged = options?.onFileChanged;
|
||||
}
|
||||
|
||||
async execute(args: TextEditorWriteParams): Promise<string> {
|
||||
async execute(args: TextEditorWriteParams): Promise<ToolResult> {
|
||||
const { path, file_text } = args;
|
||||
|
||||
// Check write permissions
|
||||
@@ -66,7 +66,7 @@ export class TextEditorWriteTool implements Tool<TextEditorWriteParams> {
|
||||
this.onFileChanged(path);
|
||||
}
|
||||
|
||||
return `File successfully written to ${path}`;
|
||||
return { content: `File successfully written to ${path}` };
|
||||
} catch (error) {
|
||||
throw new Error(String(error));
|
||||
}
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import type z from "zod";
|
||||
|
||||
export interface ToolResult {
|
||||
content: string;
|
||||
cost?: number;
|
||||
}
|
||||
|
||||
export interface Tool<TParams> {
|
||||
description: string;
|
||||
inputSchema?: z.ZodType<TParams>;
|
||||
execute(args: TParams): Promise<string>;
|
||||
execute(args: TParams): Promise<ToolResult>;
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { TypecheckTool } from './TypecheckTool';
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
|
||||
describe('TypecheckTool', () => {
|
||||
let mockFS: JSRuntimeFS;
|
||||
let tool: TypecheckTool;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
mockFS = {
|
||||
readFile: vi.fn(),
|
||||
} as unknown as JSRuntimeFS;
|
||||
|
||||
tool = new TypecheckTool(mockFS, '/test/project');
|
||||
});
|
||||
|
||||
it('should have correct description', () => {
|
||||
expect(tool.description).toBe('Run TypeScript type checking on the project to verify there are no type errors.');
|
||||
});
|
||||
|
||||
it('should fail if tsconfig.json does not exist', async () => {
|
||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found'));
|
||||
|
||||
await expect(tool.execute()).rejects.toThrow(
|
||||
'❌ Could not find tsconfig.json at /test/project. Make sure you\'re in a valid TypeScript project.'
|
||||
);
|
||||
});
|
||||
|
||||
it('should successfully return no type errors (stub implementation)', async () => {
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue('{"compilerOptions": {}}'); // tsconfig.json exists
|
||||
|
||||
const result = await tool.execute();
|
||||
|
||||
expect(result).toContain('✅ No type errors found.');
|
||||
expect(result).toContain('🔍 TypeScript compilation completed successfully.');
|
||||
expect(result).toContain('📁 Project: /test/project');
|
||||
});
|
||||
|
||||
it('should handle file system errors gracefully', async () => {
|
||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('Permission denied'));
|
||||
|
||||
await expect(tool.execute()).rejects.toThrow(
|
||||
'❌ Could not find tsconfig.json at /test/project. Make sure you\'re in a valid TypeScript project.'
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,35 +0,0 @@
|
||||
import type { Tool } from "./Tool";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
|
||||
export class TypecheckTool implements Tool<void> {
|
||||
private fs: JSRuntimeFS;
|
||||
private cwd: string;
|
||||
|
||||
readonly description = "Run TypeScript type checking on the project to verify there are no type errors.";
|
||||
|
||||
constructor(fs: JSRuntimeFS, cwd: string) {
|
||||
this.fs = fs;
|
||||
this.cwd = cwd;
|
||||
}
|
||||
|
||||
async execute(): Promise<string> {
|
||||
// TODO: Add actual typechecking functionality
|
||||
// This should run TypeScript compiler in --noEmit mode to check for type errors
|
||||
// Similar to how the test script runs: tsc --noEmit
|
||||
|
||||
try {
|
||||
// Check if we're in a valid TypeScript project
|
||||
try {
|
||||
await this.fs.readFile(`${this.cwd}/tsconfig.json`, "utf8");
|
||||
} catch {
|
||||
throw new Error(`❌ Could not find tsconfig.json at ${this.cwd}. Make sure you're in a valid TypeScript project.`);
|
||||
}
|
||||
|
||||
// TODO: Implement actual TypeScript compilation check
|
||||
// For now, return a success message as a stub
|
||||
return "✅ No type errors found.\n\n🔍 TypeScript compilation completed successfully.\n📁 Project: " + this.cwd;
|
||||
} catch (error) {
|
||||
throw new Error(`❌ Type check failed: ${String(error)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { z } from 'zod';
|
||||
import type { Tool, ToolResult } from './Tool';
|
||||
|
||||
interface ProviderModel {
|
||||
id: string;
|
||||
type?: 'chat' | 'image';
|
||||
name?: string;
|
||||
provider: string;
|
||||
fullId: string;
|
||||
description?: string;
|
||||
contextLength?: number;
|
||||
modalities?: string[];
|
||||
}
|
||||
|
||||
export class ViewAvailableModelsTool implements Tool<Record<string, never>> {
|
||||
readonly description = 'View all available AI models across all configured providers, including their capabilities. This tool MUST be called before attempting to configure an image model, as it shows which models support image generation.';
|
||||
|
||||
readonly inputSchema = z.object({});
|
||||
|
||||
constructor(
|
||||
private models: ProviderModel[],
|
||||
private currentImageModel?: string,
|
||||
) {}
|
||||
|
||||
async execute(): Promise<ToolResult> {
|
||||
if (this.models.length === 0) {
|
||||
return { content: 'No AI models are currently available. Please configure at least one AI provider in Settings > AI.' };
|
||||
}
|
||||
|
||||
// Filter image-capable models
|
||||
// Filter out models that are definitely NOT image models
|
||||
const filteredModels = this.models.filter((model) => {
|
||||
// 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;
|
||||
});
|
||||
|
||||
// Group models by provider
|
||||
const modelsByProvider = new Map<string, ProviderModel[]>();
|
||||
for (const model of filteredModels) {
|
||||
const providerModels = modelsByProvider.get(model.provider) || [];
|
||||
providerModels.push(model);
|
||||
modelsByProvider.set(model.provider, providerModels);
|
||||
}
|
||||
|
||||
// Build output
|
||||
let output = '# Available Models\n\n';
|
||||
|
||||
// Add note about current image model if configured
|
||||
if (this.currentImageModel) {
|
||||
output += `**Current Image Model**: ${this.currentImageModel}\n\n`;
|
||||
} else {
|
||||
output += '**Current Image Model**: Not configured\n\n';
|
||||
}
|
||||
|
||||
if (filteredModels.length === 0) {
|
||||
output += 'No models found in configured providers.\n';
|
||||
output += `Total models available: ${this.models.length} (none support image generation)\n`;
|
||||
return { content: output };
|
||||
}
|
||||
|
||||
output += `Found ${filteredModels.length} models:\n\n`;
|
||||
|
||||
for (const [provider, providerModels] of modelsByProvider) {
|
||||
output += `### ${provider} (${providerModels.length} models)\n\n`;
|
||||
|
||||
for (const model of providerModels) {
|
||||
// Mark models that are DEFINITE image models with a star
|
||||
const isImageModel = model.type === 'image' || model.modalities?.includes('image');
|
||||
const marker = isImageModel ? ' ⭐' : '';
|
||||
output += `- ${model.fullId}${marker}\n`;
|
||||
}
|
||||
output += '\n';
|
||||
}
|
||||
|
||||
output += `Models marked with ⭐ are definite image generation models.\n`;
|
||||
|
||||
return { content: output };
|
||||
}
|
||||
}
|
||||
+50
-6
@@ -64,6 +64,8 @@
|
||||
"shareErrorReportsDescription": "Help improve this app by automatically sending crash and error reports.",
|
||||
"systemPrompt": "System Prompt",
|
||||
"systemPromptDescription": "AI system prompt controlling the assistant's behavior and knowledge.",
|
||||
"imageModel": "Image Generation",
|
||||
"imageModelDescription": "Configure the AI model used for generating images.",
|
||||
"english": "English",
|
||||
"portuguese": "Portuguese",
|
||||
"chinese": "Chinese",
|
||||
@@ -93,11 +95,10 @@
|
||||
"name": "Name",
|
||||
"id": "ID",
|
||||
"email": "Email",
|
||||
"buildNostrApps": "Build apps with AI",
|
||||
"whatToBuild": "What would you like to build?",
|
||||
"buildApps": "Build apps with AI",
|
||||
"chooseModel": "Choose a model...",
|
||||
"selectModelToDescribe": "Please select a model below, then describe what you'd like to build...",
|
||||
"examplePrompt": "e.g., Create a farming equipment marketplace for local farmers to buy and sell tractors, tools, and supplies...",
|
||||
"selectModelToDescribe": "Select a model below to get started...",
|
||||
"examplePrompt": "Describe what you'd like to build...",
|
||||
"aiSettings": "AI",
|
||||
"aiSettingsDescription": "Configure AI providers and API keys",
|
||||
"gitSettings": "Git",
|
||||
@@ -130,7 +131,8 @@
|
||||
"selectModelFirst": "Please select a model to start chatting...",
|
||||
"sendMessage": "Send message",
|
||||
"stopGeneration": "Stop generation",
|
||||
"running": "Running",
|
||||
"runningTool": "Running {{tool}}...",
|
||||
"waitingForTool": "Waiting for {{tool}}...",
|
||||
"chat": "Chat",
|
||||
"preview": "Preview",
|
||||
"code": "Code",
|
||||
@@ -479,6 +481,26 @@
|
||||
"noPluginsConfigured": "No plugins configured. Add a plugin to get started.",
|
||||
"pluginsDirectory": "Plugins Directory",
|
||||
"pluginsDirectoryDescription": "Directory where plugins are stored in the virtual filesystem.",
|
||||
"discoverPlugins": "Discover Plugins",
|
||||
"discoverPluginsDescription": "Browse and install Shakespeare plugins shared on the Nostr network.",
|
||||
"searchPlugins": "Search plugins...",
|
||||
"noPluginsFound": "No plugins found matching your search.",
|
||||
"noPluginsAvailable": "No plugins available at this time.",
|
||||
"pluginInstalled": "Plugin Installed",
|
||||
"pluginInstalledDescription": "Plugin \"{{name}}\" has been installed successfully.",
|
||||
"pluginInstallFailed": "Failed to Install Plugin",
|
||||
"noCloneUrl": "No Clone URL",
|
||||
"noCloneUrlDescription": "This plugin does not have a clone URL configured.",
|
||||
"installed": "Installed",
|
||||
"install": "Install",
|
||||
"installing": "Installing...",
|
||||
"by": "by",
|
||||
"website": "Website",
|
||||
"loginRequired": "Login Required",
|
||||
"loginToDiscoverPlugins": "Log in with Nostr to discover plugins from people you follow.",
|
||||
"noPluginsFromNetwork": "No Plugins Found",
|
||||
"noPluginsFromNetworkDescription": "No plugins found from people you follow. Follow plugin developers on Nostr to see their plugins here.",
|
||||
"tryDifferentSearch": "Try a different search term.",
|
||||
"mcpServers": "MCP Servers",
|
||||
"mcpServersDescription": "Connect to Model Context Protocol servers to extend the AI's capabilities with external tools.",
|
||||
"addMcpServer": "Add MCP Server",
|
||||
@@ -524,5 +546,27 @@
|
||||
"templateDeleted": "Template Deleted",
|
||||
"templateDeletedDescription": "Project template '{{name}}' has been deleted.",
|
||||
"noTemplatesConfigured": "No project templates configured yet. Add a template to get started.",
|
||||
"atLeastOneTemplateRequired": "At least one template is required"
|
||||
"atLeastOneTemplateRequired": "At least one template is required",
|
||||
"projectLabels": "Project Labels",
|
||||
"manageLabels": "Manage Labels",
|
||||
"createLabel": "Create Label",
|
||||
"labelName": "Label Name",
|
||||
"enterLabelName": "Enter label name",
|
||||
"labelColor": "Color",
|
||||
"deleteLabel": "Delete Label",
|
||||
"deleteLabelConfirmation": "Are you sure you want to delete the label \"{{name}}\"? This will remove the label from all projects.",
|
||||
"noLabelsYet": "No labels yet",
|
||||
"createLabelToOrganize": "Create a label to organize your projects",
|
||||
"addLabel": "Add label",
|
||||
"selectLabels": "Select labels",
|
||||
"noLabelsCreated": "No labels created yet",
|
||||
"createNewLabel": "Create new label",
|
||||
"otherProjects": "Other projects",
|
||||
"duplicateProject": "Duplicate Project",
|
||||
"duplicatingProject": "Duplicating project...",
|
||||
"projectDuplicated": "Project duplicated",
|
||||
"projectDuplicatedDescription": "Project has been duplicated successfully.",
|
||||
"failedToDuplicateProject": "Failed to duplicate project",
|
||||
"newProjectName": "New Project Name",
|
||||
"duplicateProjectDescription": "Create a copy of this project with a new name"
|
||||
}
|
||||
+48
-6
@@ -89,11 +89,10 @@
|
||||
"name": "Suna",
|
||||
"id": "ID",
|
||||
"email": "Imel",
|
||||
"buildNostrApps": "Gina aikace-aikace da AI",
|
||||
"whatToBuild": "Me kuke son ginawa?",
|
||||
"buildApps": "Gina aikace-aikace da AI",
|
||||
"chooseModel": "Zaɓi samfuri...",
|
||||
"selectModelToDescribe": "Da fatan za a zaɓi samfuri a ƙasa, sannan a bayyana abin da kuke son ginawa...",
|
||||
"examplePrompt": "misali, Ƙirƙiri kasuwar kayan aikin noma don manoma na yankin su sayi da sayar da taraktoci, kayan aiki, da kayayyaki...",
|
||||
"selectModelToDescribe": "Zaɓi samfuri a ƙasa don farawa...",
|
||||
"examplePrompt": "Bayyana abin da kuke son ginawa...",
|
||||
"settingsDescription": "Sarrafa saitunan aikace-aikacenku da zaɓuɓɓuka.",
|
||||
"aiSettings": "AI",
|
||||
"aiSettingsDescription": "Saita masu samar da AI da maɓallan API",
|
||||
@@ -125,7 +124,8 @@
|
||||
"selectModelFirst": "Da fatan za a zaɓi samfuri don farawa hira...",
|
||||
"sendMessage": "Aika saƙo",
|
||||
"stopGeneration": "Tsayar da samarwa",
|
||||
"running": "Ana gudana",
|
||||
"runningTool": "Ana gudana {{tool}}...",
|
||||
"waitingForTool": "Ana jiran {{tool}}...",
|
||||
"chat": "Hira",
|
||||
"preview": "Duba",
|
||||
"code": "Lambar",
|
||||
@@ -431,5 +431,47 @@
|
||||
"modified": "An Canza",
|
||||
"restoreToDefault": "Mayar da asali",
|
||||
"restoredToDefault": "An Mayar da Asali",
|
||||
"terminal": "Terminal"
|
||||
"terminal": "Terminal",
|
||||
"projectLabels": "Lakabi na Aiki",
|
||||
"manageLabels": "Sarrafa Lakabi",
|
||||
"createLabel": "Ƙirƙiri Lakabi",
|
||||
"labelName": "Sunan Lakabi",
|
||||
"enterLabelName": "Shigar da sunan lakabi",
|
||||
"labelColor": "Launi",
|
||||
"deleteLabel": "Goge Lakabi",
|
||||
"deleteLabelConfirmation": "Ka tabbata kana son goge lakabi \"{{name}}\"? Wannan zai cire lakabi daga duk ayyuka.",
|
||||
"noLabelsYet": "Babu lakabi tukuna",
|
||||
"createLabelToOrganize": "Ƙirƙiri lakabi don tsara ayyukanka",
|
||||
"addLabel": "Ƙara lakabi",
|
||||
"selectLabels": "Zaɓi lakabi",
|
||||
"noLabelsCreated": "Ba a ƙirƙiri lakabi tukuna ba",
|
||||
"createNewLabel": "Ƙirƙiri sabon lakabi",
|
||||
"otherProjects": "Sauran ayyuka",
|
||||
"discoverPlugins": "Gano Plugins",
|
||||
"discoverPluginsDescription": "Bincika kuma shigar da plugins na Shakespeare da aka raba akan hanyar sadarwa ta Nostr.",
|
||||
"searchPlugins": "Bincika plugins...",
|
||||
"noPluginsFound": "Ba a sami plugins da suka dace da bincikenka ba.",
|
||||
"noPluginsAvailable": "Babu plugins a wannan lokaci.",
|
||||
"pluginInstalled": "An Shigar da Plugin",
|
||||
"pluginInstalledDescription": "An shigar da plugin \"{{name}}\" cikin nasara.",
|
||||
"pluginInstallFailed": "An Kasa Shigar da Plugin",
|
||||
"noCloneUrl": "Babu Clone URL",
|
||||
"noCloneUrlDescription": "Wannan plugin ba shi da clone URL da aka saita.",
|
||||
"installed": "An Shigar",
|
||||
"install": "Shigar",
|
||||
"installing": "Ana Shigarwa...",
|
||||
"by": "ta",
|
||||
"website": "Gidan Yanar Gizo",
|
||||
"loginRequired": "Ana Buƙatar Shiga",
|
||||
"loginToDiscoverPlugins": "Shiga tare da Nostr don gano plugins daga mutanen da kuke bi.",
|
||||
"noPluginsFromNetwork": "Ba a Sami Plugin ba",
|
||||
"noPluginsFromNetworkDescription": "Ba a sami plugins daga mutanen da kuke bi ba. Bi masu haɓaka plugins akan Nostr don ganin plugins nasu a nan.",
|
||||
"tryDifferentSearch": "Gwada kalmar bincike daban.",
|
||||
"duplicateProject": "Kwafin Aikin",
|
||||
"duplicatingProject": "Ana kwafin aikin...",
|
||||
"projectDuplicated": "An kwafi aikin",
|
||||
"projectDuplicatedDescription": "An kwafi aikin cikin nasara.",
|
||||
"failedToDuplicateProject": "An kasa kwafin aikin",
|
||||
"newProjectName": "Sunan Sabon Aikin",
|
||||
"duplicateProjectDescription": "Ƙirƙiri kwafin wannan aikin da sabon suna"
|
||||
}
|
||||
+48
-6
@@ -89,11 +89,10 @@
|
||||
"name": "Aha",
|
||||
"id": "ID",
|
||||
"email": "Ozi-eletrọniki",
|
||||
"buildNostrApps": "Wuo ngwa na AI",
|
||||
"whatToBuild": "Gịnị ka ị chọrọ iwu?",
|
||||
"buildApps": "Wuo ngwa na AI",
|
||||
"chooseModel": "Họrọ ụdịdị...",
|
||||
"selectModelToDescribe": "Biko họrọ ụdịdị n'okpuru, wee kọwaa ihe ị chọrọ iwu...",
|
||||
"examplePrompt": "ọmụmaatụ, Mepụta ahịa ngwá ọrụ ugbo maka ndị ọrụ ugbo mpaghara ịzụta na ire traktọ, ngwá ọrụ, na ngwa...",
|
||||
"selectModelToDescribe": "Họrọ ụdịdị n'okpuru iji malite...",
|
||||
"examplePrompt": "Kọwaa ihe ị chọrọ iwu...",
|
||||
"settingsDescription": "Jikwaa ntọala ngwa gị na nhọrọ.",
|
||||
"aiSettings": "AI",
|
||||
"aiSettingsDescription": "Hazie ndị na-enye AI na igodo API",
|
||||
@@ -125,7 +124,8 @@
|
||||
"selectModelFirst": "Biko họrọ ụdịdị iji malite ikwu okwu...",
|
||||
"sendMessage": "Ziga ozi",
|
||||
"stopGeneration": "Kwụsị mmepụta",
|
||||
"running": "Na-agba ọsọ",
|
||||
"runningTool": "Na-agba ọsọ {{tool}}...",
|
||||
"waitingForTool": "Na-eche {{tool}}...",
|
||||
"chat": "Nkata",
|
||||
"preview": "Nlele",
|
||||
"code": "Koodu",
|
||||
@@ -428,5 +428,47 @@
|
||||
"modified": "Gbanwere",
|
||||
"restoreToDefault": "Weghachi na nke mbụ",
|
||||
"restoredToDefault": "Weghachiri na Nke Mbụ",
|
||||
"terminal": "Terminal"
|
||||
"terminal": "Terminal",
|
||||
"projectLabels": "Akara Ọrụ",
|
||||
"manageLabels": "Jikwaa Akara",
|
||||
"createLabel": "Mepụta Akara",
|
||||
"labelName": "Aha Akara",
|
||||
"enterLabelName": "Tinye aha akara",
|
||||
"labelColor": "Agba",
|
||||
"deleteLabel": "Hichapụ Akara",
|
||||
"deleteLabelConfirmation": "Ị jiri n'ezie chọrọ ihichapụ akara \"{{name}}\"? Nke a ga-ewepụ akara ahụ n'ọrụ niile.",
|
||||
"noLabelsYet": "Enweghị akara ugbu a",
|
||||
"createLabelToOrganize": "Mepụta akara iji hazie ọrụ gị",
|
||||
"addLabel": "Tinye akara",
|
||||
"selectLabels": "Họrọ akara",
|
||||
"noLabelsCreated": "Emepụtaghị akara ọ bụla",
|
||||
"createNewLabel": "Mepụta akara ọhụrụ",
|
||||
"otherProjects": "Ọrụ ndị ọzọ",
|
||||
"discoverPlugins": "Chọpụta Plugins",
|
||||
"discoverPluginsDescription": "Chọgharịa ma wụnye plugins Shakespeare nke ekekọrịtara na netwọk Nostr.",
|
||||
"searchPlugins": "Chọọ plugins...",
|
||||
"noPluginsFound": "Achọtaghị plugins dabara na nchọgharị gị.",
|
||||
"noPluginsAvailable": "Enweghị plugins dị ugbu a.",
|
||||
"pluginInstalled": "Ewubatara Plugin",
|
||||
"pluginInstalledDescription": "Ewubatara plugin \"{{name}}\" nke ọma.",
|
||||
"pluginInstallFailed": "Ọ Dara Ada Ịwụnye Plugin",
|
||||
"noCloneUrl": "Enweghị Clone URL",
|
||||
"noCloneUrlDescription": "Plugin a enweghị clone URL edoziri.",
|
||||
"installed": "Ewubatara",
|
||||
"install": "Wụnye",
|
||||
"installing": "Na-ewunye...",
|
||||
"by": "site na",
|
||||
"website": "Webụsaịtị",
|
||||
"loginRequired": "Achọrọ Nbanye",
|
||||
"loginToDiscoverPlugins": "Banye na Nostr iji chọpụta plugins sitere na ndị ị na-eso.",
|
||||
"noPluginsFromNetwork": "Achọtaghị Plugins",
|
||||
"noPluginsFromNetworkDescription": "Achọtaghị plugins sitere na ndị ị na-eso. Soro ndị mmepe plugin na Nostr iji hụ plugins ha ebe a.",
|
||||
"tryDifferentSearch": "Gbalịa okwu nchọgharị dị iche.",
|
||||
"duplicateProject": "Mepụta Ọrụ",
|
||||
"duplicatingProject": "Na-emepụta ọrụ...",
|
||||
"projectDuplicated": "Emepụtara ọrụ",
|
||||
"projectDuplicatedDescription": "Emepụtara ọrụ nke ọma.",
|
||||
"failedToDuplicateProject": "Ọ dara ada imepụta ọrụ",
|
||||
"newProjectName": "Aha Ọrụ Ọhụrụ",
|
||||
"duplicateProjectDescription": "Mepụta oyiri nke ọrụ a na aha ọhụrụ"
|
||||
}
|
||||
+48
-6
@@ -89,11 +89,10 @@
|
||||
"name": "Nome",
|
||||
"id": "ID",
|
||||
"email": "Email",
|
||||
"buildNostrApps": "Construa aplicativos com IA",
|
||||
"whatToBuild": "O que você gostaria de construir?",
|
||||
"buildApps": "Construa aplicativos com IA",
|
||||
"chooseModel": "Escolha um modelo...",
|
||||
"selectModelToDescribe": "Por favor, selecione um modelo abaixo e depois descreva o que gostaria de construir...",
|
||||
"examplePrompt": "ex., Criar um marketplace de equipamentos agrícolas para fazendeiros locais comprarem e venderem tratores, ferramentas e suprimentos...",
|
||||
"selectModelToDescribe": "Selecione um modelo abaixo para começar...",
|
||||
"examplePrompt": "Descreva o que você gostaria de construir...",
|
||||
"settingsDescription": "Gerencie as configurações e preferências da aplicação.",
|
||||
"aiSettings": "IA",
|
||||
"aiSettingsDescription": "Configure provedores de IA e chaves de API",
|
||||
@@ -127,7 +126,8 @@
|
||||
"selectModelFirst": "Selecione um modelo para começar a conversar...",
|
||||
"sendMessage": "Enviar mensagem",
|
||||
"stopGeneration": "Parar geração",
|
||||
"running": "Executando",
|
||||
"runningTool": "Executando {{tool}}...",
|
||||
"waitingForTool": "Aguardando {{tool}}...",
|
||||
"chat": "Chat",
|
||||
"preview": "Visualização",
|
||||
"code": "Código",
|
||||
@@ -440,5 +440,47 @@
|
||||
"modified": "Modificado",
|
||||
"restoreToDefault": "Restaurar para padrão",
|
||||
"restoredToDefault": "Restaurado para Padrão",
|
||||
"terminal": "Terminal"
|
||||
"terminal": "Terminal",
|
||||
"projectLabels": "Etiquetas de Projeto",
|
||||
"manageLabels": "Gerenciar Etiquetas",
|
||||
"createLabel": "Criar Etiqueta",
|
||||
"labelName": "Nome da Etiqueta",
|
||||
"enterLabelName": "Digite o nome da etiqueta",
|
||||
"labelColor": "Cor",
|
||||
"deleteLabel": "Excluir Etiqueta",
|
||||
"deleteLabelConfirmation": "Tem certeza de que deseja excluir a etiqueta \"{{name}}\"? Isso removerá a etiqueta de todos os projetos.",
|
||||
"noLabelsYet": "Nenhuma etiqueta ainda",
|
||||
"createLabelToOrganize": "Crie uma etiqueta para organizar seus projetos",
|
||||
"addLabel": "Adicionar etiqueta",
|
||||
"selectLabels": "Selecionar etiquetas",
|
||||
"noLabelsCreated": "Nenhuma etiqueta criada ainda",
|
||||
"createNewLabel": "Criar nova etiqueta",
|
||||
"otherProjects": "Outros projetos",
|
||||
"discoverPlugins": "Descobrir Plugins",
|
||||
"discoverPluginsDescription": "Navegue e instale plugins do Shakespeare compartilhados na rede Nostr.",
|
||||
"searchPlugins": "Buscar plugins...",
|
||||
"noPluginsFound": "Nenhum plugin encontrado correspondente à sua busca.",
|
||||
"noPluginsAvailable": "Nenhum plugin disponível no momento.",
|
||||
"pluginInstalled": "Plugin Instalado",
|
||||
"pluginInstalledDescription": "Plugin \"{{name}}\" foi instalado com sucesso.",
|
||||
"pluginInstallFailed": "Falha ao Instalar Plugin",
|
||||
"noCloneUrl": "Sem URL de Clone",
|
||||
"noCloneUrlDescription": "Este plugin não tem uma URL de clone configurada.",
|
||||
"installed": "Instalado",
|
||||
"install": "Instalar",
|
||||
"installing": "Instalando...",
|
||||
"by": "por",
|
||||
"website": "Site",
|
||||
"loginRequired": "Login Necessário",
|
||||
"loginToDiscoverPlugins": "Faça login com Nostr para descobrir plugins de pessoas que você segue.",
|
||||
"noPluginsFromNetwork": "Nenhum Plugin Encontrado",
|
||||
"noPluginsFromNetworkDescription": "Nenhum plugin encontrado de pessoas que você segue. Siga desenvolvedores de plugins no Nostr para ver seus plugins aqui.",
|
||||
"tryDifferentSearch": "Tente um termo de busca diferente.",
|
||||
"duplicateProject": "Duplicar Projeto",
|
||||
"duplicatingProject": "Duplicando projeto...",
|
||||
"projectDuplicated": "Projeto duplicado",
|
||||
"projectDuplicatedDescription": "O projeto foi duplicado com sucesso.",
|
||||
"failedToDuplicateProject": "Falha ao duplicar projeto",
|
||||
"newProjectName": "Nome do Novo Projeto",
|
||||
"duplicateProjectDescription": "Criar uma cópia deste projeto com um novo nome"
|
||||
}
|
||||
+48
-6
@@ -89,11 +89,10 @@
|
||||
"name": "Orukọ",
|
||||
"id": "ID",
|
||||
"email": "Imeeli",
|
||||
"buildNostrApps": "Kọ awọn ohun elo pẹlu AI",
|
||||
"whatToBuild": "Kini o fẹ kọ?",
|
||||
"buildApps": "Kọ awọn ohun elo pẹlu AI",
|
||||
"chooseModel": "Yan awoṣe...",
|
||||
"selectModelToDescribe": "Jọwọ yan awoṣe ni isalẹ, lẹhinna ṣapejuwe ohun ti o fẹ kọ...",
|
||||
"examplePrompt": "apeere, Ṣẹda ọja ẹrọ ogbin fun awọn agbe agbegbe lati ra ati ta awọn traktọ, awọn irinṣẹ, ati awọn ipese...",
|
||||
"selectModelToDescribe": "Yan awoṣe ni isalẹ lati bẹrẹ...",
|
||||
"examplePrompt": "Ṣapejuwe ohun ti o fẹ kọ...",
|
||||
"settingsDescription": "Ṣakoso awọn eto ohun elo rẹ ati awọn ayanfẹ.",
|
||||
"aiSettings": "AI",
|
||||
"aiSettingsDescription": "Tunto awọn olupese AI ati awọn bọtini API",
|
||||
@@ -125,7 +124,8 @@
|
||||
"selectModelFirst": "Jọwọ yan awoṣe lati bẹrẹ ibaraẹnisọrọ...",
|
||||
"sendMessage": "Fi ifiranṣẹ ranṣẹ",
|
||||
"stopGeneration": "Duro ṣiṣẹda",
|
||||
"running": "N ṣiṣẹ",
|
||||
"runningTool": "N ṣiṣẹ {{tool}}...",
|
||||
"waitingForTool": "N duro de {{tool}}...",
|
||||
"chat": "Ibaraẹnisọrọ",
|
||||
"preview": "Aṣaju wiwo",
|
||||
"code": "Koodu",
|
||||
@@ -428,5 +428,47 @@
|
||||
"modified": "Ti Yipada",
|
||||
"restoreToDefault": "Pada si atilẹwa",
|
||||
"restoredToDefault": "Ti Pada si Atilẹwa",
|
||||
"terminal": "Terminal"
|
||||
"terminal": "Terminal",
|
||||
"projectLabels": "Àmì Ìṣẹ́",
|
||||
"manageLabels": "Ṣàkóso Àmì",
|
||||
"createLabel": "Ṣẹ̀dá Àmì",
|
||||
"labelName": "Orúkọ Àmì",
|
||||
"enterLabelName": "Tẹ orúkọ àmì",
|
||||
"labelColor": "Àwọ̀",
|
||||
"deleteLabel": "Pa Àmì rẹ́",
|
||||
"deleteLabelConfirmation": "Ṣé o dá a lójú pé o fẹ́ pa àmì \"{{name}}\" rẹ́? Èyí yóò yọ àmì náà kúrò nínú gbogbo iṣẹ́.",
|
||||
"noLabelsYet": "Kò sí àmì síbẹ̀",
|
||||
"createLabelToOrganize": "Ṣẹ̀dá àmì láti ṣètò àwọn iṣẹ́ rẹ",
|
||||
"addLabel": "Fi àmì kún",
|
||||
"selectLabels": "Yan àmì",
|
||||
"noLabelsCreated": "A kò tí ì ṣẹ̀dá àmì kankan",
|
||||
"createNewLabel": "Ṣẹ̀dá àmì tuntun",
|
||||
"otherProjects": "Àwọn iṣẹ́ mìíràn",
|
||||
"discoverPlugins": "Ṣawari Awọn Plugins",
|
||||
"discoverPluginsDescription": "Ṣayẹwo ati fi sori ẹrọ awọn plugins Shakespeare ti a pin lori nẹtiwọọki Nostr.",
|
||||
"searchPlugins": "Wa awọn plugins...",
|
||||
"noPluginsFound": "Ko si awọn plugins ti o baamu wiwa rẹ.",
|
||||
"noPluginsAvailable": "Ko si awọn plugins ti o wa ni akoko yii.",
|
||||
"pluginInstalled": "Plugin Ti Fi Sori Ẹrọ",
|
||||
"pluginInstalledDescription": "A ti fi plugin \"{{name}}\" sori ẹrọ ni aṣeyọri.",
|
||||
"pluginInstallFailed": "O Kuna Lati Fi Plugin Sori Ẹrọ",
|
||||
"noCloneUrl": "Ko Si Clone URL",
|
||||
"noCloneUrlDescription": "Plugin yii ko ni clone URL ti a ṣeto.",
|
||||
"installed": "Ti Fi Sori Ẹrọ",
|
||||
"install": "Fi Sori Ẹrọ",
|
||||
"installing": "N Fi Sori Ẹrọ...",
|
||||
"by": "nipasẹ",
|
||||
"website": "Oju opo wẹẹbu",
|
||||
"loginRequired": "Wiwọle Nilo",
|
||||
"loginToDiscoverPlugins": "Wọle pẹlu Nostr lati ṣawari awọn plugins lati ọdọ awọn eniyan ti o ntẹle.",
|
||||
"noPluginsFromNetwork": "Ko Ri Plugins",
|
||||
"noPluginsFromNetworkDescription": "Ko ri awọn plugins lati ọdọ awọn eniyan ti o ntẹle. Tẹle awọn olupilẹṣẹ plugin lori Nostr lati rii awọn plugins wọn nibi.",
|
||||
"tryDifferentSearch": "Gbiyanju ọrọ wiwa miiran.",
|
||||
"duplicateProject": "Ṣe Ẹda Iṣẹ Akanṣe",
|
||||
"duplicatingProject": "N ṣe ẹda iṣẹ akanṣe...",
|
||||
"projectDuplicated": "Iṣẹ akanṣe ti ṣe ẹda",
|
||||
"projectDuplicatedDescription": "Iṣẹ akanṣe ti ṣe ẹda ni aṣeyọri.",
|
||||
"failedToDuplicateProject": "O kuna lati ṣe ẹda iṣẹ akanṣe",
|
||||
"newProjectName": "Orukọ Iṣẹ Akanṣe Tuntun",
|
||||
"duplicateProjectDescription": "Ṣẹda ẹda ti iṣẹ akanṣe yii pẹlu orukọ tuntun"
|
||||
}
|
||||
+48
-6
@@ -89,11 +89,10 @@
|
||||
"name": "名称",
|
||||
"id": "ID",
|
||||
"email": "邮箱",
|
||||
"buildNostrApps": "使用AI构建应用",
|
||||
"whatToBuild": "您想构建什么?",
|
||||
"buildApps": "使用AI构建应用",
|
||||
"chooseModel": "选择模型...",
|
||||
"selectModelToDescribe": "请在下方选择一个模型,然后描述您想要构建的内容...",
|
||||
"examplePrompt": "例如:为当地农民创建一个农业设备市场,用于买卖拖拉机、工具和用品...",
|
||||
"selectModelToDescribe": "请选择下方的模型以开始...",
|
||||
"examplePrompt": "描述您想要构建的内容...",
|
||||
"settingsDescription": "管理您的应用程序设置和偏好。",
|
||||
"aiSettings": "AI",
|
||||
"aiSettingsDescription": "配置AI提供商和API密钥",
|
||||
@@ -127,7 +126,8 @@
|
||||
"selectModelFirst": "请先选择一个模型开始聊天...",
|
||||
"sendMessage": "发送消息",
|
||||
"stopGeneration": "停止生成",
|
||||
"running": "运行中",
|
||||
"runningTool": "运行{{tool}}中...",
|
||||
"waitingForTool": "等待{{tool}}...",
|
||||
"chat": "聊天",
|
||||
"preview": "预览",
|
||||
"code": "代码",
|
||||
@@ -440,5 +440,47 @@
|
||||
"modified": "已修改",
|
||||
"restoreToDefault": "恢复默认值",
|
||||
"restoredToDefault": "已恢复默认值",
|
||||
"terminal": "终端"
|
||||
"terminal": "终端",
|
||||
"projectLabels": "项目标签",
|
||||
"manageLabels": "管理标签",
|
||||
"createLabel": "创建标签",
|
||||
"labelName": "标签名称",
|
||||
"enterLabelName": "输入标签名称",
|
||||
"labelColor": "颜色",
|
||||
"deleteLabel": "删除标签",
|
||||
"deleteLabelConfirmation": "确定要删除标签 \"{{name}}\" 吗?这将从所有项目中移除该标签。",
|
||||
"noLabelsYet": "暂无标签",
|
||||
"createLabelToOrganize": "创建标签来组织您的项目",
|
||||
"addLabel": "添加标签",
|
||||
"selectLabels": "选择标签",
|
||||
"noLabelsCreated": "尚未创建标签",
|
||||
"createNewLabel": "创建新标签",
|
||||
"otherProjects": "其他项目",
|
||||
"discoverPlugins": "发现插件",
|
||||
"discoverPluginsDescription": "浏览并安装在 Nostr 网络上共享的 Shakespeare 插件。",
|
||||
"searchPlugins": "搜索插件...",
|
||||
"noPluginsFound": "未找到与您搜索匹配的插件。",
|
||||
"noPluginsAvailable": "目前没有可用的插件。",
|
||||
"pluginInstalled": "插件已安装",
|
||||
"pluginInstalledDescription": "插件 \"{{name}}\" 已成功安装。",
|
||||
"pluginInstallFailed": "安装插件失败",
|
||||
"noCloneUrl": "无克隆 URL",
|
||||
"noCloneUrlDescription": "此插件未配置克隆 URL。",
|
||||
"installed": "已安装",
|
||||
"install": "安装",
|
||||
"installing": "安装中...",
|
||||
"by": "作者",
|
||||
"website": "网站",
|
||||
"loginRequired": "需要登录",
|
||||
"loginToDiscoverPlugins": "使用 Nostr 登录以发现您关注的人的插件。",
|
||||
"noPluginsFromNetwork": "未找到插件",
|
||||
"noPluginsFromNetworkDescription": "未找到您关注的人的插件。在 Nostr 上关注插件开发者以在此处查看他们的插件。",
|
||||
"tryDifferentSearch": "尝试不同的搜索词。",
|
||||
"duplicateProject": "复制项目",
|
||||
"duplicatingProject": "正在复制项目...",
|
||||
"projectDuplicated": "项目已复制",
|
||||
"projectDuplicatedDescription": "项目已成功复制。",
|
||||
"failedToDuplicateProject": "复制项目失败",
|
||||
"newProjectName": "新项目名称",
|
||||
"duplicateProjectDescription": "使用新名称创建此项目的副本"
|
||||
}
|
||||
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user