Compare commits

..
Author SHA1 Message Date
lemonknowsall 31b2a1eb4e windows path resolution for electron 2025-12-18 21:40:20 -08:00
126 changed files with 13286 additions and 5882 deletions

No files matched your search

+2 -1
View File
@@ -41,6 +41,7 @@ Shakespeare provides AI agents with specialized tools for project development (n
- **NpmAddPackageTool**: Add npm packages to projects
- **NpmRemovePackageTool**: Remove npm packages from projects
- **GitCommitTool**: Commit changes to Git repositories
- **DeployProjectTool**: Deploy projects to hosting platforms
- **ReadWebpageTool**: Fetch and read web pages
- **NostrReadNipTool**: Read Nostr protocol NIP documents
- **NostrReadKindTool**: Read Nostr event kind documentation
@@ -239,7 +240,7 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
- Unix-style commands: `cat`, `cd`, `cp`, `find`, `grep`, `ls`, `mkdir`, `mv`, `rm`, etc.
- `/src/lib/tools/`: AI tool implementations for project development
- File operations: `TextEditorViewTool`, `TextEditorWriteTool`, `TextEditorStrReplaceTool`
- Project tools: `BuildProjectTool`
- Project tools: `BuildProjectTool`, `DeployProjectTool`
- Package management: `NpmAddPackageTool`, `NpmRemovePackageTool`
- Git integration: `GitCommitTool`
- Shell access: `ShellTool`
+35 -20
View File
@@ -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', {
+123 -203
View File
@@ -18,8 +18,8 @@
"@isomorphic-git/lightning-fs": "^4.6.2",
"@modelcontextprotocol/sdk": "^1.22.0",
"@mozilla/readability": "^0.6.0",
"@nostrify/nostrify": "^0.48.2",
"@nostrify/react": "^0.2.20",
"@nostrify/nostrify": "^0.47.1",
"@nostrify/react": "^0.2.17",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -66,7 +66,7 @@
"isomorphic-git": "^1.32.1",
"jsonc-parser": "^3.3.1",
"jszip": "^3.10.1",
"lucide-react": "^0.562.0",
"lucide-react": "^0.525.0",
"mime": "^4.1.0",
"nostr-tools": "^2.15.2",
"nunjucks": "^3.2.4",
@@ -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",
@@ -2471,9 +2475,9 @@
}
},
"node_modules/@eslint/core": {
"version": "0.15.2",
"resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.15.2.tgz",
"integrity": "sha512-78Md3/Rrxh83gCxoUc0EiciuOHsIITzLy53m3d9UyiW8y9Dj2D29FeETqyKA+BRK76tnTp6RXWb3pCay8Oyomg==",
"version": "0.15.1",
"resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.15.1.tgz",
"integrity": "sha512-bkOp+iumZCCbt1K1CmWf0R9pM5yKpDv+ZXtvSyQpudrI9kuFLp+bM2WOPXImuD/ceQuaa8f5pj93Y7zyECIGNA==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
@@ -2554,13 +2558,13 @@
}
},
"node_modules/@eslint/plugin-kit": {
"version": "0.3.5",
"resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.3.5.tgz",
"integrity": "sha512-Z5kJ+wU3oA7MMIqVR9tyZRtjYPr4OC004Q4Rw7pgOKUOKkJfZ3O24nz3WYfGRpMDNmcOi3TwQOmgm7B7Tpii0w==",
"version": "0.3.3",
"resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.3.3.tgz",
"integrity": "sha512-1+WqvgNMhmlAambTvT3KPtCl/Ibr68VldY2XY40SL1CE0ZXiakFR/cbTspaF5HsnpDMvcYYoJHfl4980NBjGag==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"@eslint/core": "^0.15.2",
"@eslint/core": "^0.15.1",
"levn": "^0.4.1"
},
"engines": {
@@ -2644,18 +2648,6 @@
"url": "lightning:[email protected]"
}
},
"node_modules/@hono/node-server": {
"version": "1.19.7",
"resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.7.tgz",
"integrity": "sha512-vUcD0uauS7EU2caukW8z5lJKtoGMokxNbJtBiwHgpqxEXokaHCBkQUmCHhjFB1VUTWdqj25QoMkMKzgjq+uhrw==",
"license": "MIT",
"engines": {
"node": ">=18.14.1"
},
"peerDependencies": {
"hono": "^4"
}
},
"node_modules/@hookform/resolvers": {
"version": "3.10.0",
"resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-3.10.0.tgz",
@@ -2880,12 +2872,11 @@
"license": "BSD-2-Clause"
},
"node_modules/@modelcontextprotocol/sdk": {
"version": "1.25.1",
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.25.1.tgz",
"integrity": "sha512-yO28oVFFC7EBoiKdAn+VqRm+plcfv4v0xp6osG/VsCB0NlPZWi87ajbCZZ8f/RvOFLEu7//rSRmuZZ7lMoe3gQ==",
"version": "1.22.0",
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.22.0.tgz",
"integrity": "sha512-VUpl106XVTCpDmTBil2ehgJZjhyLY2QZikzF8NvTXtLRF1CvO5iEE2UNZdVIUer35vFOwMKYeUGbjJtvPWan3g==",
"license": "MIT",
"dependencies": {
"@hono/node-server": "^1.19.7",
"ajv": "^8.17.1",
"ajv-formats": "^3.0.1",
"content-type": "^1.0.5",
@@ -2895,26 +2886,20 @@
"eventsource-parser": "^3.0.0",
"express": "^5.0.1",
"express-rate-limit": "^7.5.0",
"jose": "^6.1.1",
"json-schema-typed": "^8.0.2",
"pkce-challenge": "^5.0.0",
"raw-body": "^3.0.0",
"zod": "^3.25 || ^4.0",
"zod-to-json-schema": "^3.25.0"
"zod": "^3.23.8",
"zod-to-json-schema": "^3.24.1"
},
"engines": {
"node": ">=18"
},
"peerDependencies": {
"@cfworker/json-schema": "^4.1.1",
"zod": "^3.25 || ^4.0"
"@cfworker/json-schema": "^4.1.1"
},
"peerDependenciesMeta": {
"@cfworker/json-schema": {
"optional": true
},
"zod": {
"optional": false
}
}
},
@@ -3030,14 +3015,13 @@
}
},
"node_modules/@nostrify/nostrify": {
"version": "0.48.2",
"resolved": "https://registry.npmjs.org/@nostrify/nostrify/-/nostrify-0.48.2.tgz",
"integrity": "sha512-Zze3RASsgn4MLQCuC5I4XR0WJi9G3J8qZpVjVIPvkw6vbZRct++JgavcZSxwKjJH1hHq+8d90IrHMOrskNQ8NQ==",
"version": "0.47.1",
"resolved": "https://registry.npmjs.org/@nostrify/nostrify/-/nostrify-0.47.1.tgz",
"integrity": "sha512-8jdAeKIyyDK/UQN92WgrQn9+B067HYcjfW35TpIjNLAT9qYe+KYFHaC9O6PD+I1DvLHziJMxk4Q18Fu4fqOiAQ==",
"dependencies": {
"@nostrify/types": "0.36.8",
"@scure/base": "^2.0.0",
"@smithy/util-base64": "^4.3.0",
"@smithy/util-hex-encoding": "^4.2.0",
"@nostrify/types": "0.36.7",
"@scure/base": "^1.2.6",
"@std/encoding": "npm:@jsr/std__encoding@^0.224.1",
"@types/node": "^24.1.0",
"lru-cache": "^10.2.0",
"nostr-tools": "^2.13.0",
@@ -3047,18 +3031,24 @@
}
},
"node_modules/@nostrify/nostrify/node_modules/@scure/base": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/@scure/base/-/base-2.0.0.tgz",
"integrity": "sha512-3E1kpuZginKkek01ovG8krQ0Z44E3DHPjc5S2rjJw9lZn3KSQOs8S7wqikF/AH7iRanHypj85uGyxk0XAyC37w==",
"version": "1.2.6",
"resolved": "https://registry.npmjs.org/@scure/base/-/base-1.2.6.tgz",
"integrity": "sha512-g/nm5FgUa//MCj1gV09zTJTaM6KBAHqLN907YVQqf7zC49+DcO4B1so4ZX07Ef10Twr6nuqYEH9GEggFXA4Fmg==",
"license": "MIT",
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@nostrify/nostrify/node_modules/@std/encoding": {
"name": "@jsr/std__encoding",
"version": "0.224.3",
"resolved": "https://npm.jsr.io/~/11/@jsr/std__encoding/0.224.3.tgz",
"integrity": "sha512-zAuX2QV1zwJ5RSmrnDGVerAtN3pBXpYYNlGzhERW9AiQ1UJd2/xruyB3i5NdTWy2OK2pjETswOj+0+prYTPlxQ=="
},
"node_modules/@nostrify/nostrify/node_modules/@types/node": {
"version": "24.10.4",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.10.4.tgz",
"integrity": "sha512-vnDVpYPMzs4wunl27jHrfmwojOGKya0xyM3sH+UE5iv5uPS6vX7UIoh6m+vQc5LGBq52HBKPIn/zcSZVzeDEZg==",
"version": "24.9.2",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.9.2.tgz",
"integrity": "sha512-uWN8YqxXxqFMX2RqGOrumsKeti4LlmIMIyV0lgut4jx7KQBcBiW6vkDtIBvHnHIquwNfJhk8v2OtmO8zXWHfPA==",
"license": "MIT",
"dependencies": {
"undici-types": "~7.16.0"
@@ -3071,22 +3061,23 @@
"license": "MIT"
},
"node_modules/@nostrify/react": {
"version": "0.2.20",
"resolved": "https://registry.npmjs.org/@nostrify/react/-/react-0.2.20.tgz",
"integrity": "sha512-Tvkdr5X+MQxh6CKKthk9Idch3vFp5nPcm57uJZJWrIqBtuj9jxMamM6uEo2lQAr0ugK52xDlyD50lRDRe0RMbQ==",
"version": "0.2.17",
"resolved": "https://registry.npmjs.org/@nostrify/react/-/react-0.2.17.tgz",
"integrity": "sha512-IG6XPiNBe1nDFZ055EnWufxASPjgOZ2cE53Hjanj5xQQURwzA946yMhDDzaHmD9lvoBYjuijopmTiyFk2RObHQ==",
"dependencies": {
"@nostrify/nostrify": "0.48.2",
"@nostrify/types": "0.36.8",
"@nostrify/nostrify": "0.47.1",
"@nostrify/types": "0.36.7",
"@tanstack/react-query": "^5.69.0",
"happy-dom": "^17.4.4",
"nostr-tools": "^2.13.0",
"react": "^18.0.0",
"react-dom": "^18.0.0"
}
},
"node_modules/@nostrify/types": {
"version": "0.36.8",
"resolved": "https://registry.npmjs.org/@nostrify/types/-/types-0.36.8.tgz",
"integrity": "sha512-tmpz5pkU8oXu7+V1qxvAzuoo8s5x4Gvo7h+JRm+JAW6x/2VZ8aQoA54yhn89qZ9agciMJhVdhqCm1PlK55w17A=="
"version": "0.36.7",
"resolved": "https://registry.npmjs.org/@nostrify/types/-/types-0.36.7.tgz",
"integrity": "sha512-Jdf2eWdIzonMzic/st4ltre7XIcXVNTjmcbKpw4xGEfNmoq2Y4wj8KcSB6s0TUqxcLEyiXnyGP8EDx/gEVri9A=="
},
"node_modules/@pkgjs/parseargs": {
"version": "0.11.0",
@@ -5052,70 +5043,6 @@
"url": "https://github.com/sindresorhus/is?sponsor=1"
}
},
"node_modules/@smithy/is-array-buffer": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-4.2.0.tgz",
"integrity": "sha512-DZZZBvC7sjcYh4MazJSGiWMI2L7E0oCiRHREDzIxi/M2LY79/21iXt6aPLHge82wi5LsuRF5A06Ds3+0mlh6CQ==",
"license": "Apache-2.0",
"dependencies": {
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@smithy/util-base64": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/@smithy/util-base64/-/util-base64-4.3.0.tgz",
"integrity": "sha512-GkXZ59JfyxsIwNTWFnjmFEI8kZpRNIBfxKjv09+nkAWPt/4aGaEWMM04m4sxgNVWkbt2MdSvE3KF/PfX4nFedQ==",
"license": "Apache-2.0",
"dependencies": {
"@smithy/util-buffer-from": "^4.2.0",
"@smithy/util-utf8": "^4.2.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@smithy/util-buffer-from": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-4.2.0.tgz",
"integrity": "sha512-kAY9hTKulTNevM2nlRtxAG2FQ3B2OR6QIrPY3zE5LqJy1oxzmgBGsHLWTcNhWXKchgA0WHW+mZkQrng/pgcCew==",
"license": "Apache-2.0",
"dependencies": {
"@smithy/is-array-buffer": "^4.2.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@smithy/util-hex-encoding": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/@smithy/util-hex-encoding/-/util-hex-encoding-4.2.0.tgz",
"integrity": "sha512-CCQBwJIvXMLKxVbO88IukazJD9a4kQ9ZN7/UMGBjBcJYvatpWk+9g870El4cB8/EJxfe+k+y0GmR9CAzkF+Nbw==",
"license": "Apache-2.0",
"dependencies": {
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@smithy/util-utf8": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-4.2.0.tgz",
"integrity": "sha512-zBPfuzoI8xyBtR2P6WQj63Rz8i3AmfAaJLuNG8dWsfvPe8lO4aCPYLn879mEgHndZH1zQ2oXmG8O1GGzzaoZiw==",
"license": "Apache-2.0",
"dependencies": {
"@smithy/util-buffer-from": "^4.2.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@std/encoding": {
"name": "@jsr/std__encoding",
"version": "1.0.10",
@@ -5536,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",
@@ -5779,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"
@@ -5790,6 +5717,7 @@
"integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",
"devOptional": true,
"license": "MIT",
"peer": true,
"peerDependencies": {
"@types/react": "^18.0.0"
}
@@ -5894,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",
@@ -6253,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"
},
@@ -6685,43 +6615,23 @@
}
},
"node_modules/body-parser": {
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.1.tgz",
"integrity": "sha512-nfDwkulwiZYQIGwxdy0RUmowMhKcFVcYXUU7m4QlKYim1rUtg83xm2yjZ40QjDuc291AJjjeSc9b++AWHSgSHw==",
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.0.tgz",
"integrity": "sha512-02qvAaxv8tp7fBa/mw1ga98OGm+eCbqzJOKoRt70sLmfEEi+jyBYVTDGfCL/k06/4EMk/z01gCe7HoCH/f2LTg==",
"license": "MIT",
"dependencies": {
"bytes": "^3.1.2",
"content-type": "^1.0.5",
"debug": "^4.4.3",
"debug": "^4.4.0",
"http-errors": "^2.0.0",
"iconv-lite": "^0.7.0",
"iconv-lite": "^0.6.3",
"on-finished": "^2.4.1",
"qs": "^6.14.0",
"raw-body": "^3.0.1",
"type-is": "^2.0.1"
"raw-body": "^3.0.0",
"type-is": "^2.0.0"
},
"engines": {
"node": ">=18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/body-parser/node_modules/iconv-lite": {
"version": "0.7.1",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.1.tgz",
"integrity": "sha512-2Tth85cXwGFHfvRgZWszZSvdo+0Xsqmw8k8ZwxScfcBneNUraK+dxRxRm24nszx80Y0TVio8kKLt5sLE7ZCLlw==",
"license": "MIT",
"dependencies": {
"safer-buffer": ">= 2.1.2 < 3.0.0"
},
"engines": {
"node": ">=0.10.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/boolean": {
@@ -6776,6 +6686,7 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"baseline-browser-mapping": "^2.8.19",
"caniuse-lite": "^1.0.30001751",
@@ -7044,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",
@@ -7844,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",
@@ -7929,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",
@@ -8243,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",
@@ -8508,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",
@@ -9067,9 +8981,9 @@
}
},
"node_modules/glob": {
"version": "10.5.0",
"resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz",
"integrity": "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==",
"version": "10.4.5",
"resolved": "https://registry.npmjs.org/glob/-/glob-10.4.5.tgz",
"integrity": "sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg==",
"license": "ISC",
"dependencies": {
"foreground-child": "^3.1.0",
@@ -9248,9 +9162,9 @@
}
},
"node_modules/gray-matter/node_modules/js-yaml": {
"version": "3.14.2",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.2.tgz",
"integrity": "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==",
"version": "3.14.1",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz",
"integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==",
"license": "MIT",
"dependencies": {
"argparse": "^1.0.7",
@@ -9266,6 +9180,28 @@
"integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==",
"license": "BSD-3-Clause"
},
"node_modules/happy-dom": {
"version": "17.6.3",
"resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-17.6.3.tgz",
"integrity": "sha512-UVIHeVhxmxedbWPCfgS55Jg2rDfwf2BCKeylcPSqazLz5w3Kri7Q4xdBJubsr/+VUzFLh0VjIvh13RaDA2/Xug==",
"license": "MIT",
"dependencies": {
"webidl-conversions": "^7.0.0",
"whatwg-mimetype": "^3.0.0"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/happy-dom/node_modules/whatwg-mimetype": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz",
"integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==",
"license": "MIT",
"engines": {
"node": ">=12"
}
},
"node_modules/harden-react-markdown": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/harden-react-markdown/-/harden-react-markdown-1.0.5.tgz",
@@ -9572,16 +9508,6 @@
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
"license": "MIT"
},
"node_modules/hono": {
"version": "4.11.1",
"resolved": "https://registry.npmjs.org/hono/-/hono-4.11.1.tgz",
"integrity": "sha512-KsFcH0xxHes0J4zaQgWbYwmz3UPOOskdqZmItstUG93+Wk1ePBLkLGwbP9zlmh1BFUiL8Qp+Xfu9P7feJWpGNg==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=16.9.0"
}
},
"node_modules/hookable": {
"version": "5.5.3",
"resolved": "https://registry.npmjs.org/hookable/-/hookable-5.5.3.tgz",
@@ -9718,6 +9644,7 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/runtime": "^7.27.6"
},
@@ -9734,7 +9661,6 @@
"version": "0.6.3",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
"integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",
"dev": true,
"license": "MIT",
"dependencies": {
"safer-buffer": ">= 2.1.2 < 3.0.0"
@@ -10477,15 +10403,6 @@
"jiti": "bin/jiti.js"
}
},
"node_modules/jose": {
"version": "6.1.3",
"resolved": "https://registry.npmjs.org/jose/-/jose-6.1.3.tgz",
"integrity": "sha512-0TpaTfihd4QMNwrz/ob2Bp7X04yuxJkjRGi4aKmOqwhov54i6u79oCv7T+C7lo70MKH6BesI3vscD1yb/yzKXQ==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/panva"
}
},
"node_modules/js-tokens": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
@@ -10493,9 +10410,9 @@
"license": "MIT"
},
"node_modules/js-yaml": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",
"integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==",
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz",
"integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -10511,6 +10428,7 @@
"integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"cssstyle": "^4.2.1",
"data-urls": "^5.0.0",
@@ -10578,12 +10496,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/json-schema-typed": {
"version": "8.0.2",
"resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz",
"integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==",
"license": "BSD-2-Clause"
},
"node_modules/json-stable-stringify-without-jsonify": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz",
@@ -10899,9 +10811,9 @@
"license": "ISC"
},
"node_modules/lucide-react": {
"version": "0.562.0",
"resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.562.0.tgz",
"integrity": "sha512-82hOAu7y0dbVuFfmO4bYF1XEwYk/mEbM5E+b1jgci/udUBEE/R7LF5Ip0CCEmXe8AybRM8L+04eP+LGZeDvkiw==",
"version": "0.525.0",
"resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.525.0.tgz",
"integrity": "sha512-Tm1txJ2OkymCGkvwoHt33Y2JpN5xucVq1slHcgE6Lk0WjDfjgKWor5CdVER8U6DvcfMwh4M8XxmpTiyzfmfDYQ==",
"license": "ISC",
"peerDependencies": {
"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"
@@ -10913,7 +10825,6 @@
"integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==",
"dev": true,
"license": "MIT",
"peer": true,
"bin": {
"lz-string": "bin/bin.js"
}
@@ -11323,9 +11234,9 @@
}
},
"node_modules/mdast-util-to-hast": {
"version": "13.2.1",
"resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.1.tgz",
"integrity": "sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==",
"version": "13.2.0",
"resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.0.tgz",
"integrity": "sha512-QGYKEuUsYT9ykKBCMOEDLsU5JRObWQusAolFMeko/tYPufNkRffBAQjIE+99jbA87xv6FgmjLtwjh9wBWajwAA==",
"license": "MIT",
"dependencies": {
"@types/hast": "^3.0.0",
@@ -12711,6 +12622,7 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"nanoid": "^3.3.8",
"picocolors": "^1.1.1",
@@ -12878,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",
@@ -12894,7 +12805,6 @@
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=8"
}
@@ -12905,7 +12815,6 @@
"integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=10"
},
@@ -12918,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",
@@ -13127,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"
},
@@ -13153,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"
@@ -13178,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"
},
@@ -13226,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",
@@ -13807,6 +13719,7 @@
"integrity": "sha512-C5VvvgCCyfyotVITIAv+4efVytl5F7wt+/I2i9q9GZcEXW9BP52YYOXC58igUi+LFZVHukErIIqQSWwv/M3WRw==",
"devOptional": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@types/estree": "1.0.7"
},
@@ -14921,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",
@@ -15124,6 +15038,7 @@
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -15419,6 +15334,7 @@
"integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
"devOptional": true,
"license": "Apache-2.0",
"peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@@ -15941,11 +15857,12 @@
}
},
"node_modules/vite": {
"version": "6.4.1",
"resolved": "https://registry.npmjs.org/vite/-/vite-6.4.1.tgz",
"integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==",
"version": "6.3.5",
"resolved": "https://registry.npmjs.org/vite/-/vite-6.3.5.tgz",
"integrity": "sha512-cZn6NDFE7wdTpINgs++ZJ4N49W2vRp8LCKrn3Ob1kYNtOo21vfDoaV5GzBfLU4MovSAB8uNRm4jgzVQZ+mBzPQ==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"esbuild": "^0.25.0",
"fdir": "^6.4.4",
@@ -16090,6 +16007,7 @@
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -16204,7 +16122,6 @@
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz",
"integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==",
"dev": true,
"license": "BSD-2-Clause",
"engines": {
"node": ">=12"
@@ -16561,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",
@@ -16637,6 +16555,7 @@
"integrity": "sha512-fS6iqSPZDs3dr/y7Od6y5nha8dW1YnbgtsyotCVvoFGKbERG++CVRFv1meyGDE1SNItQA8BrnCw7ScdAhRJ3XQ==",
"dev": true,
"license": "MIT",
"peer": true,
"bin": {
"rollup": "dist/bin/rollup"
},
@@ -17096,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"
}
+3 -3
View File
@@ -31,8 +31,8 @@
"@isomorphic-git/lightning-fs": "^4.6.2",
"@modelcontextprotocol/sdk": "^1.22.0",
"@mozilla/readability": "^0.6.0",
"@nostrify/nostrify": "^0.48.2",
"@nostrify/react": "^0.2.20",
"@nostrify/nostrify": "^0.47.1",
"@nostrify/react": "^0.2.17",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -79,7 +79,7 @@
"isomorphic-git": "^1.32.1",
"jsonc-parser": "^3.3.1",
"jszip": "^3.10.1",
"lucide-react": "^0.562.0",
"lucide-react": "^0.525.0",
"mime": "^4.1.0",
"nostr-tools": "^2.15.2",
"nunjucks": "^3.2.4",
+6 -11
View File
@@ -23,14 +23,6 @@ export default {
} catch {
return new Response('Invalid url parameter', { status: 400 });
}
// GitHub hack: neutral color for light/dark mode
if (url.hostname === 'github.com') {
const svg = await (await fetch('https://github.githubassets.com/favicons/favicon.svg')).text();
return new Response(svg.replaceAll('#24292E', '#808080'), {
headers: { 'Content-Type': 'image/svg+xml' },
});
}
// AI-provider-specific hacks
let hostname = url.hostname;
@@ -45,7 +37,10 @@ export default {
// Strip `ai.` and `api.` subdomains for a better chance at finding a favicon
hostname = hostname.replace(/^(ai\.|api\.)/, '');
// Fetch the favicon from DuckDuckGo's service
return fetch(`https://external-content.duckduckgo.com/ip3/${hostname}.ico`);
return fetchFavicon(hostname);
},
};
};
function fetchFavicon(hostname: string): Promise<Response> {
return fetch(`https://external-content.duckduckgo.com/ip3/${hostname}.ico`);
}
@@ -160,6 +160,16 @@ consistent handling of both text and binary data across the messaging protocol.
**Parameters:** None
**Result:** None (notification only)
#### `goBack`
**Purpose:** Navigate back in the iframe's history
**Parameters:** None
**Result:** None (notification only)
#### `goForward`
**Purpose:** Navigate forward in the iframe's history
**Parameters:** None
**Result:** None (notification only)
#### `updateNavigationState`
**Purpose:** Update parent about iframe's current navigation state
**Parameters:**
@@ -193,6 +193,12 @@ class NavigationHandler {
case "refresh":
this.handleRefresh();
break;
case "goBack":
this.handleGoBack();
break;
case "goForward":
this.handleGoForward();
break;
}
}
});
@@ -280,6 +286,14 @@ class NavigationHandler {
window.location.reload();
}
handleGoBack() {
window.history.back();
}
handleGoForward() {
window.history.forward();
}
updateNavigationState() {
// Use tracked semantic path, fallback to current location if needed
const semanticPath = this.currentSemanticPath || this.extractSemanticPath(window.location);
+1 -8
View File
@@ -106,13 +106,6 @@ const defaultConfig: AppConfig = {
],
updatedAt: 0,
},
graspMetadata: {
relays: [
{ url: 'wss://git.shakespeare.diy/' },
{ url: 'wss://relay.ngit.dev/' },
],
updatedAt: 0,
},
templates: [
{
name: "MKStack",
@@ -133,10 +126,10 @@ const defaultConfig: AppConfig = {
esmUrl: "https://esm.sh",
corsProxy: "https://proxy.shakespeare.diy/?url={href}",
faviconUrl: "https://favicon.shakespeare.diy/?url={href}",
ngitWebUrl: "https://nostrhub.io/{naddr}",
previewDomain: "local-shakespeare.dev",
showcaseEnabled: true,
showcaseModerator: "npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc",
ngitServers: ["git.shakespeare.diy", "relay.ngit.dev"],
fsPathProjects: electronPaths.fsPathProjects,
fsPathConfig: electronPaths.fsPathConfig,
fsPathTmp: electronPaths.fsPathTmp,
+9 -1
View File
@@ -80,6 +80,14 @@ export const AIMessageItem = memo(({
// User messages: right-aligned bubble without avatar/name
// Extract text and image parts from message content
const contentArray = Array.isArray(message.content) ? message.content : null;
const textParts = contentArray
? contentArray.filter(part => part.type === 'text') as OpenAI.Chat.Completions.ChatCompletionContentPartText[]
: [];
const userContent = typeof message.content === 'string'
? message.content
: textParts.length > 0
? textParts.map(part => part.text).join('\n')
: '';
// Extract image URLs from content array
const imageUrls = contentArray
@@ -94,7 +102,7 @@ export const AIMessageItem = memo(({
<div className="max-w-[80%] bg-secondary rounded-2xl rounded-br-md px-4 py-3">
<div className="text-sm break-words space-y-2">
{/* Render text content and attachments first */}
<UserMessage content={message.content} />
{userContent && <UserMessage content={userContent} />}
{/* Render images after text and attachments */}
{imageUrls.length > 0 && (
<div className="space-y-2">
-2
View File
@@ -151,7 +151,6 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
};
const isConfigured = settings.providers.length > 0;
const isLoading = !isInitialized;
const contextValue: AISettingsContextType = {
settings,
@@ -163,7 +162,6 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
setMCPServer,
removeMCPServer,
isConfigured,
isLoading,
};
return (
+157
View File
@@ -0,0 +1,157 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
GitBranch,
MoreHorizontal,
MessageSquarePlus,
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;
projectName: string;
onNewChat: () => void;
onProjectDetails?: () => void;
isLoading?: boolean;
isBuildLoading?: boolean;
disabled?: boolean;
onFirstInteraction?: () => void;
}
export function ActionsMenu({
projectId,
projectName,
onNewChat,
onProjectDetails,
isLoading = false,
isBuildLoading = false,
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;
return (
<>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0"
disabled={disabled}
>
<MoreHorizontal className="h-4 w-4" />
<span className="sr-only">Open menu</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuItem
onClick={onNewChat}
disabled={isLoading}
className="gap-2"
>
<MessageSquarePlus className="h-4 w-4" />
New Chat
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setGitHistoryOpen(true)}
disabled={isAnyLoading}
className="gap-2"
>
<History className="h-4 w-4" />
Rollback
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setGitDialogOpen(true)}
disabled={isAnyLoading}
className="gap-2"
>
<GitBranch className="h-4 w-4" />
Repository
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setDeployDialogOpen(true)}
disabled={isAnyLoading}
className="gap-2"
>
<Rocket className="h-4 w-4" />
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}
className="gap-2"
>
<Folder className="h-4 w-4" />
Project Details
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
{/* Dialogs */}
<GitDialog
projectId={projectId}
open={gitDialogOpen}
onOpenChange={setGitDialogOpen}
/>
<GitHistoryDialog
projectId={projectId}
open={gitHistoryOpen}
onOpenChange={setGitHistoryOpen}
/>
<DeployDialog
projectId={projectId}
projectName={projectName}
open={deployDialogOpen}
onOpenChange={setDeployDialogOpen}
/>
<DuplicateProjectDialog
projectId={projectId}
projectName={projectName}
open={duplicateDialogOpen}
onOpenChange={setDuplicateDialogOpen}
/>
</>
);
}
+10 -18
View File
@@ -1,8 +1,9 @@
import { ReactNode, useEffect } from 'react';
import { z } from 'zod';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { AppContext, type AppConfig, type AppContextType, type Theme, type RelayMetadata, type GraspMetadata } from '@/contexts/AppContext';
import { AppContext, type AppConfig, type AppContextType, type Theme, type RelayMetadata } from '@/contexts/AppContext';
import i18n from '@/lib/i18n';
import { expandTildePath, normalizeToForwardSlashes } from '@/lib/pathUtils';
interface AppProviderProps {
children: ReactNode;
@@ -22,14 +23,6 @@ const RelayMetadataSchema = z.object({
updatedAt: z.number(),
}) satisfies z.ZodType<RelayMetadata>;
// Zod schema for GraspMetadata
const GraspMetadataSchema = z.object({
relays: z.array(z.object({
url: z.string().url(),
})),
updatedAt: z.number(),
}) satisfies z.ZodType<GraspMetadata>;
// Zod schema for ProjectTemplate
const ProjectTemplateSchema = z.object({
name: z.string().min(1),
@@ -41,16 +34,15 @@ const ProjectTemplateSchema = z.object({
const AppConfigSchema = z.object({
theme: z.enum(['dark', 'light', 'system']),
relayMetadata: RelayMetadataSchema,
graspMetadata: GraspMetadataSchema,
templates: z.array(ProjectTemplateSchema),
esmUrl: z.string().url(),
corsProxy: z.string().url(),
faviconUrl: z.string().url(),
ngitWebUrl: z.string().url(),
previewDomain: z.string().min(1),
language: z.string(),
showcaseEnabled: z.boolean(),
showcaseModerator: z.string(),
ngitServers: z.array(z.string()),
fsPathProjects: z.string().min(1),
fsPathConfig: z.string().min(1),
fsPathTmp: z.string().min(1),
@@ -165,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);
}
+25 -51
View File
@@ -35,51 +35,25 @@ export function AppShowcase() {
}, [config.showcaseModerator]);
const isModerator = user?.pubkey === MODERATOR_HEX;
// Categorize and organize submissions - single pass for efficiency
const {
displayedFeaturedApps,
displayedTemplateApps,
moreApps
} = useMemo(() => {
const DISPLAY_LIMIT = 6;
// Single pass categorization
const templates: typeof submissions = [];
const featured: typeof submissions = [];
const approved: typeof submissions = [];
for (const app of submissions) {
if (app.isHidden) continue;
const isTemplate = app.appTags.includes('Template');
const isFeatured = app.isFeatured;
const isApproved = app.isApproved;
if (isTemplate) {
templates.push(app);
} else if (isFeatured) {
featured.push(app);
} else if (isApproved) {
approved.push(app);
}
}
// Shuffle each category once
const shuffledTemplates = shuffleArray(templates);
const shuffledFeatured = shuffleArray(featured);
const shuffledApproved = shuffleArray(approved);
// Split into display and more sections
// Filter and shuffle submissions - memoized with stable dependency
const { templateApps, featuredApps, approvedApps } = useMemo(() => {
// Filter visible submissions
const visibleSubmissions = submissions.filter(app => !app.isHidden);
// Separate template apps from other apps
const templates = shuffleArray(visibleSubmissions.filter(app => app.appTags.includes('Template')));
const nonTemplateSubmissions = visibleSubmissions.filter(app => !app.appTags.includes('Template'));
// Shuffle featured and approved apps for random display order
const featured = shuffleArray(nonTemplateSubmissions.filter(app => app.isFeatured));
const approved = shuffleArray(nonTemplateSubmissions.filter(app => app.isApproved && !app.isFeatured));
return {
displayedFeaturedApps: shuffledFeatured.slice(0, DISPLAY_LIMIT),
displayedTemplateApps: shuffledTemplates.slice(0, DISPLAY_LIMIT),
moreApps: [
...shuffledFeatured.slice(DISPLAY_LIMIT),
...shuffledTemplates.slice(DISPLAY_LIMIT),
...shuffledApproved,
],
templateApps: templates,
featuredApps: featured,
approvedApps: approved,
};
}, [submissions]);
}, [submissions]); // Only depend on submissions, not intermediate filtered arrays
// Don't show showcase if disabled in settings
if (!config.showcaseEnabled) {
@@ -150,7 +124,7 @@ export function AppShowcase() {
{/* Apps Grid */}
<div className="space-y-12">
{/* Featured Apps */}
{displayedFeaturedApps.length > 0 && (
{featuredApps.length > 0 && (
<div>
<div className="flex items-start gap-3 mb-6">
<div className="flex-none w-8 h-8 bg-yellow-100 dark:bg-yellow-900/30 rounded-lg flex items-center justify-center">
@@ -162,7 +136,7 @@ export function AppShowcase() {
</div>
</div>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{displayedFeaturedApps.map((app) => (
{featuredApps.slice(0, 6).map((app) => (
<AppShowcaseCard
key={app.id}
app={app}
@@ -175,7 +149,7 @@ export function AppShowcase() {
)}
{/* Templates Section */}
{displayedTemplateApps.length > 0 && (
{templateApps.length > 0 && (
<div>
<div className="flex items-start gap-3 mb-6">
<div className="flex-none w-8 h-8 bg-purple-100 dark:bg-purple-900/30 rounded-lg flex items-center justify-center">
@@ -187,7 +161,7 @@ export function AppShowcase() {
</div>
</div>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{displayedTemplateApps.map((app) => (
{templateApps.slice(0, 6).map((app) => (
<AppShowcaseCard
key={app.id}
app={app}
@@ -199,8 +173,8 @@ export function AppShowcase() {
</div>
)}
{/* More Apps (Remaining Featured, Templates, and Approved) - Collapsible */}
{moreApps.length > 0 && (
{/* More Apps (Approved) - Collapsible */}
{approvedApps.length > 0 && (
<div>
<Collapsible open={showAllApps} onOpenChange={setShowAllApps}>
<CollapsibleTrigger asChild>
@@ -211,7 +185,7 @@ export function AppShowcase() {
</div>
<div className="text-left">
<h3 className="text-xl font-bold text-foreground">
{t('moreAppsCount', { count: moreApps.length })}
{t('moreAppsCount', { count: approvedApps.length })}
</h3>
<p className="text-sm text-muted-foreground">
{showAllApps ? t('clickToCollapse') : t('clickToViewMore')}
@@ -222,7 +196,7 @@ export function AppShowcase() {
</CollapsibleTrigger>
<CollapsibleContent>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{moreApps.map((app) => (
{approvedApps.map((app) => (
<AppShowcaseCard
key={app.id}
app={app}
@@ -1,11 +1,25 @@
import { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { Rocket, ExternalLink, AlertCircle, Settings, Cloud } from 'lucide-react';
import { Rocket, ExternalLink, AlertCircle } from 'lucide-react';
import { ExternalFavicon } from '@/components/ExternalFavicon';
import {
Dialog,
DialogContent,
DialogDescription,
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 { Alert, AlertDescription } from '@/components/ui/alert';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { useDeploySettings } from '@/hooks/useDeploySettings';
import { useProjectDeploySettings } from '@/hooks/useProjectDeploySettings';
import { useCurrentUser } from '@/hooks/useCurrentUser';
@@ -22,7 +36,6 @@ import { VercelDeployForm } from '@/components/deploy/VercelDeployForm';
import { NsiteDeployForm } from '@/components/deploy/NsiteDeployForm';
import { CloudflareDeployForm } from '@/components/deploy/CloudflareDeployForm';
import { DenoDeployForm } from '@/components/deploy/DenoDeployForm';
import { cn } from '@/lib/utils';
/**
* Helper function to get provider URL for favicon
@@ -86,10 +99,11 @@ function renderProviderIcon(provider: DeployProvider, size = 14) {
return <Rocket size={size} />;
}
interface DeployStepsProps {
interface DeployDialogProps {
projectId: string;
projectName: string;
onClose: () => void;
open: boolean;
onOpenChange: (open: boolean) => void;
}
interface ShakespeareFormData {
@@ -118,7 +132,7 @@ interface DenoDeployFormData {
projectName: string;
}
export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProps) {
export function DeployDialog({ projectId, projectName, open, onOpenChange }: DeployDialogProps) {
const { t } = useTranslation();
const { settings } = useDeploySettings();
const { settings: projectSettings, updateSettings: updateProjectSettings } = useProjectDeploySettings(projectId);
@@ -156,19 +170,21 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
projectName: projectName || projectId,
});
// Load project settings when component mounts
// Load project settings when dialog opens
useEffect(() => {
// First, try to use the currentProvider from project settings
if (projectSettings.currentProvider && settings.providers.some(p => p.id === projectSettings.currentProvider)) {
setSelectedProviderId(projectSettings.currentProvider);
} else {
// Otherwise, find the first configured provider in project settings
const providerIds = Object.keys(projectSettings.providers);
if (providerIds.length > 0) {
setSelectedProviderId(providerIds[0]);
if (open) {
// First, try to use the currentProvider from project settings
if (projectSettings.currentProvider && settings.providers.some(p => p.id === projectSettings.currentProvider)) {
setSelectedProviderId(projectSettings.currentProvider);
} else {
// Otherwise, find the first configured provider in project settings
const providerIds = Object.keys(projectSettings.providers);
if (providerIds.length > 0) {
setSelectedProviderId(providerIds[0]);
}
}
}
}, [projectSettings, settings.providers]);
}, [open, projectSettings, settings.providers]);
const selectedProvider = settings.providers.find(p => p.id === selectedProviderId);
@@ -358,7 +374,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
setVercelForm({ projectName: projectName || projectId, teamId: '' });
setCloudflareForm({ projectName: projectName || projectId });
setDenoDeployForm({ projectName: projectName || projectId });
onClose();
onOpenChange(false);
};
const handleShakespeareSubdomainChange = useCallback((subdomain: string) => {
@@ -498,196 +514,184 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
};
return (
<div className="space-y-4">
<div>
<h3 className="font-semibold mb-1">Deploy your project</h3>
<p className="text-sm text-muted-foreground">
Choose a provider to deploy your project
</p>
</div>
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent className="sm:max-w-[500px]">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Rocket className="h-5 w-5" />
Deploy Project
</DialogTitle>
<DialogDescription>
Deploy your project to a hosting platform
</DialogDescription>
</DialogHeader>
{deployResult ? (
<div className="space-y-4">
<Alert>
<Rocket className="h-4 w-4" />
<AlertDescription>
Your project has been successfully deployed!
</AlertDescription>
</Alert>
{deployResult ? (
<div className="space-y-4">
<Alert>
<Rocket className="h-4 w-4" />
<AlertDescription>
Your project has been successfully deployed!
</AlertDescription>
</Alert>
<div className="space-y-2">
<Label>Deployed URL</Label>
<div className="flex gap-2">
<Input
value={deployResult.url}
readOnly
className="flex-1"
/>
<Button
size="sm"
variant="outline"
onClick={() => window.open(deployResult.url, '_blank')}
>
<ExternalLink className="h-4 w-4" />
<div className="space-y-2">
<Label>Deployed URL</Label>
<div className="flex gap-2">
<Input
value={deployResult.url}
readOnly
className="flex-1"
/>
<Button
size="sm"
variant="outline"
onClick={() => window.open(deployResult.url, '_blank')}
>
<ExternalLink className="h-4 w-4" />
</Button>
</div>
</div>
<div className="flex justify-end gap-2">
<Button onClick={handleClose}>
{t('close')}
</Button>
</div>
</div>
<div className="flex justify-end gap-2">
<Button onClick={handleClose}>
{t('close')}
</Button>
</div>
</div>
) : (
<div className="space-y-4">
{settings.providers.length === 0 ? (
<div className="py-8 px-4">
<div className="max-w-md mx-auto space-y-6 text-center">
{/* Icon */}
<div className="flex justify-center">
<div className="relative">
<div className="absolute inset-0 bg-primary/10 rounded-full blur-xl"></div>
<div className="relative bg-gradient-to-br from-primary/20 to-primary/5 p-6 rounded-2xl border border-primary/20">
<Cloud className="h-12 w-12 text-primary" />
</div>
</div>
</div>
{/* Heading */}
<div className="space-y-2">
<h3 className="text-xl font-semibold">Choose Your Deployment Platform</h3>
<p className="text-sm text-muted-foreground leading-relaxed">
Deploy your Shakespeare projects to any hosting provider. Configure your preferred platform to get started.
</p>
</div>
{/* CTA */}
<div className="pt-2">
<Button
asChild
size="lg"
className="w-full"
) : (
<div className="space-y-4">
{settings.providers.length === 0 ? (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
No deployment providers configured.{' '}
<Link
to="/settings/deploy"
className="underline hover:no-underline"
onClick={handleClose}
>
<Link to="/settings/deploy">
<Settings className="h-4 w-4 mr-2" />
Configure Deployment Provider
</Link>
Configure deployment settings
</Link>
</AlertDescription>
</Alert>
) : (
<>
<div className="space-y-2">
<Label htmlFor="provider">Select Provider</Label>
<Select value={selectedProviderId} onValueChange={setSelectedProviderId}>
<SelectTrigger id="provider">
{selectedProvider ? (
<div className="flex items-center gap-2">
{renderProviderIcon(selectedProvider, 14)}
<span>{selectedProvider.name}</span>
</div>
) : (
<SelectValue placeholder="Choose a deployment provider..." />
)}
</SelectTrigger>
<SelectContent>
{settings.providers.map((provider) => (
<SelectItem key={provider.id} value={provider.id}>
<div className="flex items-center gap-2">
{renderProviderIcon(provider, 14)}
<span>{provider.name}</span>
</div>
</SelectItem>
))}
</SelectContent>
</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 && (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
You must be logged in with Nostr to use Shakespeare Deploy.{' '}
<Link
to="/settings/nostr"
className="underline hover:no-underline"
onClick={handleClose}
>
Go to Nostr Settings
</Link>
</AlertDescription>
</Alert>
)}
{error && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={handleClose}>
{t('cancel')}
</Button>
<Button
onClick={handleDeploy}
disabled={
!selectedProvider ||
isDeploying ||
(selectedProvider.type === 'shakespeare' && !user) ||
(selectedProvider.type === 'shakespeare' && !isShakespeareFormValid) ||
(selectedProvider.type === 'nsite' && !nsiteForm.nsec) ||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName) ||
(selectedProvider.type === 'cloudflare' && !cloudflareForm.projectName) ||
(selectedProvider.type === 'deno' && !denoDeployForm.projectName)
}
>
{isDeploying ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
Deploying...
</>
) : (
<>
<Rocket className="h-4 w-4 mr-2" />
Deploy
</>
)}
</Button>
</div>
</div>
</div>
) : (
<>
<div className="space-y-2">
<Label>Select Provider</Label>
<div className="flex flex-wrap gap-2">
{settings.providers.map((provider) => (
<button
key={provider.id}
type="button"
onClick={() => setSelectedProviderId(provider.id)}
className={cn(
"inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-sm font-medium transition-all",
"border-2 hover:scale-105 active:scale-95",
selectedProviderId === provider.id
? "bg-primary text-primary-foreground border-primary shadow-sm"
: "bg-background text-foreground border-border hover:border-primary/50"
)}
>
{renderProviderIcon(provider, 14)}
<span>{provider.name}</span>
</button>
))}
</div>
</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 && (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
You must be logged in with Nostr to use Shakespeare Deploy.{' '}
<Link
to="/settings/nostr"
className="underline hover:no-underline"
onClick={handleClose}
>
Go to Nostr Settings
</Link>
</AlertDescription>
</Alert>
)}
{error && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{selectedProvider && (
<Button
onClick={handleDeploy}
disabled={
isDeploying ||
(selectedProvider.type === 'shakespeare' && !user) ||
(selectedProvider.type === 'shakespeare' && !isShakespeareFormValid) ||
(selectedProvider.type === 'nsite' && !nsiteForm.nsec) ||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName) ||
(selectedProvider.type === 'cloudflare' && !cloudflareForm.projectName) ||
(selectedProvider.type === 'deno' && !denoDeployForm.projectName)
}
className="w-full"
>
{isDeploying ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
Deploying...
</>
) : (
<>
<Rocket className="h-4 w-4 mr-2" />
Deploy
</>
)}
</Button>
)}
</>
)}
</div>
)}
</div>
</>
)}
</div>
)}
</DialogContent>
</Dialog>
);
}
+1 -2
View File
@@ -1,6 +1,5 @@
import { useAppContext } from '@/hooks/useAppContext';
import { faviconUrl } from '@/lib/faviconUrl';
import { normalizeUrl } from '@/lib/url';
import { faviconUrl, normalizeUrl } from '@/lib/faviconUrl';
import { cn } from '@/lib/utils';
import { ReactNode, useMemo } from 'react';
+245
View File
@@ -0,0 +1,245 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { GitDialog } from './GitDialog';
// Mock the hooks
const mockRefetch = vi.fn();
const mockUseGitStatus = vi.fn();
const baseGitStatus = {
isGitRepo: true,
currentBranch: 'main',
hasUncommittedChanges: false,
changedFiles: [],
totalCommits: 5,
remotes: [{ name: 'origin', url: 'https://github.com/example/repo.git' }],
latestCommit: {
oid: 'abc123def456',
message: 'Initial commit',
author: {
name: 'Test User',
email: '[email protected]',
timestamp: Date.now() / 1000,
},
},
ahead: 0,
behind: 0,
remoteBranchExists: false,
};
vi.mock('@/hooks/useGitStatus', () => ({
useGitStatus: () => mockUseGitStatus(),
}));
vi.mock('@/hooks/useFS', () => ({
useFS: vi.fn(() => ({
fs: {},
})),
}));
vi.mock('@/hooks/useToast', () => ({
useToast: vi.fn(() => ({
toast: vi.fn(),
})),
}));
const mockUseGitSettings = vi.fn();
vi.mock('@/hooks/useGitSettings', () => ({
useGitSettings: () => mockUseGitSettings(),
}));
describe('GitDialog', () => {
beforeEach(() => {
mockUseGitStatus.mockReturnValue({
data: baseGitStatus,
refetch: mockRefetch,
});
mockUseGitSettings.mockReturnValue({
settings: {
credentials: {
'https://github.com': {
username: 'git',
password: 'github-token',
},
},
},
});
});
it('renders git dialog without repository information section', () => {
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
<button>Open Git Dialog</button>
</GitDialog>
</TestApp>
);
expect(screen.getByText('Repository')).toBeInTheDocument();
expect(screen.queryByText('Repository Information')).not.toBeInTheDocument();
expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed
});
it('shows sync status when branch is published', () => {
// Mock git status with published branch
mockUseGitStatus.mockReturnValue({
data: {
...baseGitStatus,
remoteBranchExists: true,
},
refetch: mockRefetch,
});
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
<button>Open Git Dialog</button>
</GitDialog>
</TestApp>
);
expect(screen.getByText('Sync Status')).toBeInTheDocument();
expect(screen.getByText('Up to date')).toBeInTheDocument();
expect(screen.getByText('Pull')).toBeInTheDocument();
expect(screen.getByText('Push')).toBeInTheDocument();
});
it('shows clean working directory when no changes', () => {
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
<button>Open Git Dialog</button>
</GitDialog>
</TestApp>
);
expect(screen.getByText('Working directory is clean')).toBeInTheDocument();
expect(screen.getByText('No uncommitted changes')).toBeInTheDocument();
});
it('enables push button when there are commits ahead', () => {
// Mock git status with commits ahead
mockUseGitStatus.mockReturnValue({
data: {
...baseGitStatus,
ahead: 2,
},
refetch: mockRefetch,
});
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
<button>Open Git Dialog</button>
</GitDialog>
</TestApp>
);
const pushButton = screen.getByText('Push');
expect(pushButton).toBeInTheDocument();
expect(pushButton.closest('button')).not.toBeDisabled();
});
it('disables push button when no commits ahead and branch is published', () => {
// Mock git status with published branch and no commits ahead
mockUseGitStatus.mockReturnValue({
data: {
...baseGitStatus,
ahead: 0,
remoteBranchExists: true,
},
refetch: mockRefetch,
});
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
<button>Open Git Dialog</button>
</GitDialog>
</TestApp>
);
const pushButton = screen.getByText('Push');
expect(pushButton).toBeInTheDocument();
expect(pushButton.closest('button')).toBeDisabled();
});
it('enables push and disables pull when branch is not published', () => {
// Mock git status with unpublished branch (has commits but no remote branch)
mockUseGitStatus.mockReturnValue({
data: {
...baseGitStatus,
ahead: 0,
remoteBranchExists: false,
totalCommits: 5,
},
refetch: mockRefetch,
});
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
<button>Open Git Dialog</button>
</GitDialog>
</TestApp>
);
expect(screen.getByText('Sync Status')).toBeInTheDocument();
expect(screen.getByText('Branch not published')).toBeInTheDocument();
const pushButton = screen.getByText('Push');
expect(pushButton).toBeInTheDocument();
expect(pushButton.closest('button')).not.toBeDisabled();
const pullButton = screen.getByText('Pull');
expect(pullButton).toBeInTheDocument();
expect(pullButton.closest('button')).toBeDisabled();
});
it('does not show credentials warning when credentials are configured', () => {
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
<button>Open Git Dialog</button>
</GitDialog>
</TestApp>
);
// Should not show warning when credentials are configured
expect(screen.queryByText(/No credentials configured/)).not.toBeInTheDocument();
expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed
});
it('shows credentials warning when no credentials are configured', () => {
// Mock git settings with no credentials and mock git status with an https remote
mockUseGitSettings.mockReturnValue({
settings: {
credentials: {},
},
});
mockUseGitStatus.mockReturnValue({
data: {
...baseGitStatus,
remotes: [{ name: 'origin', url: 'https://github.com/example/repo.git' }],
},
refetch: mockRefetch,
});
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
<button>Open Git Dialog</button>
</GitDialog>
</TestApp>
);
// Should show warning when credentials are missing
expect(screen.getByText(/You are not logged into github.com/)).toBeInTheDocument();
expect(screen.getByText('log in')).toBeInTheDocument();
expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed
});
});
File diff suppressed because it is too large. Load diff
+18 -34
View File
@@ -14,49 +14,35 @@ vi.mock('@/lib/configUtils', () => ({
// Test component that uses the hook
function TestComponent() {
const { settings, addCredential, removeCredential, setCredentials, isConfigured } = useGitSettings();
const { settings, addCredential, removeCredential, updateCredential, isConfigured } = useGitSettings();
const handleAdd = () => {
const credential: GitCredential = {
id: crypto.randomUUID(),
name: 'GitHub',
origin: 'https://github.com',
username: 'git',
password: 'test-token',
};
addCredential(credential);
addCredential('https://github.com', credential);
};
const handleUpdate = () => {
const githubCred = settings.credentials.find(c => c.origin === 'https://github.com');
if (githubCred) {
const updatedCredentials = settings.credentials.map((cred) =>
cred.id === githubCred.id ? { ...cred, password: 'updated-token' } : cred
);
setCredentials(updatedCredentials);
}
updateCredential('https://github.com', { password: 'updated-token' });
};
const handleRemove = () => {
const githubCred = settings.credentials.find(c => c.origin === 'https://github.com');
if (githubCred) {
removeCredential(githubCred.id);
}
removeCredential('https://github.com');
};
const githubCred = settings.credentials.find(c => c.origin === 'https://github.com');
return (
<div>
<div data-testid="configured">{isConfigured ? 'configured' : 'not-configured'}</div>
<div data-testid="count">{settings.credentials.length}</div>
<div data-testid="count">{Object.keys(settings.credentials).length}</div>
<button onClick={handleAdd}>Add GitHub</button>
<button onClick={handleUpdate}>Update GitHub</button>
<button onClick={handleRemove}>Remove GitHub</button>
{githubCred && (
{settings.credentials['https://github.com'] && (
<div data-testid="github-creds">
{githubCred.username}:
{githubCred.password}
{settings.credentials['https://github.com'].username}:
{settings.credentials['https://github.com'].password}
</div>
)}
</div>
@@ -81,7 +67,8 @@ describe('GitSettingsProvider', () => {
// Mock the read function to return default settings
const { readGitSettings } = await import('@/lib/configUtils');
vi.mocked(readGitSettings).mockResolvedValue({
credentials: [],
credentials: {},
hostTokens: {},
});
});
@@ -178,13 +165,12 @@ describe('GitSettingsProvider', () => {
expect(writeGitSettings).toHaveBeenCalledWith(
expect.anything(), // fs instance
expect.objectContaining({
credentials: expect.arrayContaining([
expect.objectContaining({
origin: 'https://github.com',
credentials: {
'https://github.com': {
username: 'git',
password: 'test-token',
})
])
}
}
}),
'/config' // configPath
);
@@ -193,15 +179,13 @@ describe('GitSettingsProvider', () => {
it('loads settings from VFS', async () => {
const settings = {
credentials: [
{
id: crypto.randomUUID(),
name: 'GitLab',
origin: 'https://gitlab.com',
credentials: {
'https://gitlab.com': {
username: 'git',
password: 'gitlab-token',
},
],
},
hostTokens: {},
};
const { readGitSettings } = await import('@/lib/configUtils');
+59 -10
View File
@@ -1,5 +1,5 @@
import { ReactNode, useState, useEffect } from 'react';
import { GitSettingsContext, type GitSettings, type GitCredential, type GitSettingsContextType } from '@/contexts/GitSettingsContext';
import { GitSettingsContext, type GitSettings, type GitCredential, type GitHostToken, type GitSettingsContextType } from '@/contexts/GitSettingsContext';
import { useFS } from '@/hooks/useFS';
import { useFSPaths } from '@/hooks/useFSPaths';
import { readGitSettings, writeGitSettings } from '@/lib/configUtils';
@@ -9,7 +9,8 @@ interface GitSettingsProviderProps {
}
const DEFAULT_SETTINGS: GitSettings = {
credentials: [],
credentials: {},
hostTokens: {},
};
export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
@@ -54,35 +55,83 @@ export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
setSettings(prev => ({ ...prev, ...newSettings }));
};
const addCredential = (credential: GitCredential) => {
const addCredential = (origin: string, credential: GitCredential) => {
setSettings(prev => ({
...prev,
credentials: [...prev.credentials, credential],
credentials: {
...prev.credentials,
[origin]: credential,
},
}));
};
const removeCredential = (id: string) => {
const removeCredential = (origin: string) => {
setSettings(prev => {
const { [origin]: removed, ...rest } = prev.credentials;
return {
...prev,
credentials: rest,
};
});
};
const updateCredential = (origin: string, credential: Partial<GitCredential>) => {
setSettings(prev => ({
...prev,
credentials: prev.credentials.filter((cred) => cred.id !== id),
credentials: {
...prev.credentials,
[origin]: {
...prev.credentials[origin],
...credential,
},
},
}));
};
const setCredentials = (credentials: GitCredential[]) => {
const addHostToken = (host: string, token: GitHostToken) => {
setSettings(prev => ({
...prev,
credentials,
hostTokens: {
...prev.hostTokens,
[host]: token,
},
}));
};
const isConfigured = settings.credentials.length > 0;
const removeHostToken = (host: string) => {
setSettings(prev => {
const { [host]: removed, ...rest } = prev.hostTokens;
return {
...prev,
hostTokens: rest,
};
});
};
const updateHostToken = (host: string, token: Partial<GitHostToken>) => {
setSettings(prev => ({
...prev,
hostTokens: {
...prev.hostTokens,
[host]: {
...prev.hostTokens[host],
...token,
},
},
}));
};
const isConfigured = Object.entries(settings.credentials).length > 0;
const contextValue: GitSettingsContextType = {
settings,
updateSettings,
addCredential,
removeCredential,
setCredentials,
updateCredential,
addHostToken,
removeHostToken,
updateHostToken,
isConfigured,
isInitialized,
};
-223
View File
@@ -1,223 +0,0 @@
import { useState, useEffect } from 'react';
import { Plus, X, Server } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { useAppContext } from '@/hooks/useAppContext';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { toast } from '@/hooks/useToast';
export function GraspListManager() {
const { config, updateConfig } = useAppContext();
const { user } = useCurrentUser();
const { mutate: publishEvent } = useNostrPublish();
const [graspRelays, setGraspRelays] = useState<{ url: string }[]>(config.graspMetadata.relays);
const [newRelayUrl, setNewRelayUrl] = useState('');
// Sync local state with config when it changes (e.g., from NostrProvider sync)
useEffect(() => {
setGraspRelays(config.graspMetadata.relays);
}, [config.graspMetadata.relays]);
const normalizeRelayUrl = (url: string): string => {
url = url.trim();
try {
const parsed = new URL(url);
// Ensure it's a websocket URL
if (parsed.protocol !== 'ws:' && parsed.protocol !== 'wss:') {
parsed.protocol = 'wss:';
}
// Ensure trailing slash
if (!parsed.pathname.endsWith('/')) {
parsed.pathname += '/';
}
return parsed.toString();
} catch {
// If parsing fails, try to construct a valid URL
try {
const withProtocol = url.startsWith('ws://') || url.startsWith('wss://')
? url
: `wss://${url}`;
const parsed = new URL(withProtocol);
if (!parsed.pathname.endsWith('/')) {
parsed.pathname += '/';
}
return parsed.toString();
} catch {
return url;
}
}
};
const isValidRelayUrl = (url: string): boolean => {
const trimmed = url.trim();
if (!trimmed) return false;
const normalized = normalizeRelayUrl(trimmed);
try {
const parsed = new URL(normalized);
return parsed.protocol === 'ws:' || parsed.protocol === 'wss:';
} catch {
return false;
}
};
const handleAddRelay = () => {
if (!isValidRelayUrl(newRelayUrl)) {
toast({
title: 'Invalid relay URL',
description: 'Please enter a valid websocket URL (e.g., wss://git.shakespeare.diy/)',
variant: 'destructive',
});
return;
}
const normalized = normalizeRelayUrl(newRelayUrl);
if (graspRelays.some(r => r.url === normalized)) {
toast({
title: 'Relay already exists',
description: 'This relay is already in your list',
variant: 'destructive',
});
return;
}
const newRelays = [...graspRelays, { url: normalized }];
setGraspRelays(newRelays);
setNewRelayUrl('');
saveRelays(newRelays);
};
const handleRemoveRelay = (url: string) => {
const newRelays = graspRelays.filter(r => r.url !== url);
setGraspRelays(newRelays);
saveRelays(newRelays);
};
const saveRelays = (newRelays: { url: string }[]) => {
const now = Math.floor(Date.now() / 1000);
// Update local config
updateConfig((current) => ({
...current,
graspMetadata: {
relays: newRelays,
updatedAt: now,
},
}));
// Publish to Nostr if user is logged in
if (user) {
publishNIP34GraspList(newRelays);
}
};
const publishNIP34GraspList = (relays: { url: string }[]) => {
const tags = relays.map(relay => ['g', relay.url]);
publishEvent(
{
kind: 10317,
content: '',
tags,
},
{
onSuccess: () => {
toast({
title: 'Grasp list published',
description: 'Your Nostr git server list has been published to your relays',
});
},
onError: (error) => {
console.error('Failed to publish grasp list:', error);
toast({
title: 'Publish failed',
description: 'Failed to publish your grasp server list',
variant: 'destructive',
});
},
}
);
};
const renderRelayUrl = (url: string): string => {
try {
const parsed = new URL(url);
if (parsed.pathname === '/') {
return parsed.host;
} else {
return parsed.host + parsed.pathname;
}
} catch {
return url;
}
};
return (
<div className="space-y-4">
{/* Relay List */}
<div className="space-y-2">
{graspRelays.map((relay) => (
<div
key={relay.url}
className="flex items-center gap-2 p-2 rounded-md border bg-muted/20"
>
<Server className="h-4 w-4 text-muted-foreground shrink-0" />
<span className="font-mono text-sm flex-1 truncate" title={relay.url}>
{renderRelayUrl(relay.url)}
</span>
<Button
variant="ghost"
size="icon"
onClick={() => handleRemoveRelay(relay.url)}
className="size-5 text-muted-foreground hover:text-destructive hover:bg-transparent shrink-0"
disabled={graspRelays.length <= 1}
>
<X className="h-4 w-4" />
</Button>
</div>
))}
</div>
{/* Add Relay Form */}
<div className="flex gap-2">
<div className="flex-1">
<Label htmlFor="new-grasp-relay" className="sr-only">
Grasp Relay URL
</Label>
<Input
id="new-grasp-relay"
placeholder="wss://git.shakespeare.diy/"
value={newRelayUrl}
onChange={(e) => setNewRelayUrl(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleAddRelay();
}
}}
/>
</div>
<Button
onClick={handleAddRelay}
disabled={!newRelayUrl.trim()}
variant="outline"
size="sm"
className="h-10 shrink-0"
>
<Plus className="h-4 w-4 mr-2" />
Add
</Button>
</div>
{!user && (
<p className="text-xs text-muted-foreground">
Log in to sync your grasp server list with Nostr
</p>
)}
</div>
);
}
+2 -1
View File
@@ -3,6 +3,7 @@ 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;
@@ -46,7 +47,7 @@ export function ImageLightbox({ imageUrl, onClose }: ImageLightboxProps) {
className="relative z-[2] flex items-center justify-center w-full h-full pointer-events-none"
onClick={(e) => e.stopPropagation()}
>
{imageUrl.startsWith('/') ? (
{isAbsolutePath(imageUrl) ? (
<VFSImage
path={imageUrl}
alt="Expanded image"
-5
View File
@@ -45,7 +45,6 @@ describe('ModelSelector', () => {
settings: { providers: [], recentlyUsedModels: [], mcpServers: {} },
addRecentlyUsedModel: mockAddRecentlyUsedModel,
isConfigured: true,
isLoading: false,
updateSettings: vi.fn(),
removeProvider: vi.fn(),
setProvider: vi.fn(),
@@ -92,7 +91,6 @@ describe('ModelSelector', () => {
},
addRecentlyUsedModel: mockAddRecentlyUsedModel,
isConfigured: true,
isLoading: false,
updateSettings: vi.fn(),
removeProvider: vi.fn(),
setProvider: vi.fn(),
@@ -156,7 +154,6 @@ describe('ModelSelector', () => {
},
addRecentlyUsedModel: mockAddRecentlyUsedModel,
isConfigured: true,
isLoading: false,
updateSettings: vi.fn(),
removeProvider: vi.fn(),
setProvider: vi.fn(),
@@ -216,7 +213,6 @@ describe('ModelSelector', () => {
},
addRecentlyUsedModel: mockAddRecentlyUsedModel,
isConfigured: true,
isLoading: false,
updateSettings: vi.fn(),
removeProvider: vi.fn(),
setProvider: vi.fn(),
@@ -270,7 +266,6 @@ describe('ModelSelector', () => {
settings: { providers: [], recentlyUsedModels: [], mcpServers: {} }, // No recently used models
addRecentlyUsedModel: mockAddRecentlyUsedModel,
isConfigured: true,
isLoading: false,
updateSettings: vi.fn(),
removeProvider: vi.fn(),
setProvider: vi.fn(),
+4 -8
View File
@@ -44,7 +44,7 @@ export const ModelSelector = memo(function ModelSelector({
const [isCustomInput, setIsCustomInput] = useState(false);
const [customValue, setCustomValue] = useState('');
const { settings, addRecentlyUsedModel, isConfigured, isLoading: isLoadingSettings } = useAISettings();
const { settings, addRecentlyUsedModel, isConfigured } = useAISettings();
const { models: allModels, isLoading, error, refetch } = useProviderModels();
const navigate = useNavigate();
const isMobile = useIsMobile();
@@ -314,11 +314,9 @@ export const ModelSelector = memo(function ModelSelector({
className={cn(
"h-8 p-0 gap-1 text-xs border-0 bg-transparent hover:bg-transparent hover:text-foreground focus-visible:ring-0 focus-visible:ring-offset-0 text-muted-foreground text-right min-w-0 max-w-[280px]"
)}
disabled={disabled || isLoading || isLoadingSettings}
disabled={disabled}
>
{(isLoading || isLoadingSettings) ? (
<Skeleton className="h-4 w-32" />
) : selectedModelDisplay ? (
{selectedModelDisplay ? (
<>
{selectedModelDisplay.baseURL ? (
<ExternalFavicon
@@ -339,9 +337,7 @@ export const ModelSelector = memo(function ModelSelector({
{placeholder || defaultPlaceholder}
</span>
)}
{(!isLoading && !isLoadingSettings) && (
<ChevronDown className="size-3 shrink-0 opacity-50" />
)}
<ChevronDown className="size-3 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="p-0 w-80" align="end">
+1 -1
View File
@@ -19,7 +19,7 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
const { children } = props;
const { config } = useAppContext();
const gitRelays = config.graspMetadata.relays.map(r => r.url);
const gitRelays = config.ngitServers.map(server => `wss://${server}/`);
const queryClient = useQueryClient();
// Create NPool instance only once
-41
View File
@@ -10,7 +10,6 @@ import { useContacts } from '@/hooks/useContacts';
* This component runs globally to sync various Nostr data when the user logs in.
* Currently syncs:
* - NIP-65 relay list (kind 10002)
* - NIP-34 grasp server list (kind 10317)
*/
export function NostrSync() {
const { nostr } = useNostr();
@@ -63,45 +62,5 @@ export function NostrSync() {
syncRelaysFromNostr();
}, [user, config.relayMetadata.updatedAt, nostr, updateConfig]);
useEffect(() => {
if (!user) return;
const syncGraspServersFromNostr = async () => {
try {
const events = await nostr.query(
[{ kinds: [10317], authors: [user.pubkey], limit: 1 }],
{ signal: AbortSignal.timeout(5000) }
);
if (events.length > 0) {
const event = events[0];
// Only update if the event is newer than our stored data
if (event.created_at > config.graspMetadata.updatedAt) {
const fetchedRelays = event.tags
.filter(([name]) => name === 'g')
.map(([_, url]) => ({ url }))
.filter(relay => relay.url); // Filter out empty URLs
if (fetchedRelays.length > 0) {
console.log('Syncing grasp server list from Nostr:', fetchedRelays);
updateConfig((current) => ({
...current,
graspMetadata: {
relays: fetchedRelays,
updatedAt: event.created_at,
},
}));
}
}
}
} catch (error) {
console.error('Failed to sync grasp servers from Nostr:', error);
}
};
syncGraspServersFromNostr();
}, [user, config.graspMetadata.updatedAt, nostr, updateConfig]);
return null;
}
+195 -42
View File
@@ -7,6 +7,17 @@ import {
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
@@ -18,28 +29,32 @@ import { useNavigate } from 'react-router-dom';
import {
Calendar,
Folder,
Download,
Loader2,
Trash2,
Save,
DollarSign,
ExternalLink,
FileCode,
} from 'lucide-react';
import { Skeleton } from './ui/skeleton';
import JSZip from 'jszip';
import { Separator } from './ui/separator';
import { DotAI } from '@/lib/DotAI';
import { LabelSelector } from '@/components/labels/LabelSelector';
import { cn } from '@/lib/utils';
interface ProjectDetailsDialogProps {
project: Project;
open: boolean;
onOpenChange: (open: boolean) => void;
onProjectDeleted?: () => void;
}
export function ProjectDetailsDialog({ project, open, onOpenChange }: ProjectDetailsDialogProps) {
export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDeleted }: ProjectDetailsDialogProps) {
const [isExporting, setIsExporting] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
const [isRenaming, setIsRenaming] = useState(false);
const [newProjectName, setNewProjectName] = useState(project.id);
const [totalCost, setTotalCost] = useState<number | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [templateInfo, setTemplateInfo] = useState<{ name: string; description: string; url: string } | null>(null);
const { toast } = useToast();
const { fs } = useFS();
@@ -57,7 +72,6 @@ export function ProjectDetailsDialog({ project, open, onOpenChange }: ProjectDet
// Load total project cost and template info
useEffect(() => {
const loadProjectData = async () => {
setIsLoading(true);
try {
const dotAI = new DotAI(fs, `${projectsPath}/${project.id}`);
@@ -72,8 +86,6 @@ export function ProjectDetailsDialog({ project, open, onOpenChange }: ProjectDet
console.warn('Failed to load project data:', error);
setTotalCost(null);
setTemplateInfo(null);
} finally {
setIsLoading(false);
}
};
@@ -129,6 +141,105 @@ export function ProjectDetailsDialog({ project, open, onOpenChange }: ProjectDet
}
};
const handleDeleteProject = async () => {
setIsDeleting(true);
try {
await projectsManager.deleteProject(project.id);
// Invalidate the projects query to update the sidebar
await queryClient.invalidateQueries({ queryKey: ['projects'] });
toast({
title: "Project deleted",
description: `"${project.name}" has been permanently deleted.`,
});
// Close the dialog first
onOpenChange(false);
// Navigate back to home and notify parent
navigate('/');
if (onProjectDeleted) {
onProjectDeleted();
}
} catch (error) {
toast({
title: "Failed to delete project",
description: error instanceof Error ? error.message : "An unexpected error occurred",
variant: "destructive",
});
} finally {
setIsDeleting(false);
}
};
const handleExportProject = async () => {
setIsExporting(true);
try {
const zip = new JSZip();
const projectPath = `${projectsPath}/${project.id}`;
// Recursive function to add files and directories to zip from a specific project
const addFolderToZip = async (dirPath: string, zipFolder: JSZip) => {
try {
const entries = await fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = `${dirPath}/${entry.name}`;
if (entry.isDirectory()) {
// Create folder in zip and recursively add its contents
const folder = zipFolder.folder(entry.name);
if (folder) {
await addFolderToZip(fullPath, folder);
}
} else if (entry.isFile()) {
// Add file to zip
try {
const fileContent = await fs.readFile(fullPath);
zipFolder.file(entry.name, fileContent);
} catch (error) {
console.warn(`Failed to read file ${fullPath}:`, error);
}
}
}
} catch (error) {
console.warn(`Failed to read directory ${dirPath}:`, error);
}
};
// Start from the project directory
await addFolderToZip(projectPath, zip);
// Generate zip file
const content = await zip.generateAsync({ type: 'blob' });
// Create download link
const url = URL.createObjectURL(content);
const link = document.createElement('a');
link.href = url;
link.download = `${project.id}.zip`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
toast({
title: "Project exported successfully",
description: `"${project.name}" has been downloaded as a zip file.`,
});
} catch (error) {
console.error('Failed to export project:', error);
toast({
title: "Failed to export project",
description: error instanceof Error ? error.message : "An unexpected error occurred",
variant: "destructive",
});
} finally {
setIsExporting(false);
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md" onOpenAutoFocus={(e) => e.preventDefault()}>
@@ -148,44 +259,30 @@ export function ProjectDetailsDialog({ project, open, onOpenChange }: ProjectDet
</div>
{/* Total Cost */}
<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>
{typeof totalCost === 'number' ? (
{totalCost !== null && totalCost > 0 && (
<div className="flex items-center gap-2 text-sm">
<DollarSign className="h-4 w-4 text-muted-foreground" />
<span className="text-muted-foreground">Total Cost:</span>
<span className="font-mono">${totalCost.toFixed(2)}</span>
) : (
isLoading ? (
<Skeleton className="h-4 w-16" />
) : (
<span>N/A</span>
)
)}
</div>
</div>
)}
{/* Template Info */}
<div className="flex items-center gap-2 text-sm">
<FileCode className="h-4 w-4 text-muted-foreground" />
<span className="text-muted-foreground">Template:</span>
<a
href={templateInfo?.url}
target="_blank"
rel="noopener noreferrer"
className={cn("flex items-center gap-1", { "text-primary hover:underline": !!templateInfo })}
>
{templateInfo ? (
<>
<span>{templateInfo.name}</span>
<ExternalLink className="h-3 w-3" />
</>
) : (
isLoading ? (
<Skeleton className="h-4 w-24" />
) : (
<span>N/A</span>
)
)}
</a>
</div>
{templateInfo && (
<div className="flex items-center gap-2 text-sm">
<FileCode className="h-4 w-4 text-muted-foreground" />
<span className="text-muted-foreground">Template:</span>
<a
href={templateInfo.url}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-1 text-primary hover:underline"
>
{templateInfo.name}
<ExternalLink className="h-3 w-3" />
</a>
</div>
)}
{/* Project Name */}
<div className="space-y-2">
@@ -223,6 +320,62 @@ export function ProjectDetailsDialog({ project, open, onOpenChange }: ProjectDet
{/* Labels */}
<LabelSelector projectId={project.id} />
<Separator />
{/* Export Project Button */}
<Button
onClick={handleExportProject}
disabled={isExporting || isDeleting || isRenaming}
className="w-full gap-2"
variant="outline"
>
{isExporting ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Download className="h-4 w-4" />
)}
{isExporting ? 'Exporting...' : 'Export Project'}
</Button>
{/* Delete Project Button */}
<AlertDialog>
<AlertDialogTrigger asChild>
<Button
variant="destructive"
className="w-full gap-2"
disabled={isExporting || isDeleting || isRenaming}
>
<Trash2 className="h-4 w-4" />
Delete Project
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete Project</AlertDialogTitle>
<AlertDialogDescription>
Are you sure you want to delete "{project.name}"? This action cannot be undone and will permanently delete all project data including files.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={handleDeleteProject}
disabled={isDeleting}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{isDeleting ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Deleting...
</>
) : (
'Delete Project'
)}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</DialogContent>
</Dialog>
-160
View File
@@ -1,160 +0,0 @@
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
MessageSquarePlus,
History,
Folder,
Copy,
ChevronDown,
Download,
Trash2,
Star,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { useToast } from '@/hooks/useToast';
import { useQueryClient } from '@tanstack/react-query';
interface ProjectTitleMenuProps {
projectId: string;
projectName: string;
onNewChat: () => void;
onGitHistory: () => void;
onDuplicate: () => void;
onExport: () => void;
onDelete: () => void;
onProjectDetails: () => void;
isAILoading: boolean;
isAnyLoading: boolean;
className?: string;
}
export function ProjectTitleMenu({
projectId,
projectName,
onNewChat,
onGitHistory,
onDuplicate,
onExport,
onDelete,
onProjectDetails,
isAILoading,
isAnyLoading,
className = '',
}: ProjectTitleMenuProps) {
const { t } = useTranslation();
const [favorites, setFavorites] = useLocalStorage<string[]>('project-favorites', []);
const { toast } = useToast();
const queryClient = useQueryClient();
const isFavorite = favorites.includes(projectId);
const handleToggleFavorite = (e: React.MouseEvent) => {
e.preventDefault(); // Prevent menu from closing
e.stopPropagation();
const newFavorites = isFavorite
? favorites.filter(id => id !== projectId)
: [...favorites, projectId];
setFavorites(newFavorites);
// Invalidate the projects query to trigger a refetch with new sorting
queryClient.invalidateQueries({ queryKey: ['projects'] });
toast({
title: isFavorite ? "Project Unfavorited" : "Project Favorited",
description: `"${projectName}" has been ${isFavorite ? 'removed from' : 'added to'} your favorites.`,
});
};
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
className={cn("p-0 h-auto font-semibold truncate hover:bg-transparent hover:text-muted-foreground flex items-center gap-1", className)}
>
<span className="truncate">{projectName}</span>
<ChevronDown className="h-4 w-4 flex-shrink-0 text-muted-foreground" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-48">
<DropdownMenuItem
onClick={handleToggleFavorite}
disabled={isAnyLoading}
className="gap-2"
onSelect={(e) => e.preventDefault()} // Prevent menu from closing
>
<Star
className={cn(
"h-4 w-4",
{ "text-yellow-500 fill-current": isFavorite },
)}
/>
{isFavorite ? 'Unfavorite' : 'Favorite'}
</DropdownMenuItem>
<DropdownMenuItem
onClick={onProjectDetails}
disabled={isAnyLoading}
className="gap-2"
>
<Folder className="h-4 w-4" />
Project Details
</DropdownMenuItem>
<DropdownMenuItem
onClick={onGitHistory}
disabled={isAnyLoading}
className="gap-2"
>
<History className="h-4 w-4" />
Rollback
</DropdownMenuItem>
<DropdownMenuItem
onClick={onNewChat}
disabled={isAILoading}
className="gap-2"
>
<MessageSquarePlus className="h-4 w-4" />
New Chat
</DropdownMenuItem>
<DropdownMenuItem
onClick={onDuplicate}
disabled={isAnyLoading}
className="gap-2"
>
<Copy className="h-4 w-4" />
{t('duplicateProject')}
</DropdownMenuItem>
<DropdownMenuItem
onClick={onExport}
disabled={isAnyLoading}
className="gap-2"
>
<Download className="h-4 w-4" />
Export Project
</DropdownMenuItem>
<DropdownMenuItem
onClick={onDelete}
disabled={isAnyLoading}
className="gap-2 text-destructive focus:text-destructive"
>
<Trash2 className="h-4 w-4" />
Delete Project
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
}
+10 -80
View File
@@ -1,20 +1,14 @@
import React, { useState } from 'react';
import React from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { GitBranch, Loader2 } from 'lucide-react';
import { GitBranch } from 'lucide-react';
import type { Repository } from '@/hooks/useUserRepositories';
import { useAuthor } from '@/hooks/useAuthor';
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar';
import { genUserName } from '@/lib/genUserName';
import { useNavigate } from 'react-router-dom';
import { NostrURI } from '@/lib/NostrURI';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useToast } from '@/hooks/useToast';
import { useTranslation } from 'react-i18next';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useGitSettings } from '@/hooks/useGitSettings';
import { detectFork } from '@/lib/detectFork';
import { nip19 } from 'nostr-tools';
interface RepositoryCardProps {
repo: Repository;
@@ -22,75 +16,21 @@ interface RepositoryCardProps {
export function RepositoryCard({ repo }: RepositoryCardProps) {
const { data: authorData } = useAuthor(repo.pubkey);
const { user } = useCurrentUser();
const { settings: gitSettings } = useGitSettings();
const navigate = useNavigate();
const projectsManager = useProjectsManager();
const { toast } = useToast();
const { t } = useTranslation();
const [isCloning, setIsCloning] = useState(false);
const displayName = authorData?.metadata?.name || genUserName(repo.pubkey);
const profileImage = authorData?.metadata?.picture;
// Construct Nostr clone URL
const nostrURI = new NostrURI({ pubkey: repo.pubkey, identifier: repo.repoId });
const nostrCloneUrl = `nostr://${nip19.npubEncode(repo.pubkey)}/${repo.repoId}`;
const handleClone = async (e: React.MouseEvent) => {
// Prevent card click from triggering
e.stopPropagation();
setIsCloning(true);
try {
await projectsManager.init();
// Determine if this is a fork
const repoUrl = nostrURI.toString();
const fork = await detectFork(repoUrl, user?.pubkey, gitSettings.credentials);
// Clone the repository using the Nostr URI
const project = await projectsManager.cloneProject({
name: repo.name,
repoUrl,
fork,
});
toast({
title: t('nostrRepositoryImportedSuccessfully'),
description: t('repositoryClonedFromNostr', { repoName: repo.name }),
});
// Navigate to the new project with build parameter
navigate(`/project/${project.id}?build`);
} catch (error) {
console.error('Failed to clone repository:', error);
let errorMessage = t('failedToImportRepository');
if (error instanceof Error) {
if (error.message.includes('Repository not found on Nostr network')) {
errorMessage = t('repositoryNotFoundOnNostr');
} else if (error.message.includes('No clone URLs found')) {
errorMessage = t('noCloneUrlsFound');
} else if (error.message.includes('All clone attempts failed')) {
errorMessage = t('allCloneAttemptsFailed');
} else {
errorMessage = error.message;
}
}
toast({
title: t('failedToImportRepository'),
description: errorMessage,
variant: "destructive",
});
} finally {
setIsCloning(false);
}
const handleClone = () => {
// Navigate to clone page with Nostr URL parameter
navigate(`/clone?url=${encodeURIComponent(nostrCloneUrl)}`);
};
return (
<Card className="h-full flex flex-col hover:shadow-lg transition-shadow">
<Card className="h-full flex flex-col hover:shadow-lg transition-shadow cursor-pointer" onClick={handleClone}>
<CardContent className="p-6 flex flex-col flex-1">
{/* Header with name and author */}
<div className="mb-4">
@@ -148,19 +88,9 @@ export function RepositoryCard({ repo }: RepositoryCardProps) {
size="sm"
className="w-full"
onClick={handleClone}
disabled={isCloning}
>
{isCloning ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Cloning...
</>
) : (
<>
<GitBranch className="h-4 w-4 mr-2" />
Clone
</>
)}
<GitBranch className="h-4 w-4 mr-2" />
Clone
</Button>
</div>
</CardContent>
+4 -20
View File
@@ -27,18 +27,14 @@ describe('SentryProvider', () => {
relays: [{ url: 'wss://relay.test', read: true, write: true }],
updatedAt: 0,
},
graspMetadata: {
relays: [],
updatedAt: 0,
},
templates: [{ name: 'Test', description: 'Test template', url: 'https://test.git' }],
esmUrl: 'https://esm.test',
corsProxy: 'https://proxy.test/{href}',
faviconUrl: 'https://favicon.test/{href}',
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'test.dev',
showcaseEnabled: false,
showcaseModerator: '',
ngitServers: [],
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
@@ -68,18 +64,14 @@ describe('SentryProvider', () => {
relays: [{ url: 'wss://relay.test', read: true, write: true }],
updatedAt: 0,
},
graspMetadata: {
relays: [],
updatedAt: 0,
},
templates: [{ name: 'Test', description: 'Test template', url: 'https://test.git' }],
esmUrl: 'https://esm.test',
corsProxy: 'https://proxy.test/{href}',
faviconUrl: 'https://favicon.test/{href}',
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'test.dev',
showcaseEnabled: false,
showcaseModerator: '',
ngitServers: [],
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
@@ -110,18 +102,14 @@ describe('SentryProvider', () => {
relays: [{ url: 'wss://relay.test', read: true, write: true }],
updatedAt: 0,
},
graspMetadata: {
relays: [],
updatedAt: 0,
},
templates: [{ name: 'Test', description: 'Test template', url: 'https://test.git' }],
esmUrl: 'https://esm.test',
corsProxy: 'https://proxy.test/{href}',
faviconUrl: 'https://favicon.test/{href}',
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'test.dev',
showcaseEnabled: false,
showcaseModerator: '',
ngitServers: [],
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
@@ -155,18 +143,14 @@ describe('SentryProvider', () => {
relays: [{ url: 'wss://relay.test', read: true, write: true }],
updatedAt: 0,
},
graspMetadata: {
relays: [],
updatedAt: 0,
},
templates: [{ name: 'Test', description: 'Test template', url: 'https://test.git' }],
esmUrl: 'https://esm.test',
corsProxy: 'https://proxy.test/{href}',
faviconUrl: 'https://favicon.test/{href}',
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'test.dev',
showcaseEnabled: false,
showcaseModerator: '',
ngitServers: [],
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
+34 -7
View File
@@ -11,7 +11,6 @@ import { ModelSelector } from '@/components/ModelSelector';
interface ChatInputProps {
isLoading: boolean;
isConfigured: boolean;
isLoadingSettings: boolean;
providerModel: string;
onProviderModelChange: (model: string) => void;
onSend: (input: string, files: File[]) => void;
@@ -34,7 +33,6 @@ interface ChatInputProps {
export const ChatInput = memo(function ChatInput({
isLoading,
isConfigured,
isLoadingSettings,
providerModel,
onProviderModelChange,
onSend,
@@ -85,6 +83,35 @@ export const ChatInput = memo(function ChatInput({
}
}, [handleSend]);
const handlePaste = useCallback(async (e: React.ClipboardEvent) => {
const items = e.clipboardData?.items;
if (!items) return;
for (let i = 0; i < items.length; i++) {
const item = items[i];
// Check if the item is an image
if (item.type.startsWith('image/')) {
e.preventDefault(); // Prevent default paste behavior for images
const file = item.getAsFile();
if (file) {
// Generate a filename with timestamp
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const extension = file.type.split('/')[1] || 'png';
const filename = `pasted-image-${timestamp}.${extension}`;
// Create a new File object with the generated name
const namedFile = new File([file], filename, { type: file.type });
// Add to attached files
setAttachedFiles(prev => [...prev, namedFile]);
}
break; // Only handle the first image found
}
}
}, []);
const handleInputChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
setInput(e.target.value);
}, []);
@@ -105,7 +132,7 @@ export const ChatInput = memo(function ChatInput({
value={input}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
onPasteImage={(file) => setAttachedFiles(prev => [...prev, file])}
onPaste={handlePaste}
onFocus={onFocus}
placeholder={
!isConfigured
@@ -115,7 +142,7 @@ export const ChatInput = memo(function ChatInput({
: t('selectModelFirst')
}
className="flex-1 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
disabled={isLoadingSettings || isLoading || (isConfigured && !providerModel.trim())}
disabled={isLoading || (isConfigured && !providerModel.trim())}
rows={1}
aria-label="Chat message input"
style={{
@@ -136,7 +163,7 @@ export const ChatInput = memo(function ChatInput({
onFileSelect={handleFileSelect}
onFileRemove={handleFileRemove}
selectedFiles={attachedFiles}
disabled={isLoadingSettings || isLoading}
disabled={isLoading}
multiple={true}
/>
@@ -185,7 +212,7 @@ export const ChatInput = memo(function ChatInput({
<ModelSelector
value={providerModel}
onChange={onProviderModelChange}
disabled={isLoadingSettings || isLoading}
disabled={isLoading}
placeholder={t('chooseModel')}
open={isModelSelectorOpen}
onOpenChange={onModelSelectorOpenChange}
@@ -207,7 +234,7 @@ export const ChatInput = memo(function ChatInput({
<Button
onClick={handleSend}
onMouseDown={onFirstInteraction}
disabled={isLoadingSettings || (!input.trim() && attachedFiles.length === 0) || (isConfigured && !providerModel.trim())}
disabled={(!input.trim() && attachedFiles.length === 0) || (isConfigured && !providerModel.trim())}
size="sm"
className="size-8 [&_svg]:size-5 rounded-full p-0"
>
+10 -6
View File
@@ -24,6 +24,7 @@ import { NpmAddPackageTool } from '@/lib/tools/NpmAddPackageTool';
import { NpmRemovePackageTool } from '@/lib/tools/NpmRemovePackageTool';
import { GitCommitTool } from '@/lib/tools/GitCommitTool';
import { BuildProjectTool } from '@/lib/tools/BuildProjectTool';
import { DeployProjectTool } from '@/lib/tools/DeployProjectTool';
import { NostrReadNipTool } from '@/lib/tools/NostrReadNipTool';
import { NostrFetchEventTool } from '@/lib/tools/NostrFetchEventTool';
import { NostrReadKindTool } from '@/lib/tools/NostrReadKindTool';
@@ -96,15 +97,14 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const [templateInfo, setTemplateInfo] = useState<{ name: string; description: string; url: string } | null>(null);
const [showTemplateInfo, setShowTemplateInfo] = useState(false);
// Determine which error to show - AI errors take priority over console errors
// since they are more immediately relevant to the user's current action
const displayError = aiError || consoleError;
// Determine which error to show - console error takes priority over AI errors
const displayError = consoleError || aiError;
// Use external state if provided, otherwise default to false
const isBuildLoading = externalIsBuildLoading || false;
const scrollAreaRef = useRef<HTMLDivElement>(null);
const aiSettings = useAISettings();
const { isConfigured, settings, addRecentlyUsedModel, isLoading: isLoadingSettings } = aiSettings;
const { isConfigured, settings, addRecentlyUsedModel } = aiSettings;
const [providerModel, setProviderModel] = useState(() => {
// Initialize with first recently used model if available, otherwise empty
return settings.recentlyUsedModels?.[0] || '';
@@ -185,6 +185,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
skill: new SkillTool(fs, pluginsPath, cwd),
};
// Add deploy tool only if user is logged in
if (user && user.signer) {
tools.deploy_project = new DeployProjectTool(fs, cwd, user.signer, projectId);
}
// Add generate_image tool if imageModel is configured
if (settings.imageModel) {
try {
@@ -234,7 +239,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
return tools;
}, [fs, git, cwd, user, projectsPath, tmpPath, pluginsPath, config.corsProxy, settings, aiSettings, models, 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]);
@@ -783,7 +788,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
<ChatInput
isLoading={isLoading}
isConfigured={isConfigured}
isLoadingSettings={isLoadingSettings}
providerModel={providerModel}
onProviderModelChange={handleModelChange}
onSend={handleSend}
+165 -121
View File
@@ -10,11 +10,16 @@ import { useBuildProject } from '@/hooks/useBuildProject';
import { Tabs, TabsContent } from '@/components/ui/tabs';
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
import { Button } from '@/components/ui/button';
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Loader2, Code, X, Terminal, Expand, Shrink, Hammer } from 'lucide-react';
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, Rocket, X, Terminal } from 'lucide-react';
import { useIsMobile } from '@/hooks/useIsMobile';
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
import { type DeviceMode } from '@/components/ui/device-toggle';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
Popover,
PopoverContent,
@@ -23,6 +28,7 @@ import {
import { cn } from '@/lib/utils';
import { FileTree } from './FileTree';
import { FileEditor } from './FileEditor';
import { DeployDialog } from '@/components/DeployDialog';
import { Terminal as TerminalComponent } from '@/components/Terminal';
import { useSearchParams } from 'react-router-dom';
import { useAppContext } from '@/hooks/useAppContext';
@@ -32,6 +38,8 @@ interface PreviewPaneProps {
projectId: string;
activeTab: 'preview' | 'code';
onToggleView?: () => void;
projectName?: string;
onFirstInteraction?: () => void;
isPreviewable?: boolean;
}
@@ -65,7 +73,7 @@ interface JSONRPCResponse {
id: number;
}
export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable = true }: PreviewPaneProps) {
export function PreviewPane({ projectId, activeTab, onToggleView, projectName, onFirstInteraction: _onFirstInteraction, isPreviewable = true }: PreviewPaneProps) {
const { t } = useTranslation();
const { config } = useAppContext();
const { previewDomain } = config;
@@ -80,9 +88,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
const [navigationHistory, setNavigationHistory] = useState<string[]>(['/']);
const [historyIndex, setHistoryIndex] = useState(0);
const [isFullscreen, setIsFullscreen] = useState(false);
const [deviceMode, setDeviceMode] = useState<DeviceMode>('laptop');
const previewContainerRef = useRef<HTMLDivElement>(null);
const [deployDialogOpen, setDeployDialogOpen] = useState(false);
const iframeRef = useRef<HTMLIFrameElement>(null);
const { fs } = useFS();
const { projectsPath } = useFSPaths();
@@ -96,6 +102,14 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
const [searchParams, setSearchParams] = useSearchParams();
const [shouldBuild, setShouldBuild] = useState(false);
const handleBuildProject = useCallback(() => {
buildProject(undefined, {
onError: (error) => {
console.error('Build failed:', error);
}
});
}, [buildProject]);
// Handle "build" URL parameter on initial load
useEffect(() => {
if (searchParams.has('build')) {
@@ -112,13 +126,9 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
useEffect(() => {
if (shouldBuild && isPreviewable && !isBuildLoading) {
setShouldBuild(false);
buildProject(undefined, {
onError: (error) => {
console.error('Build failed:', error);
}
});
handleBuildProject();
}
}, [isBuildLoading, isPreviewable, buildProject, shouldBuild]);
}, [isBuildLoading, isPreviewable, handleBuildProject, shouldBuild]);
const loadFileContent = useCallback(async (filePath: string) => {
// Skip loading media files - they can't be edited as text
@@ -179,17 +189,14 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
// Legacy refresh function for build completion events
const refreshIframeLegacy = useCallback(() => {
if (iframeRef.current) {
// Force reload the iframe by updating its src with a timestamp to bust cache
const currentSrc = `https://${projectId}.${previewDomain}/`;
const newSrc = `${currentSrc}?_refresh=${Date.now()}`;
iframeRef.current.src = newSrc;
// After a brief moment, remove the query param to clean up the URL
// Force reload the iframe by updating its src
iframeRef.current.src = '/';
// Use a small timeout to ensure the src is cleared before setting it back
setTimeout(() => {
if (iframeRef.current) {
iframeRef.current.src = currentSrc;
iframeRef.current.src = `https://${projectId}.${previewDomain}/`;
}
}, 100);
}, 10);
}
}, [projectId, previewDomain]);
@@ -284,9 +291,33 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
sendNavigationCommand('refresh');
}, [sendNavigationCommand]);
const toggleFullscreen = useCallback(() => {
setIsFullscreen(prev => !prev);
}, []);
const goBackIframe = useCallback(() => {
if (historyIndex > 0) {
// Move back in history
const newIndex = historyIndex - 1;
const targetPath = navigationHistory[newIndex];
setHistoryIndex(newIndex);
setCurrentPath(targetPath);
// Tell iframe to navigate to this path
sendNavigationCommand('navigate', { url: targetPath });
}
}, [historyIndex, navigationHistory, sendNavigationCommand]);
const goForwardIframe = useCallback(() => {
if (historyIndex < navigationHistory.length - 1) {
// Move forward in history
const newIndex = historyIndex + 1;
const targetPath = navigationHistory[newIndex];
setHistoryIndex(newIndex);
setCurrentPath(targetPath);
// Tell iframe to navigate to this path
sendNavigationCommand('navigate', { url: targetPath });
}
}, [historyIndex, navigationHistory, sendNavigationCommand]);
const handleFetch = useCallback(async (request: JSONRPCRequest) => {
const { params, id } = request;
@@ -491,11 +522,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
// Automatically trigger a rebuild after saving a file
if (isPreviewable) {
console.log('File saved, triggering rebuild...');
buildProject(undefined, {
onError: (error) => {
console.error('Build failed:', error);
}
});
handleBuildProject();
}
} catch (error) {
console.error('Failed to save file:', error);
@@ -526,7 +553,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
<Button
variant="ghost"
size="sm"
className="h-8 gap-2 relative"
className="h-8 w-8 p-0 relative"
>
<Bug className="h-4 w-4" />
{hasConsoleErrors && (
@@ -536,7 +563,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
</PopoverTrigger>
<PopoverContent
align="end"
className="w-[calc(100vw-1rem)] max-w-[480px] max-h-[512px] overflow-hidden shadow-lg border rounded-lg bg-background p-0 z-[9999]"
className="w-[calc(100vw-1rem)] max-w-[480px] max-h-[512px] overflow-hidden shadow-lg border rounded-lg bg-background p-0"
sideOffset={4}
>
@@ -601,111 +628,118 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
);
};
const Menu = () => {
const isAnyLoading = isBuildLoading;
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0"
>
<MenuIcon className="h-4 w-4" />
<span className="sr-only">Open menu</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48 sm:w-48">
<DropdownMenuItem
onClick={handleBuildProject}
disabled={isBuildLoading}
className="gap-2"
>
{isBuildLoading ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Play className="h-4 w-4" />
)}
{isBuildLoading ? 'Building...' : 'Build'}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setDeployDialogOpen(true)}
disabled={isAnyLoading}
className="gap-2"
>
<Rocket className="h-4 w-4" />
Deploy
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
};
return (
<div className="h-full">
<Tabs value={activeTab} className="h-full">
{isPreviewable && (
<TabsContent value="preview" className="h-full mt-0">
<div
ref={previewContainerRef}
className={cn(
"h-full w-full flex flex-col relative",
isFullscreen && "fixed inset-0 z-[100] bg-background"
)}
>
{/* Top navigation bar */}
<div className="h-12 flex items-center gap-2 p-2 border-b bg-background w-full">
{/* Left side - fullscreen toggle */}
<Button
variant="ghost"
size="sm"
onClick={toggleFullscreen}
className="h-8 w-8 p-0"
title={isFullscreen ? 'Exit immersive view' : 'Enter immersive view'}
>
{isFullscreen ? (
<Shrink className="h-4 w-4" />
) : (
<Expand className="h-4 w-4" />
<div className="h-full w-full flex flex-col relative">
{/* Always show browser address bar */}
<div className="h-12 flex items-center w-full">
<BrowserAddressBar
currentPath={currentPath}
onNavigate={hasBuiltProject ? navigateIframe : undefined}
onRefresh={hasBuiltProject ? refreshIframe : undefined}
onBack={hasBuiltProject ? goBackIframe : undefined}
onForward={hasBuiltProject ? goForwardIframe : undefined}
canGoBack={hasBuiltProject && historyIndex > 0}
canGoForward={hasBuiltProject && historyIndex < navigationHistory.length - 1}
extraContent={(
<div className="flex items-center">
{(!isMobile && onToggleView && isPreviewable) && (
<Button
variant="ghost"
size="sm"
onClick={onToggleView}
className="h-8 gap-2"
>
<Code className="h-4 w-4" />
</Button>
)}
<ConsoleDropdown />
<Menu />
</div>
)}
</Button>
{/* Center - address bar with device toggle */}
<div className="flex-1 px-6">
<div className="relative max-w-64 mx-auto">
<BrowserAddressBar
currentPath={currentPath}
onNavigate={hasBuiltProject ? navigateIframe : undefined}
onRefresh={hasBuiltProject ? refreshIframe : undefined}
navigationHistory={navigationHistory}
deviceMode={deviceMode}
onDeviceModeChange={setDeviceMode}
/>
</div>
</div>
{/* Right side - actions */}
<div className="flex items-center gap-1">
{/* Build button */}
<Button
variant="ghost"
size="sm"
onClick={() => buildProject(undefined, {
onError: (error) => {
console.error('Build failed:', error);
}
})}
disabled={isBuildLoading}
className="h-8 gap-2"
title="Build project"
>
{isBuildLoading ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Hammer className="h-4 w-4" />
)}
</Button>
{(!isMobile && onToggleView && isPreviewable) && (
<Button
variant="ghost"
size="sm"
onClick={onToggleView}
className="h-8 gap-2"
>
<Code className="h-4 w-4" />
</Button>
)}
<ConsoleDropdown />
</div>
/>
</div>
{/* Content area */}
<div className="flex-1 flex items-center justify-center bg-muted/30">
<div className="flex-1">
{hasBuiltProject ? (
<div
className={cn(
"h-full transition-all duration-300 ease-in-out bg-background",
deviceMode === 'laptop' && "w-full",
deviceMode === 'tablet' && "w-full max-w-3xl shadow-lg",
deviceMode === 'phone' && "w-full max-w-sm shadow-lg"
)}
>
<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 allow-forms"
/>
</div>
<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 allow-forms"
/>
) : (
<div className="h-full w-full flex items-center justify-center bg-muted">
<div className="h-full flex items-center justify-center bg-muted">
<div className="text-center">
<h3 className="text-lg font-semibold mb-2">{t('projectPreview')}</h3>
<p className="text-muted-foreground">
<p className="text-muted-foreground mb-4">
{t('buildProjectToSeePreview')}
</p>
<Button
onClick={handleBuildProject}
disabled={isBuildLoading}
variant="outline"
className="gap-2"
>
{isBuildLoading ? (
<>
<Loader2 className="h-5 w-5 animate-spin" />
Building...
</>
) : (
<>
<Play className="h-5 w-5" />
Build Project
</>
)}
</Button>
</div>
</div>
)}
@@ -905,6 +939,16 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
)}
</TabsContent>
</Tabs>
{/* Deploy Dialog */}
{projectName && (
<DeployDialog
projectId={projectId}
projectName={projectName}
open={deployDialogOpen}
onOpenChange={setDeployDialogOpen}
/>
)}
</div>
);
}
}
+1 -1
View File
@@ -61,7 +61,7 @@ export function StarButton({
>
<Star
className={cn(
"size-5",
"h-4 w-4",
isFavorite ? "text-yellow-500 fill-current" : "text-muted-foreground hover:text-yellow-500"
)}
/>
+5 -3
View File
@@ -428,11 +428,13 @@ export function ToolCallDisplay({ toolName, toolArgs, state, result }: ToolCallD
// For completed state, we need the result
if (!result) return null;
// Parse "Generated image: /tmp/filename.png" from result
const match = result.match(/Generated image:\s*(\/tmp\/[^\s\n]+)/);
// 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];
const filename = imagePath.split('/').pop() || imagePath;
// 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;
@@ -0,0 +1,61 @@
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { UserMessage } from './UserMessage';
describe('UserMessage Integration', () => {
it('renders text parts with file attachments correctly', () => {
// Simulate the new text parts structure that ChatPane would create
const content = [
{ type: 'text' as const, text: 'Please analyze this file:' },
{ type: 'text' as const, text: 'Added file: /tmp/data.csv' },
{ type: 'text' as const, text: 'Let me know what you find!' }
];
render(<UserMessage content={content} />);
// Check that regular text is displayed
expect(screen.getByText('Please analyze this file:')).toBeInTheDocument();
expect(screen.getByText('Let me know what you find!')).toBeInTheDocument();
// Check that file attachment is rendered as a badge
expect(screen.getByText('data.csv')).toBeInTheDocument();
// Full path should not be displayed
expect(screen.queryByText('/tmp/data.csv')).not.toBeInTheDocument();
});
it('handles single text part with file attachment', () => {
const content = [
{ type: 'text' as const, text: 'Added file: /tmp/script.js' }
];
render(<UserMessage content={content} />);
expect(screen.getByText('script.js')).toBeInTheDocument();
// Full path should not be displayed
expect(screen.queryByText('/tmp/script.js')).not.toBeInTheDocument();
});
it('handles multiple file attachments in separate parts', () => {
const content = [
{ type: 'text' as const, text: 'Here are my files:' },
{ type: 'text' as const, text: 'Added file: /tmp/config.json' },
{ type: 'text' as const, text: 'Added file: /tmp/styles.css' },
{ type: 'text' as const, text: 'Added file: /tmp/main.js' }
];
render(<UserMessage content={content} />);
expect(screen.getByText('Here are my files:')).toBeInTheDocument();
expect(screen.getByText('config.json')).toBeInTheDocument();
expect(screen.getByText('styles.css')).toBeInTheDocument();
expect(screen.getByText('main.js')).toBeInTheDocument();
});
it('handles empty content gracefully', () => {
const content: Array<{ type: 'text'; text: string }> = [];
const { container } = render(<UserMessage content={content} />);
expect(container.firstChild).toBeNull();
});
});
+113
View File
@@ -0,0 +1,113 @@
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { UserMessage } from './UserMessage';
describe('UserMessage', () => {
it('renders regular text without file attachments', () => {
const content = 'This is a regular message without any file attachments.';
render(<UserMessage content={content} />);
expect(screen.getByText(content)).toBeInTheDocument();
});
it('handles backward compatibility with string content containing file attachments', () => {
const content = 'Here is my file: Added file: /tmp/test.txt';
render(<UserMessage content={content} />);
// When using string content, it should parse and separate file attachments
expect(screen.getByText('Here is my file:')).toBeInTheDocument();
expect(screen.getByText('test.txt')).toBeInTheDocument();
// Full path should not be displayed
expect(screen.queryByText('/tmp/test.txt')).not.toBeInTheDocument();
});
it('renders file attachment badges for single file with text parts', () => {
const content = [
{ type: 'text' as const, text: 'Here is my file:' },
{ type: 'text' as const, text: 'Added file: /tmp/test.txt' }
];
render(<UserMessage content={content} />);
expect(screen.getByText('Here is my file:')).toBeInTheDocument();
expect(screen.getByText('test.txt')).toBeInTheDocument();
// Full path should not be displayed
expect(screen.queryByText('/tmp/test.txt')).not.toBeInTheDocument();
});
it('renders multiple file attachments with text parts', () => {
const content = [
{ type: 'text' as const, text: 'Files uploaded:' },
{ type: 'text' as const, text: 'Added file: /tmp/document.pdf' },
{ type: 'text' as const, text: 'Added file: /tmp/image.jpg' },
{ type: 'text' as const, text: 'All done!' }
];
render(<UserMessage content={content} />);
expect(screen.getByText('Files uploaded:')).toBeInTheDocument();
expect(screen.getByText('document.pdf')).toBeInTheDocument();
expect(screen.getByText('image.jpg')).toBeInTheDocument();
expect(screen.getByText('All done!')).toBeInTheDocument();
});
it('renders text files with FileText icon', () => {
const content = [{ type: 'text' as const, text: 'Added file: /tmp/script.js' }];
render(<UserMessage content={content} />);
expect(screen.getByText('script.js')).toBeInTheDocument();
// FileText icon should be rendered (we can't easily test the icon itself, but we can test the component renders)
});
it('handles files without extensions', () => {
const content = [{ type: 'text' as const, text: 'Added file: /tmp/README' }];
render(<UserMessage content={content} />);
expect(screen.getByText('README')).toBeInTheDocument();
// Full path should not be displayed
expect(screen.queryByText('/tmp/README')).not.toBeInTheDocument();
});
it('handles complex filenames with underscores and numbers', () => {
const content = [{ type: 'text' as const, text: 'Added file: /tmp/my_file_1.txt' }];
render(<UserMessage content={content} />);
expect(screen.getByText('my_file_1.txt')).toBeInTheDocument();
// Full path should not be displayed
expect(screen.queryByText('/tmp/my_file_1.txt')).not.toBeInTheDocument();
});
it('preserves whitespace in text content', () => {
const content = [
{ type: 'text' as const, text: 'Line 1\n\nLine 3 with spaces \n\nFinal line' },
{ type: 'text' as const, text: 'Added file: /tmp/test.txt' }
];
const { container } = render(<UserMessage content={content} />);
// Check that the component renders and contains the expected text content
expect(container.textContent).toContain('Line 1');
expect(container.textContent).toContain('Line 3 with spaces');
expect(container.textContent).toContain('Final line');
expect(screen.getByText('test.txt')).toBeInTheDocument();
});
it('handles mixed content with file attachments in the middle', () => {
const content = [
{ type: 'text' as const, text: 'Starting text' },
{ type: 'text' as const, text: 'Added file: /tmp/middle.txt' },
{ type: 'text' as const, text: 'ending text' }
];
render(<UserMessage content={content} />);
expect(screen.getByText('Starting text')).toBeInTheDocument();
expect(screen.getByText('middle.txt')).toBeInTheDocument();
expect(screen.getByText('ending text')).toBeInTheDocument();
});
});
+77 -32
View File
@@ -3,7 +3,7 @@ import { Badge } from '@/components/ui/badge';
import type OpenAI from 'openai';
interface UserMessageProps {
content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPart>;
content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText>;
}
/**
@@ -13,12 +13,71 @@ interface UserMessageProps {
*/
export function UserMessage({ content }: UserMessageProps) {
// Convert content to array format for uniform processing
const parts = typeof content === 'string'
const contentParts = typeof content === 'string'
? [{ type: 'text' as const, text: content }]
: content.filter(part => part.type === 'text');
: content.filter(part => part.type === 'text') as Array<{ type: 'text'; text: string }>;
// Regular expression to match "Added file: /tmp/<filename>" patterns
// Matches the pattern anywhere in the text
const filePattern = /Added file:\s*(\/tmp\/[^\s\n]+)/g;
// Process each content part and categorize as text or file
const processedParts: Array<{ type: 'text' | 'file'; content: string; filepath?: string }> = [];
contentParts.forEach(part => {
const text = part.text.trim();
// Find all file patterns in this text part
const fileMatches: Array<{ filepath: string; index: number; length: number }> = [];
let match;
filePattern.lastIndex = 0; // Reset regex
while ((match = filePattern.exec(text)) !== null) {
fileMatches.push({
filepath: match[1], // "/tmp/filename.txt"
index: match.index,
length: match[0].length
});
}
if (fileMatches.length > 0) {
// Split text around file patterns and process each segment
let lastIndex = 0;
fileMatches.forEach((fileMatch) => {
// Add text before the file pattern
if (fileMatch.index > lastIndex) {
const textBefore = text.substring(lastIndex, fileMatch.index).trim();
if (textBefore) {
processedParts.push({ type: 'text', content: textBefore });
}
}
// Add the file attachment badge (without showing "Added file:" text)
processedParts.push({
type: 'file',
content: '', // Empty - badge will show filename only
filepath: fileMatch.filepath
});
lastIndex = fileMatch.index + fileMatch.length;
});
// Add remaining text after the last file pattern
if (lastIndex < text.length) {
const textAfter = text.substring(lastIndex).trim();
if (textAfter) {
processedParts.push({ type: 'text', content: textAfter });
}
}
} else if (text) {
// No file patterns found, treat as regular text
processedParts.push({ type: 'text', content: text });
}
});
// If no content, return empty
if (parts.length === 0) {
if (processedParts.length === 0) {
return null;
}
@@ -28,42 +87,28 @@ export function UserMessage({ content }: UserMessageProps) {
return (
<div className="space-y-2">
{parts.map((part, index) => {
{processedParts.map((part, index) => {
if (part.type === 'text') {
// Only render text if it has content
if (!part.text.trim()) return null;
// Detect "Added file: <filename>" pattern
const fileAddedMatch = /^Added file: (\/[^\s\n]+$)/g.exec(part.text);
console.log('fileAddedMatch', part, fileAddedMatch);
if (fileAddedMatch && fileAddedMatch[1]) {
const path = fileAddedMatch[1];
const filename = getFileName(path);
return (
<div key={index} className="flex items-center gap-2 max-w-full min-w-0">
<Badge variant="secondary" className="inline-flex items-center gap-1.5 px-2 py-1 max-w-full">
<span className="flex-shrink-0">
<Paperclip className="h-3 w-3" />
</span>
<span className="text-xs font-medium truncate min-w-0" title={filename}>
{filename}
</span>
</Badge>
</div>
);
}
// Regular text rendering
if (!part.content.trim()) return null;
return (
<div key={index} className="whitespace-pre-wrap">
{part.text}
{part.content}
</div>
);
} else {
// Unsupported content type
// Render file attachment badge (no "Added file:" text)
const filename = getFileName(part.filepath!);
return (
<div key={index} className="text-sm text-red-500">
[Unsupported content type]
<div key={index} className="flex items-center gap-2 max-w-full min-w-0">
<Badge variant="secondary" className="inline-flex items-center gap-1.5 px-2 py-1 max-w-full">
<span className="flex-shrink-0">
<Paperclip className="h-3 w-3" />
</span>
<span className="text-xs font-medium truncate min-w-0" title={filename}>
{filename}
</span>
</Badge>
</div>
);
}
-44
View File
@@ -1,44 +0,0 @@
import { useState } from 'react';
import { Rocket } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { cn } from '@/lib/utils';
import { DeploySteps } from './DeploySteps';
interface DeployPopoverProps {
projectId: string;
projectName: string;
className?: string;
disabled?: boolean;
}
export function DeployPopover({ projectId, projectName, className, disabled }: DeployPopoverProps) {
const [open, setOpen] = useState(false);
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="ghost"
size="sm"
className={cn("h-8 w-8 p-0", className)}
aria-label="Deploy project"
disabled={disabled}
>
<Rocket className="size-5 text-muted-foreground" />
</Button>
</PopoverTrigger>
<PopoverContent
align="start"
className="w-96"
onOpenAutoFocus={(e) => e.preventDefault()}
>
<DeploySteps
projectId={projectId}
projectName={projectName}
onClose={() => setOpen(false)}
/>
</PopoverContent>
</Popover>
);
}
-2
View File
@@ -4,5 +4,3 @@ export { VercelDeployForm } from './VercelDeployForm';
export { NsiteDeployForm } from './NsiteDeployForm';
export { CloudflareDeployForm } from './CloudflareDeployForm';
export { DenoDeployForm } from './DenoDeployForm';
export { DeployPopover } from './DeployPopover';
export { DeploySteps } from './DeploySteps';
-51
View File
@@ -1,51 +0,0 @@
import { useState } from 'react';
import { CloudUpload } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { useGitStatus } from '@/hooks/useGitStatus';
import { cn } from '@/lib/utils';
import { GitSyncSteps } from './GitSyncSteps';
interface GitSyncButtonProps {
projectId: string;
className?: string;
}
export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
const [open, setOpen] = useState(false);
const { data: gitStatus, isLoading: isGitStatusLoading } = useGitStatus(projectId);
// Determine if we have a remote configured
const originRemote = gitStatus?.remotes.find(r => r.name === 'origin');
const hasRemote = !!originRemote;
// Determine if we need to show the indicator dot
// Show indicator if no origin remote is configured, UNLESS there are less than 2 commits
const showIndicator = !isGitStatusLoading && !hasRemote && (gitStatus?.totalCommits ?? 0) >= 2;
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="ghost"
size="sm"
className={cn("h-8 w-8 p-0 relative", className)}
aria-label="Sync with Git"
>
<CloudUpload className="size-5 text-muted-foreground" />
{showIndicator && (
<span className="absolute top-1 right-1 h-2 w-2 rounded-full bg-primary" />
)}
</Button>
</PopoverTrigger>
<PopoverContent
align="start"
className="w-96"
onOpenAutoFocus={(e) => e.preventDefault()}
>
<GitSyncSteps projectId={projectId} onClose={() => setOpen(false)} />
</PopoverContent>
</Popover>
);
}
-112
View File
@@ -1,112 +0,0 @@
import { useState, useEffect } from 'react';
import { useGitStatus } from '@/hooks/useGitStatus';
import { SelectProviderStep } from './steps/SelectProviderStep';
import { ConfigureRepoStep } from './steps/ConfigureRepoStep';
import { SyncStep } from './steps/SyncStep';
import { InitSuccessStep } from './steps/InitSuccessStep';
import type { StepType, ProviderOption } from './types';
interface GitSyncStepsProps {
projectId: string;
onClose: () => void;
}
export function GitSyncSteps({ projectId, onClose }: GitSyncStepsProps) {
const { data: gitStatus, isLoading: isGitStatusLoading } = useGitStatus(projectId);
// Determine if we have a remote configured
const originRemote = gitStatus?.remotes.find(r => r.name === 'origin');
const hasRemote = !!originRemote;
const [currentStep, setCurrentStep] = useState<StepType>(hasRemote ? 'sync' : 'select-provider');
const [selectedProvider, setSelectedProvider] = useState<ProviderOption | null>(null);
// Handle a remote being added after loading
useEffect(() => {
if (hasRemote && currentStep === 'select-provider') {
setCurrentStep('sync');
} else if (!hasRemote && currentStep === 'sync') {
setCurrentStep('select-provider');
}
}, [hasRemote, currentStep]);
// Auto-reset success state after 2 seconds
useEffect(() => {
if (currentStep === 'init-success') {
const timer = setTimeout(() => {
setCurrentStep('sync');
}, 2000);
return () => clearTimeout(timer);
}
}, [currentStep]);
const handleSelectProvider = (provider: ProviderOption) => {
setSelectedProvider(provider);
setCurrentStep('configure-repo');
};
const handleBack = () => {
setCurrentStep('select-provider');
setSelectedProvider(null);
};
const handleSuccess = () => {
setCurrentStep('init-success');
};
// Don't render anything while loading git status
if (isGitStatusLoading) {
return (
<div className="flex items-center justify-center py-8">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
</div>
);
}
// Render the appropriate step
if (currentStep === 'select-provider') {
return (
<SelectProviderStep
projectId={projectId}
onSelectProvider={handleSelectProvider}
onChangeStep={setCurrentStep}
onClose={onClose}
/>
);
}
if (currentStep === 'configure-repo' && selectedProvider) {
return (
<ConfigureRepoStep
projectId={projectId}
selectedProvider={selectedProvider}
onBack={handleBack}
onSuccess={handleSuccess}
onChangeStep={setCurrentStep}
onClose={onClose}
/>
);
}
if (currentStep === 'sync') {
return (
<SyncStep
projectId={projectId}
onChangeStep={setCurrentStep}
onClose={onClose}
/>
);
}
if (currentStep === 'init-success') {
return (
<InitSuccessStep
projectId={projectId}
onChangeStep={setCurrentStep}
onClose={onClose}
/>
);
}
return null;
}
-2
View File
@@ -1,2 +0,0 @@
export { GitSyncButton } from './GitSyncButton';
export type { ProviderOption, StepType } from './types';
@@ -1,342 +0,0 @@
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useGit } from '@/hooks/useGit';
import { useGitStatus } from '@/hooks/useGitStatus';
import { useFSPaths } from '@/hooks/useFSPaths';
import { useNostr } from '@nostrify/react';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useFS } from '@/hooks/useFS';
import { useAppContext } from '@/hooks/useAppContext';
import { Link } from 'react-router-dom';
import { createRepositoryAnnouncementEvent } from '@/lib/announceRepository';
import { DotAI } from '@/lib/DotAI';
import { nip19 } from 'nostr-tools';
import type { ConfigureRepoStepProps } from '../types';
import type { NostrEvent } from '@nostrify/nostrify';
import { NostrURI } from '@/lib/NostrURI';
export function ConfigureRepoStep({
projectId,
selectedProvider,
onBack,
onSuccess,
onClose,
}: ConfigureRepoStepProps) {
const [repositoryUrl, setRepositoryUrl] = useState('');
const [isPushing, setIsPushing] = useState(false);
const [error, setError] = useState<string | null>(null);
const { user } = useCurrentUser();
const { git } = useGit();
const { projectsPath } = useFSPaths();
const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId);
const { nostr } = useNostr();
const { mutateAsync: publishEvent } = useNostrPublish();
const { fs } = useFS();
const { config } = useAppContext();
const handlePushInitial = async () => {
setIsPushing(true);
setError(null);
try {
const dir = `${projectsPath}/${projectId}`;
if (selectedProvider.id === 'nostr') {
if (!user) {
throw new Error('User is not logged in');
}
// Check if a NIP-34 repo announcement already exists for this project
const existingRepos = await nostr.query(
[{ kinds: [30617], authors: [user.pubkey], '#d': [projectId], limit: 1 }],
{ signal: AbortSignal.timeout(5000) }
);
// Convert user's GRASP servers to clone URLs and relay URLs
const npub = nip19.npubEncode(user.pubkey);
const cloneUrls = new Set<string>();
const relays = new Set<string>();
for (const graspRelay of config.graspMetadata.relays) {
try {
const relayUrl = new URL(graspRelay.url);
relays.add(relayUrl.href);
const cloneUrl = new URL(`/${npub}/${projectId}.git`, `https://${relayUrl.host}`);
cloneUrls.add(cloneUrl.href);
} catch (err) {
console.warn(`Failed to parse Nostr git relay URL: ${graspRelay.url}`, err);
}
}
// Validate that we have at least one clone URL and relay
if (cloneUrls.size === 0 || relays.size === 0) {
throw new Error('No Nostr git servers configured. Please configure Nostr git servers in Settings > Nostr.');
}
let repoEvent: NostrEvent;
if (existingRepos.length > 0) {
// Use existing repo announcement as template and update with current GRASP servers
const existingEvent = existingRepos[0];
// Extract existing data from the event
const name = existingEvent.tags.find(([tagName]) => tagName === 'name')?.[1];
const description = existingEvent.tags.find(([tagName]) => tagName === 'description')?.[1];
const webTag = existingEvent.tags.find(([tagName]) => tagName === 'web');
const webUrls = webTag ? webTag.slice(1) : undefined;
const tTags = existingEvent.tags
.filter(([tagName]) => tagName === 't')
.map(([, value]) => value);
const eucTag = existingEvent.tags.find(([tagName, , marker]) => tagName === 'r' && marker === 'euc');
const earliestCommit = eucTag?.[1];
// Create updated repository announcement event with new clone URLs and relays
const eventTemplate = createRepositoryAnnouncementEvent({
repoId: projectId,
name,
description,
webUrls,
cloneUrls: [...cloneUrls],
relays: [...relays],
tTags: tTags.length > 0 ? tTags : undefined,
earliestCommit,
});
// Publish the updated event
repoEvent = await publishEvent(eventTemplate);
} else {
// Create and publish new NIP-34 repository announcement
// Get the template name
const dotAI = new DotAI(fs, `${projectsPath}/${projectId}`);
const template = await dotAI.readTemplate();
// Build t-tags array
const tTags = ['shakespeare'];
if (template) {
tTags.push(template.name);
}
// Create the repository announcement event
const eventTemplate = createRepositoryAnnouncementEvent({
repoId: projectId,
name: projectId,
cloneUrls: [...cloneUrls],
relays: [...relays],
tTags,
});
// Publish the event
repoEvent = await publishEvent(eventTemplate);
}
// Wait 5 seconds for Nostr git servers to update
await new Promise(resolve => setTimeout(resolve, 5000));
// Construct Nostr URI
const nostrURI = new NostrURI({ pubkey: repoEvent.pubkey, identifier: projectId });
// Configure the Nostr URI as the origin
await git.addRemote({
dir,
remote: 'origin',
url: nostrURI.toString(),
force: true,
});
// Push to Nostr (the rest of the Nostr logic is handled internally by git.push)
await git.push({
dir,
remote: 'origin',
ref: gitStatus?.currentBranch || 'main',
});
} else {
// Validate repository URL
if (!repositoryUrl.trim()) {
throw new Error('Repository URL is required');
}
// Add remote
await git.addRemote({
dir,
remote: 'origin',
url: repositoryUrl,
force: true, // Override if exists
});
// Push to remote
await git.push({
dir,
remote: 'origin',
ref: gitStatus?.currentBranch || 'main',
});
}
// Refresh git status before showing success
await refetchGitStatus();
// Show success state
onSuccess();
} catch (err) {
const message = err instanceof Error ? err.message : 'Failed to push';
setError(message);
} finally {
setIsPushing(false);
}
};
// "Other" provider - show link to git settings
if (selectedProvider.id === 'other') {
return (
<div className="space-y-4">
<div className="flex items-center gap-2">
{selectedProvider.icon}
<h3 className="font-semibold">{selectedProvider.name}</h3>
</div>
<p className="text-sm text-muted-foreground">
Configure additional git providers in{' '}
<Link
to="/settings/git"
className="underline hover:no-underline font-medium"
onClick={onClose}
>
Git Settings
</Link>
.
</p>
<Button
onClick={onBack}
variant="outline"
className="w-full"
>
Back
</Button>
</div>
);
}
// Nostr provider - check if user is logged in
if (selectedProvider.id === 'nostr') {
if (!user) {
return (
<div className="space-y-4">
<div className="flex items-center gap-2">
{selectedProvider.icon}
<h3 className="font-semibold">{selectedProvider.name}</h3>
</div>
<p className="text-sm text-muted-foreground">
You need to be logged in with Nostr to use this feature. Please visit{' '}
<Link
to="/settings/nostr"
className="underline hover:no-underline font-medium"
onClick={onClose}
>
Nostr Settings
</Link>{' '}
to log in.
</p>
<Button
onClick={onBack}
variant="outline"
className="w-full"
>
Back
</Button>
</div>
);
}
return (
<div className="space-y-4">
<div className="flex items-center gap-2">
{selectedProvider.icon}
<h3 className="font-semibold">{selectedProvider.name}</h3>
</div>
<p className="text-sm text-muted-foreground">
Push your code to Nostr with one click. Your repository will be stored on public Nostr git <Link className="underline" to="/settings/nostr">servers</Link>.
</p>
{error && (
<Alert variant="destructive">
<AlertDescription className="text-sm">{error}</AlertDescription>
</Alert>
)}
<div className="flex gap-2">
<Button
onClick={handlePushInitial}
disabled={isPushing}
className="flex-1"
>
{isPushing ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-current mr-2" />
Pushing...
</>
) : (
'Push'
)}
</Button>
</div>
</div>
);
}
// Regular git provider - show repository URL input
return (
<div className="space-y-4">
<div className="flex items-center gap-2">
{selectedProvider.icon}
<h3 className="font-semibold">{selectedProvider.name}</h3>
</div>
<div className="space-y-2">
<Label htmlFor="repo-url">Repository URL</Label>
<Input
id="repo-url"
placeholder="https://github.com/username/repo.git"
value={repositoryUrl}
onChange={(e) => setRepositoryUrl(e.target.value)}
/>
<p className="text-xs text-muted-foreground">
First create the repository on {selectedProvider.origin ? <a href={selectedProvider.origin} className="underline" target="_blank">{selectedProvider.name}</a> : selectedProvider.name}, then paste the URL here.
</p>
</div>
{error && (
<Alert variant="destructive">
<AlertDescription className="text-sm">{error}</AlertDescription>
</Alert>
)}
<div className="flex gap-2">
<Button
onClick={handlePushInitial}
disabled={isPushing || !repositoryUrl.trim()}
className="flex-1"
>
{isPushing ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-current mr-2" />
Pushing...
</>
) : (
'Push'
)}
</Button>
</div>
</div>
);
}
@@ -1,19 +0,0 @@
import { CheckCircle2 } from 'lucide-react';
import type { StepProps } from '../types';
export function InitSuccessStep(_props: StepProps) {
return (
<div className="flex flex-col items-center justify-center py-8 space-y-4">
<div className="relative">
<CheckCircle2 className="h-20 w-20 text-green-500 animate-in zoom-in duration-300" />
<div className="absolute inset-0 h-20 w-20 rounded-full bg-green-500/20 animate-ping" />
</div>
<div className="text-center space-y-1">
<h3 className="font-semibold text-lg">Successfully Synced!</h3>
<p className="text-sm text-muted-foreground">
Your code has been synced to the remote repository.
</p>
</div>
</div>
);
}
@@ -1,70 +0,0 @@
import { Zap, GitBranch } from 'lucide-react';
import { Label } from '@/components/ui/label';
import { ExternalFavicon } from '@/components/ExternalFavicon';
import { useGitSettings } from '@/hooks/useGitSettings';
import { cn } from '@/lib/utils';
import type { SelectProviderStepProps, ProviderOption } from '../types';
export function SelectProviderStep({
onSelectProvider,
}: SelectProviderStepProps) {
const { settings } = useGitSettings();
const providerOptions: ProviderOption[] = [
{
id: 'nostr',
name: 'Nostr',
icon: <Zap className="h-4 w-4" />,
},
...settings.credentials.map(credential => ({
id: credential.id,
name: credential.name,
origin: credential.origin,
icon: (
<ExternalFavicon
url={credential.origin}
size={16}
fallback={<GitBranch className="h-4 w-4" />}
/>
),
credential,
})),
{
id: 'other',
name: 'Other',
icon: <GitBranch className="h-4 w-4" />,
},
];
return (
<div className="space-y-4">
<div>
<h3 className="font-semibold mb-1">Sync your code to git</h3>
<p className="text-sm text-muted-foreground">
Choose a provider to sync your project
</p>
</div>
<div className="space-y-2">
<Label className="text-xs text-muted-foreground">Select Provider</Label>
<div className="flex flex-wrap gap-2">
{providerOptions.map((provider) => (
<button
key={provider.id}
type="button"
onClick={() => onSelectProvider(provider)}
className={cn(
"inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-sm font-medium transition-all",
"border-2 hover:scale-105 active:scale-95",
"bg-background text-foreground border-border hover:border-primary/50"
)}
>
{provider.icon}
<span>{provider.name}</span>
</button>
))}
</div>
</div>
</div>
);
}
-246
View File
@@ -1,246 +0,0 @@
import { useState } from 'react';
import { Zap, GitBranch, Copy, Check, RefreshCw, EllipsisVertical, CloudOff, ExternalLink } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Alert, AlertDescription } from '@/components/ui/alert';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { ExternalFavicon } from '@/components/ExternalFavicon';
import { useGitStatus } from '@/hooks/useGitStatus';
import { useGitSettings } from '@/hooks/useGitSettings';
import { useGit } from '@/hooks/useGit';
import { useFSPaths } from '@/hooks/useFSPaths';
import { useAppContext } from '@/hooks/useAppContext';
import type { StepProps } from '../types';
import { cn } from '@/lib/utils';
import { NostrURI } from '@/lib/NostrURI';
import { ngitWebUrl } from '@/lib/ngitWebUrl';
import { useQueryClient } from '@tanstack/react-query';
export function SyncStep({ projectId }: StepProps) {
const queryClient = useQueryClient();
const [isSyncing, setIsSyncing] = useState(false);
const [error, setError] = useState<string | null>(null);
const [copiedUrl, setCopiedUrl] = useState(false);
const [syncSuccess, setSyncSuccess] = useState(false);
const { data: gitStatus } = useGitStatus(projectId);
const { settings } = useGitSettings();
const { git } = useGit();
const { projectsPath } = useFSPaths();
const { config } = useAppContext();
const originRemote = gitStatus?.remotes.find(r => r.name === 'origin');
// Match origin URL to a credential
const matchedCredential = originRemote
? settings.credentials.find(c => originRemote.url.startsWith(c.origin))
: null;
const handleSync = async () => {
if (!originRemote) return;
setIsSyncing(true);
setError(null);
setSyncSuccess(false);
try {
const dir = `${projectsPath}/${projectId}`;
// Pull first to get latest changes
await git.pull({
dir,
ref: gitStatus?.currentBranch || 'main',
singleBranch: true,
});
// Then push local changes
await git.push({
dir,
remote: 'origin',
ref: gitStatus?.currentBranch || 'main',
});
// Show success feedback
setSyncSuccess(true);
setTimeout(() => setSyncSuccess(false), 1500);
} catch (err) {
const message = err instanceof Error ? err.message : 'Failed to sync';
setError(message);
} finally {
setIsSyncing(false);
}
};
const handleCopyUrl = async () => {
if (!originRemote) return;
try {
await navigator.clipboard.writeText(originRemote.url);
setCopiedUrl(true);
setTimeout(() => setCopiedUrl(false), 2000);
} catch (err) {
console.error('Failed to copy URL:', err);
}
};
const handleDisconnect = async () => {
if (!originRemote) return;
try {
const dir = `${projectsPath}/${projectId}`;
await git.deleteRemote({
dir,
remote: 'origin',
});
queryClient.invalidateQueries({ queryKey: ['git-status', projectId] });
} catch (err) {
const message = err instanceof Error ? err.message : 'Failed to disconnect';
setError(message);
}
};
const handleOpenExternal = async () => {
if (!originRemote) return;
try {
let externalUrl: string;
if (originRemote.url.startsWith('https://')) {
// For HTTPS URLs, open directly
externalUrl = originRemote.url;
} else if (originRemote.url.startsWith('nostr://')) {
// For Nostr URLs, parse and generate URL using the configured template
const nostrUri = await NostrURI.parse(originRemote.url);
externalUrl = ngitWebUrl(config.ngitWebUrl, nostrUri);
} else {
// Unsupported URL type
return;
}
window.open(externalUrl, '_blank', 'noopener,noreferrer');
} catch (err) {
console.error('Failed to open external URL:', err);
}
};
const getProviderInfo = () => {
if (!originRemote) return null;
// Check if it's a Nostr URI
if (originRemote.url.startsWith('nostr://')) {
return {
name: 'Nostr Git',
icon: <Zap className="h-4 w-4" />,
};
}
// Check if we have a matched credential
if (matchedCredential) {
return {
name: matchedCredential.name,
icon: (
<ExternalFavicon
url={matchedCredential.origin}
size={16}
fallback={<GitBranch className="h-4 w-4" />}
/>
),
};
}
// Fallback to generic Git
return {
name: 'Git',
icon: <GitBranch className="h-4 w-4" />,
};
};
const providerInfo = getProviderInfo();
if (!originRemote) {
return null;
}
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
{providerInfo?.icon}
<h3 className="font-semibold">{providerInfo?.name}</h3>
</div>
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={handleOpenExternal}
>
<ExternalLink className="h-4 w-4" />
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="h-8 w-8">
<EllipsisVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={handleDisconnect} className="text-destructive">
<CloudOff className="h-4 w-4 mr-2" />
Disconnect
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
<div className="space-y-2">
<Label className="text-xs text-muted-foreground">Repository URL</Label>
<div className="flex gap-2">
<Input
value={originRemote.url}
readOnly
className="flex-1 text-sm"
/>
<Button
size="sm"
variant="outline"
onClick={handleCopyUrl}
className="shrink-0 h-10"
>
{copiedUrl ? (
<Check className="h-4 w-4" />
) : (
<Copy className="h-4 w-4" />
)}
</Button>
</div>
</div>
{error && (
<Alert variant="destructive">
<AlertDescription className="text-sm">{error}</AlertDescription>
</Alert>
)}
<Button
onClick={handleSync}
disabled={isSyncing}
className="w-full"
>
<div className="flex items-center gap-2">
{syncSuccess
? <Check className="h-4 w-4" />
: <RefreshCw className={cn("size-4", { "animate-spin": isSyncing })} />}
<span>Sync</span>
</div>
</Button>
</div>
);
}
-32
View File
@@ -1,32 +0,0 @@
import type { GitCredential } from '@/contexts/GitSettingsContext';
import type { ReactNode } from 'react';
export interface ProviderOption {
id: string;
name: string;
origin?: string;
icon: ReactNode;
credential?: GitCredential;
}
export type StepType =
| 'select-provider'
| 'configure-repo'
| 'sync'
| 'init-success';
export interface StepProps {
projectId: string;
onChangeStep: (step: StepType) => void;
onClose: () => void;
}
export interface SelectProviderStepProps extends StepProps {
onSelectProvider: (provider: ProviderOption) => void;
}
export interface ConfigureRepoStepProps extends StepProps {
selectedProvider: ProviderOption;
onBack: () => void;
onSuccess: () => void;
}
@@ -0,0 +1,124 @@
import { describe, it, expect } from 'vitest';
describe('AnnounceRepositoryDialog - NIP-34 Tag Structure', () => {
it('should create tags with multiple values in single tag per NIP-34', () => {
// Test the tag structure that would be created
const webUrls = ['https://example.com/browse', 'https://mirror.example.com'];
const cloneUrls = [
'https://git.shakespeare.diy/npub1.../repo.git',
'https://relay.ngit.dev/npub1.../repo.git',
];
const relays = ['wss://git.shakespeare.diy', 'wss://relay.ngit.dev'];
const tags: string[][] = [['d', 'test-repo']];
// Simulate the tag creation logic from AnnounceRepositoryDialog
if (webUrls.length > 0) {
const trimmedUrls = webUrls.map((url) => url.trim()).filter((url) => url);
if (trimmedUrls.length > 0) {
tags.push(['web', ...trimmedUrls]);
}
}
if (cloneUrls.length > 0) {
const trimmedUrls = cloneUrls.map((url) => url.trim()).filter((url) => url);
if (trimmedUrls.length > 0) {
tags.push(['clone', ...trimmedUrls]);
}
}
if (relays.length > 0) {
const trimmedRelays = relays.map((relay) => relay.trim()).filter((relay) => relay);
if (trimmedRelays.length > 0) {
tags.push(['relays', ...trimmedRelays]);
}
}
// Verify the structure matches NIP-34 spec
expect(tags).toEqual([
['d', 'test-repo'],
['web', 'https://example.com/browse', 'https://mirror.example.com'],
[
'clone',
'https://git.shakespeare.diy/npub1.../repo.git',
'https://relay.ngit.dev/npub1.../repo.git',
],
['relays', 'wss://git.shakespeare.diy', 'wss://relay.ngit.dev'],
]);
// Verify we have single tags with multiple values, not multiple tags
const cloneTags = tags.filter((t) => t[0] === 'clone');
expect(cloneTags.length).toBe(1);
expect(cloneTags[0].length).toBe(3); // ['clone', url1, url2]
const relayTags = tags.filter((t) => t[0] === 'relays');
expect(relayTags.length).toBe(1);
expect(relayTags[0].length).toBe(3); // ['relays', relay1, relay2]
});
it('should handle reading relays from single tag with multiple values', () => {
// Simulate the event structure from Nostr
const repoEvent = {
tags: [
['d', 'hello-shakespeare'],
[
'clone',
'https://git.shakespeare.diy/npub1.../hello-shakespeare.git',
'https://relay.ngit.dev/npub1.../hello-shakespeare.git',
],
['relays', 'wss://git.shakespeare.diy', 'wss://relay.ngit.dev'],
],
};
// Simulate the reading logic from PullRequestDialog
const relayTag = repoEvent.tags.find((t: string[]) => t[0] === 'relays');
let publishRelays: string[] = [];
if (relayTag && relayTag.length > 1) {
publishRelays = relayTag.slice(1);
}
// Verify we extracted all relay URLs correctly
expect(publishRelays).toEqual(['wss://git.shakespeare.diy', 'wss://relay.ngit.dev']);
});
it('should handle reading clone URLs from single tag with multiple values', () => {
const repoEvent = {
tags: [
['d', 'hello-shakespeare'],
[
'clone',
'https://git.shakespeare.diy/npub1.../hello-shakespeare.git',
'https://relay.ngit.dev/npub1.../hello-shakespeare.git',
],
],
};
const cloneTag = repoEvent.tags.find((t: string[]) => t[0] === 'clone');
let cloneUrls: string[] = [];
if (cloneTag && cloneTag.length > 1) {
cloneUrls = cloneTag.slice(1);
}
expect(cloneUrls).toEqual([
'https://git.shakespeare.diy/npub1.../hello-shakespeare.git',
'https://relay.ngit.dev/npub1.../hello-shakespeare.git',
]);
});
it('should handle reading maintainers from single tag with multiple values', () => {
const repoEvent = {
tags: [
['d', 'hello-shakespeare'],
['maintainers', 'pubkey1', 'pubkey2', 'pubkey3'],
],
};
// Simulate the reading logic from NostrGitProvider
const maintainerTag = repoEvent.tags.find((t: string[]) => t[0] === 'maintainers');
const maintainers = maintainerTag ? maintainerTag.slice(1) : [];
expect(maintainers).toEqual(['pubkey1', 'pubkey2', 'pubkey3']);
});
});
@@ -0,0 +1,738 @@
import { useState, useEffect, useCallback } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { TagInput } from '@/components/ui/tag-input';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog';
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from '@/components/ui/collapsible';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { ScrollArea } from '@/components/ui/scroll-area';
import {
GitBranch,
Loader2,
AlertCircle,
Plus,
X,
Settings,
ChevronDown,
} from 'lucide-react';
import { useGit } from '@/hooks/useGit';
import { useFSPaths } from '@/hooks/useFSPaths';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostr } from '@/hooks/useNostr';
import { useToast } from '@/hooks/useToast';
import { useAppContext } from '@/hooks/useAppContext';
import { useFS } from '@/hooks/useFS';
import { DotAI } from '@/lib/DotAI';
import { nip19 } from 'nostr-tools';
import {
createRepositoryAnnouncementEvent,
createRepositoryNaddr,
validateRepositoryAnnouncementData,
validateRepositoryId,
parseRepositoryAnnouncement,
} from '@/lib/announceRepository';
export interface AnnounceRepositoryResult {
repoId: string;
cloneUrls: string[];
relays: string[];
naddr: string;
}
interface AnnounceRepositoryDialogProps {
projectId: string;
open?: boolean;
onOpenChange?: (open: boolean) => void;
onSuccess?: (result: AnnounceRepositoryResult) => void;
/** Repository naddr to edit (if editing existing repo) */
editNaddr?: string;
}
export function AnnounceRepositoryDialog({
projectId,
open,
onOpenChange,
onSuccess,
editNaddr,
}: AnnounceRepositoryDialogProps) {
const [isOpen, setIsOpen] = useState(open ?? false);
const [isPrepopulated, setIsPrepopulated] = useState(false);
const [repoId, setRepoId] = useState('');
const [repoIdError, setRepoIdError] = useState<string | null>(null);
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [showAdvanced, setShowAdvanced] = useState(false);
const [webUrls, setWebUrls] = useState<string[]>([]);
const [cloneUrls, setCloneUrls] = useState<string[]>([]);
const [relays, setRelays] = useState<string[]>([]);
const [tTags, setTTags] = useState<string[]>([]);
const [earliestCommit, setEarliestCommit] = useState('');
const [isCreating, setIsCreating] = useState(false);
const [error, setError] = useState<string | null>(null);
const [newWebUrl, setNewWebUrl] = useState('');
const [newCloneUrl, setNewCloneUrl] = useState('');
const [newRelay, setNewRelay] = useState('');
const { git } = useGit();
const { projectsPath } = useFSPaths();
const { user } = useCurrentUser();
const { nostr } = useNostr();
const { toast } = useToast();
const { config } = useAppContext();
const { fs } = useFS();
const projectPath = `${projectsPath}/${projectId}`;
useEffect(() => {
if (open !== undefined) {
setIsOpen(open);
}
}, [open]);
// Convert projectId to kebab-case for repo ID
const toKebabCase = (str: string): string => {
return str
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
};
// Validate repository ID on change
const handleRepoIdChange = (value: string) => {
setRepoId(value);
try {
validateRepositoryId(value);
setRepoIdError(null);
} catch (err) {
setRepoIdError(err instanceof Error ? err.message : 'Invalid repository ID');
}
};
const getEarliestCommit = useCallback(async () => {
try {
const commits = await git.log({
dir: projectPath,
ref: 'HEAD',
});
if (commits.length > 0) {
// Get the earliest commit (last in the log)
const earliest = commits[commits.length - 1];
setEarliestCommit(earliest.oid);
}
} catch (err) {
console.warn('Failed to get earliest commit:', err);
}
}, [git, projectPath]);
const prepopulateFields = useCallback(async () => {
// Set default repo ID from project ID (kebab-case)
const defaultRepoId = toKebabCase(projectId);
setRepoId(defaultRepoId);
// Set default name from project ID (title case)
const defaultName = projectId
.split(/[-_]/)
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
setName(defaultName);
// Prepopulate clone URLs and relays from ngitServers (matching original handlePushToNostr)
if (user?.pubkey && config.ngitServers && config.ngitServers.length > 0) {
// Clone URLs: https://{server}/{npub}/{repo-id}.git
const npub = nip19.npubEncode(user.pubkey);
const cloneUrls = config.ngitServers.map(server =>
`https://${server}/${npub}/${defaultRepoId}.git`
);
setCloneUrls(cloneUrls);
// Relay URLs: wss://{server}
const relayUrls = config.ngitServers.map(server => `wss://${server}`);
setRelays(relayUrls);
} else {
// Fallback to write relays if no ngitServers configured
const writeRelays = config.relayMetadata.relays
.filter(r => r.write)
.map(r => r.url);
setRelays(writeRelays.length > 0 ? writeRelays : ['wss://relay.nostr.band']);
}
// Prepopulate t-tags
const defaultTTags: string[] = ['shakespeare'];
// Try to read template.json to get template name
try {
const dotAI = new DotAI(fs, projectPath);
const template = await dotAI.readTemplate();
if (template?.name) {
// Convert template name to lowercase and add as t-tag
const templateTag = template.name.toLowerCase();
if (!defaultTTags.includes(templateTag)) {
defaultTTags.push(templateTag);
}
}
} catch (error) {
console.warn('Failed to read template for t-tags:', error);
}
setTTags(defaultTTags);
// Get earliest commit
await getEarliestCommit();
}, [projectId, projectPath, fs, config.relayMetadata, config.ngitServers, user?.pubkey, getEarliestCommit]);
// Load existing repository data if editing, or prepopulate fields for new repos
useEffect(() => {
// Only run when dialog opens
if (!isOpen || isPrepopulated) return;
const loadExistingRepo = async () => {
if (!editNaddr) return;
try {
// Decode the naddr to get repository coordinates
const decoded = nip19.decode(editNaddr);
if (decoded.type !== 'naddr') {
throw new Error('Invalid repository identifier');
}
const { identifier, pubkey, kind, relays: naddrRelays } = decoded.data;
// Query for the repository announcement event
const filter = {
kinds: [kind],
authors: [pubkey],
'#d': [identifier],
};
const signal = AbortSignal.timeout(3000);
const readRelays = config.relayMetadata.relays
.filter(r => r.read)
.map(r => r.url);
const events = await nostr.query([filter], {
signal,
relays: naddrRelays && naddrRelays.length > 0 ? naddrRelays : readRelays
});
if (events.length === 0) {
throw new Error('Repository announcement not found');
}
// Use the most recent event
const event = events.sort((a, b) => b.created_at - a.created_at)[0];
// Parse the NIP-34 repository announcement
const parsed = parseRepositoryAnnouncement(event);
setRepoId(parsed.identifier);
setName(parsed.name || '');
setDescription(parsed.description || '');
setWebUrls(parsed.webUrls);
setCloneUrls(parsed.httpsCloneUrls);
setRelays(parsed.relays);
setEarliestCommit(parsed.earliestCommit || '');
// Extract t-tags from the event
const extractedTTags = parsed.event.tags
.filter(([name]) => name === 't')
.map(([, value]) => value)
.filter((value): value is string => !!value);
setTTags(extractedTTags);
setIsPrepopulated(true);
} catch (error) {
console.error('Failed to load repository data:', error);
toast({
title: 'Failed to load repository',
description: error instanceof Error ? error.message : 'Unknown error',
variant: 'destructive',
});
}
};
if (editNaddr) {
loadExistingRepo();
} else {
prepopulateFields();
setIsPrepopulated(true);
}
}, [isOpen, isPrepopulated, editNaddr, nostr, config.relayMetadata, toast, prepopulateFields]);
const addWebUrl = () => {
if (newWebUrl.trim() && !webUrls.includes(newWebUrl.trim())) {
setWebUrls([...webUrls, newWebUrl.trim()]);
setNewWebUrl('');
}
};
const removeWebUrl = (index: number) => {
setWebUrls(webUrls.filter((_, i) => i !== index));
};
const addCloneUrl = () => {
const trimmedUrl = newCloneUrl.trim();
// Prevent nostr:// URLs in clone URLs
if (trimmedUrl.startsWith('nostr://')) {
toast({
title: 'Invalid clone URL',
description: 'Clone URLs must be HTTPS URLs, not nostr:// URLs',
variant: 'destructive',
});
return;
}
if (trimmedUrl && !cloneUrls.includes(trimmedUrl)) {
setCloneUrls([...cloneUrls, trimmedUrl]);
setNewCloneUrl('');
}
};
const removeCloneUrl = (index: number) => {
setCloneUrls(cloneUrls.filter((_, i) => i !== index));
};
const addRelay = () => {
if (newRelay.trim() && !relays.includes(newRelay.trim())) {
setRelays([...relays, newRelay.trim()]);
setNewRelay('');
}
};
const removeRelay = (index: number) => {
setRelays(relays.filter((_, i) => i !== index));
};
const announceRepository = async () => {
if (!user || !user.signer) {
toast({
title: 'Authentication required',
description: 'Please log in with Nostr to announce repositories',
variant: 'destructive',
});
return;
}
setIsCreating(true);
setError(null);
try {
// Validate data
validateRepositoryAnnouncementData({
repoId,
cloneUrls,
});
// Create repository announcement event using shared utility
const repoEvent = createRepositoryAnnouncementEvent({
repoId,
name,
description,
webUrls,
cloneUrls,
relays,
tTags,
earliestCommit,
});
console.log('=== ANNOUNCING REPOSITORY ===');
console.log('Repository ID:', repoId.trim());
console.log('Owner pubkey:', user.pubkey);
console.log('Creating repository announcement event:', repoEvent);
// Sign the event
const signedEvent = await user.signer.signEvent(repoEvent);
console.log('Signed repository announcement:', signedEvent);
console.log('Event coordinate:', `30617:${user.pubkey}:${repoId.trim()}`);
// Publish to Nostr relays
// Repository announcements go to: write relays + relays specified in the announcement
const writeRelays = config.relayMetadata.relays
.filter(r => r.write)
.map(r => r.url);
const publishRelays = [...new Set([...writeRelays, ...relays])];
console.log('Publishing repository announcement to relays:', publishRelays);
await nostr.event(signedEvent, { relays: publishRelays });
console.log('Published repository announcement to Nostr relays');
console.log('To verify: Query for kind 30617 with authors=[' + user.pubkey + '] and #d=[' + repoId.trim() + ']');
// Create naddr for the repository using shared utility
const naddr = createRepositoryNaddr(repoId, user.pubkey, relays);
toast({
title: 'Published Nostr announcement',
description: 'Configuring repository...',
});
// Close the dialog
handleOpenChange(false);
// Call success callback with the data needed for Git operations
onSuccess?.({
repoId: repoId.trim(),
cloneUrls,
relays,
naddr,
});
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error';
setError(errorMessage);
toast({
title: 'Failed to announce repository',
description: errorMessage,
variant: 'destructive',
duration: Infinity,
});
} finally {
setIsCreating(false);
}
};
const handleOpenChange = (newOpen: boolean) => {
setIsOpen(newOpen);
onOpenChange?.(newOpen);
// Reset form when closing
if (!newOpen) {
setIsPrepopulated(false);
setRepoId('');
setName('');
setDescription('');
setWebUrls([]);
setCloneUrls([]);
setRelays(['wss://relay.nostr.band']);
setTTags([]);
setEarliestCommit('');
setError(null);
setNewWebUrl('');
setNewCloneUrl('');
setNewRelay('');
}
};
return (
<Dialog open={isOpen} onOpenChange={handleOpenChange}>
<DialogContent className="max-w-2xl max-h-[90vh]">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Settings className="h-5 w-5" />
{editNaddr ? 'Edit' : ''} Nostr Repository Settings
</DialogTitle>
<DialogDescription>
{editNaddr
? 'Update your repository announcement (NIP-34) for Nostr git clients'
: 'Configure your repository announcement (NIP-34) for Nostr git clients'
}
</DialogDescription>
</DialogHeader>
<ScrollArea className="max-h-[60vh]">
<div className="space-y-6 p-1 pr-4">
{/* Error alert */}
{error && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{/* Repository ID */}
<div className="space-y-2">
<Label htmlFor="repo-id">Repository ID *</Label>
<Input
id="repo-id"
placeholder="e.g., my-project"
value={repoId}
onChange={(e) => handleRepoIdChange(e.target.value)}
disabled={isCreating}
className={repoIdError ? 'border-destructive' : ''}
/>
{repoIdError ? (
<p className="text-xs text-destructive">{repoIdError}</p>
) : (
<p className="text-xs text-muted-foreground">
Kebab-case short name (e.g., "my-project", "awesome-app")
</p>
)}
</div>
{/* Name */}
<div className="space-y-2">
<Label htmlFor="repo-name">Name</Label>
<Input
id="repo-name"
placeholder="Human-readable project name"
value={name}
onChange={(e) => setName(e.target.value)}
disabled={isCreating}
/>
<p className="text-xs text-muted-foreground">
Display name for your repository
</p>
</div>
{/* Description */}
<div className="space-y-2">
<Label htmlFor="repo-description">Description</Label>
<Textarea
id="repo-description"
placeholder="Brief description of your project"
value={description}
onChange={(e) => setDescription(e.target.value)}
rows={3}
disabled={isCreating}
/>
</div>
{/* Advanced Settings */}
<Collapsible open={showAdvanced} onOpenChange={setShowAdvanced}>
<CollapsibleTrigger asChild>
<Button
variant="ghost"
className="w-full justify-between p-0 hover:bg-transparent"
>
<span className="text-sm font-medium">Advanced Settings</span>
<ChevronDown
className={`h-4 w-4 transition-transform ${
showAdvanced ? 'rotate-180' : ''
}`}
/>
</Button>
</CollapsibleTrigger>
<CollapsibleContent className="space-y-6 pt-4">
{/* Web URLs */}
<div className="space-y-2">
<Label>Web URLs (Optional)</Label>
<div className="space-y-2">
{webUrls.map((url, index) => (
<div key={index} className="flex gap-2">
<Input
value={url}
onChange={(e) => {
const newUrls = [...webUrls];
newUrls[index] = e.target.value;
setWebUrls(newUrls);
}}
className="flex-1"
disabled={isCreating}
/>
<Button
variant="outline"
size="icon"
onClick={() => removeWebUrl(index)}
disabled={isCreating}
>
<X className="h-4 w-4" />
</Button>
</div>
))}
<div className="flex gap-2">
<Input
placeholder="https://example.com/browse"
value={newWebUrl}
onChange={(e) => setNewWebUrl(e.target.value)}
onKeyDown={(e) =>
e.key === 'Enter' && (e.preventDefault(), addWebUrl())
}
disabled={isCreating}
/>
<Button
variant="outline"
size="icon"
onClick={addWebUrl}
disabled={isCreating}
>
<Plus className="h-4 w-4" />
</Button>
</div>
</div>
<p className="text-xs text-muted-foreground">
URLs where the repository can be browsed online
</p>
</div>
{/* Clone URLs */}
<div className="space-y-2">
<Label>Git Server Clone URLs</Label>
<div className="space-y-2">
{cloneUrls.map((url, index) => (
<div key={index} className="flex gap-2">
<Input
value={url}
onChange={(e) => {
const newUrls = [...cloneUrls];
newUrls[index] = e.target.value;
setCloneUrls(newUrls);
}}
className="flex-1 font-mono text-sm"
disabled={isCreating}
/>
<Button
variant="outline"
size="icon"
onClick={() => removeCloneUrl(index)}
disabled={isCreating}
>
<X className="h-4 w-4" />
</Button>
</div>
))}
<div className="flex gap-2">
<Input
placeholder="https://gitnostr.com/..."
value={newCloneUrl}
onChange={(e) => setNewCloneUrl(e.target.value)}
onKeyDown={(e) =>
e.key === 'Enter' && (e.preventDefault(), addCloneUrl())
}
disabled={isCreating}
className="font-mono text-sm"
/>
<Button
variant="outline"
size="icon"
onClick={addCloneUrl}
disabled={isCreating}
>
<Plus className="h-4 w-4" />
</Button>
</div>
</div>
<p className="text-xs text-muted-foreground">
HTTPS URLs for cloning the repository (nostr:// URLs not allowed)
</p>
</div>
{/* Relays */}
<div className="space-y-2">
<Label>Git Nostr Relays</Label>
<div className="space-y-2">
{relays.map((relay, index) => (
<div key={index} className="flex gap-2">
<Input
value={relay}
onChange={(e) => {
const newRelays = [...relays];
newRelays[index] = e.target.value;
setRelays(newRelays);
}}
className="flex-1 font-mono text-sm"
disabled={isCreating}
/>
<Button
variant="outline"
size="icon"
onClick={() => removeRelay(index)}
disabled={isCreating || relays.length === 1}
>
<X className="h-4 w-4" />
</Button>
</div>
))}
<div className="flex gap-2">
<Input
placeholder="wss://relay.example.com"
value={newRelay}
onChange={(e) => setNewRelay(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && (e.preventDefault(), addRelay())}
disabled={isCreating}
className="font-mono text-sm"
/>
<Button
variant="outline"
size="icon"
onClick={addRelay}
disabled={isCreating}
>
<Plus className="h-4 w-4" />
</Button>
</div>
</div>
<p className="text-xs text-muted-foreground">
Nostr relays where patches and issues will be published and monitored
</p>
</div>
{/* Category Tags (t-tags) */}
<div className="space-y-2">
<Label htmlFor="category-tags">Category Tags</Label>
<TagInput
id="category-tags"
value={tTags}
onChange={setTTags}
placeholder="e.g., nostr, social, web"
disabled={isCreating}
transformTag={(tag) => tag.trim().toLowerCase()}
allowDuplicates={false}
/>
<p className="text-xs text-muted-foreground">
Tags for categorizing your repository. Press space or comma to add a tag.
</p>
</div>
{/* Earliest Commit */}
<div className="space-y-2">
<Label htmlFor="earliest-commit">Earliest Unique Commit</Label>
<Input
id="earliest-commit"
placeholder="Commit hash"
value={earliestCommit}
onChange={(e) => setEarliestCommit(e.target.value)}
disabled={isCreating}
className="font-mono text-sm"
/>
<p className="text-xs text-muted-foreground">
The root commit of your repository (auto-detected)
</p>
</div>
</CollapsibleContent>
</Collapsible>
</div>
</ScrollArea>
<DialogFooter>
<Button
variant="outline"
onClick={() => handleOpenChange(false)}
disabled={isCreating}
>
Cancel
</Button>
<Button
onClick={announceRepository}
disabled={isCreating || !!repoIdError || !repoId.trim()}
>
{isCreating ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
{editNaddr ? 'Updating...' : 'Publishing...'}
</>
) : (
<>
<GitBranch className="h-4 w-4 mr-2" />
{editNaddr ? 'Update on Nostr' : 'Publish to Nostr'}
</>
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
+522
View File
@@ -0,0 +1,522 @@
import { useState, useEffect, useCallback } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Badge } from '@/components/ui/badge';
import {
GitBranch,
Plus,
Trash2,
Check,
Loader2,
ArrowUpRight,
} from 'lucide-react';
import { useGit } from '@/hooks/useGit';
import { useFSPaths } from '@/hooks/useFSPaths';
import { useToast } from '@/hooks/useToast';
import { cn } from '@/lib/utils';
interface BranchInfo {
name: string;
isCurrent: boolean;
isRemote: boolean;
remoteName?: string;
commitId?: string;
ahead?: number;
behind?: number;
}
interface BranchManagerProps {
projectId: string;
currentBranch: string | null;
onBranchChange?: () => void;
}
export function BranchManager({ projectId, currentBranch, onBranchChange }: BranchManagerProps) {
const [branches, setBranches] = useState<BranchInfo[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [newBranchName, setNewBranchName] = useState('');
const [isCreating, setIsCreating] = useState(false);
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
const [deletingBranch, setDeletingBranch] = useState<string | null>(null);
const [switchingToBranch, setSwitchingToBranch] = useState<string | null>(null);
const { git } = useGit();
const { projectsPath } = useFSPaths();
const { toast } = useToast();
const projectPath = `${projectsPath}/${projectId}`;
const loadBranches = useCallback(async () => {
setIsLoading(true);
try {
// Get local branches
const localBranches = await git.listBranches({
dir: projectPath,
});
// Get remote branches
let remoteBranches: string[] = [];
try {
remoteBranches = await git.listBranches({
dir: projectPath,
remote: 'origin',
});
} catch {
// No remote or error fetching remote branches
}
// Get current branch
const current = await git.currentBranch({ dir: projectPath }).catch(() => null);
// Build branch info
const branchInfos: BranchInfo[] = [];
// Add local branches
for (const branch of localBranches) {
const isCurrent = branch === current;
let commitId: string | undefined;
try {
commitId = await git.resolveRef({
dir: projectPath,
ref: `refs/heads/${branch}`,
});
} catch {
// Skip branches we can't resolve
}
branchInfos.push({
name: branch,
isCurrent,
isRemote: false,
commitId,
});
}
// Add remote branches
for (const branch of remoteBranches) {
// Skip if we already have this as a local branch
if (localBranches.includes(branch)) continue;
let commitId: string | undefined;
try {
commitId = await git.resolveRef({
dir: projectPath,
ref: `refs/remotes/origin/${branch}`,
});
} catch {
// Skip branches we can't resolve
}
branchInfos.push({
name: branch,
isCurrent: false,
isRemote: true,
remoteName: 'origin',
commitId,
});
}
setBranches(branchInfos);
} catch (error) {
console.error('Failed to load branches:', error);
toast({
title: 'Failed to load branches',
description: error instanceof Error ? error.message : 'Unknown error',
variant: 'destructive',
});
} finally {
setIsLoading(false);
}
}, [git, projectPath, toast]);
useEffect(() => {
loadBranches();
}, [projectId, currentBranch, loadBranches]);
const handleCreateBranch = async () => {
if (!newBranchName.trim()) {
toast({
title: 'Invalid branch name',
description: 'Please enter a branch name',
variant: 'destructive',
});
return;
}
// Validate branch name
const invalidChars = /[~^: \\?*[\]]/;
if (invalidChars.test(newBranchName)) {
toast({
title: 'Invalid branch name',
description: 'Branch name contains invalid characters',
variant: 'destructive',
});
return;
}
setIsCreating(true);
try {
// Get current HEAD to base the new branch on
const currentRef = await git.resolveRef({
dir: projectPath,
ref: 'HEAD',
});
// Create the new branch
await git.branch({
dir: projectPath,
ref: newBranchName.trim(),
object: currentRef,
});
// Automatically check out the new branch
await git.checkout({
dir: projectPath,
ref: newBranchName.trim(),
force: true,
});
// Close the dialog before showing the toast
setNewBranchName('');
setIsCreateDialogOpen(false);
// Show success toast indicating the branch was created and checked out
toast({
title: 'Branch created and checked out',
description: `Switched to new branch "${newBranchName.trim()}"`,
});
await loadBranches();
onBranchChange?.();
} catch (error) {
toast({
title: 'Failed to create branch',
description: error instanceof Error ? error.message : 'Unknown error',
variant: 'destructive',
});
} finally {
setIsCreating(false);
}
};
const handleSwitchBranch = async (branchName: string) => {
setSwitchingToBranch(branchName);
try {
await git.checkout({
dir: projectPath,
ref: branchName,
});
toast({
title: 'Branch switched',
description: `Switched to branch "${branchName}"`,
});
await loadBranches();
onBranchChange?.();
} catch (error) {
toast({
title: 'Failed to switch branch',
description: error instanceof Error ? error.message : 'Unknown error',
variant: 'destructive',
});
} finally {
setSwitchingToBranch(null);
}
};
const handleDeleteBranch = async (branchName: string) => {
setDeletingBranch(branchName);
try {
await git.deleteBranch({
dir: projectPath,
ref: branchName,
});
toast({
title: 'Branch deleted',
description: `Deleted branch "${branchName}"`,
});
await loadBranches();
onBranchChange?.();
} catch (error) {
toast({
title: 'Failed to delete branch',
description: error instanceof Error ? error.message : 'Unknown error',
variant: 'destructive',
});
} finally {
setDeletingBranch(null);
}
};
const localBranches = branches.filter(b => !b.isRemote);
const remoteBranches = branches.filter(b => b.isRemote);
return (
<div className="space-y-4">
{/* Header with create button */}
<div className="flex items-center justify-between">
<h3 className="text-sm font-medium">Branches</h3>
<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
<DialogTrigger asChild>
<Button variant="outline" size="sm" className="h-8 gap-2">
<Plus className="h-4 w-4" />
New Branch
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Create New Branch</DialogTitle>
<DialogDescription>
Create a new branch from the current HEAD
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="branch-name">Branch Name</Label>
<Input
id="branch-name"
placeholder="feature/my-new-feature"
value={newBranchName}
onChange={(e) => setNewBranchName(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && !isCreating) {
handleCreateBranch();
}
}}
autoFocus
/>
</div>
{currentBranch && (
<div className="text-sm text-muted-foreground">
Creating from: <span className="font-medium">{currentBranch}</span>
</div>
)}
</div>
<div className="flex justify-end gap-2">
<Button
variant="outline"
onClick={() => setIsCreateDialogOpen(false)}
disabled={isCreating}
>
Cancel
</Button>
<Button onClick={handleCreateBranch} disabled={isCreating}>
{isCreating ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Creating...
</>
) : (
<>
<Plus className="h-4 w-4 mr-2" />
Create Branch
</>
)}
</Button>
</div>
</DialogContent>
</Dialog>
</div>
{isLoading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
) : (
<div className="space-y-4">
{/* Local Branches */}
{localBranches.length > 0 && (
<div className="space-y-2">
<div className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
Local Branches
</div>
<div className="space-y-1">
{localBranches.map((branch) => (
<BranchItem
key={branch.name}
branch={branch}
onSwitch={handleSwitchBranch}
onDelete={handleDeleteBranch}
isSwitching={switchingToBranch === branch.name}
isDeleting={deletingBranch === branch.name}
/>
))}
</div>
</div>
)}
{/* Remote Branches */}
{remoteBranches.length > 0 && (
<div className="space-y-2">
<div className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
Remote Branches
</div>
<div className="space-y-1">
{remoteBranches.map((branch) => (
<BranchItem
key={`remote-${branch.name}`}
branch={branch}
onSwitch={handleSwitchBranch}
onDelete={handleDeleteBranch}
isSwitching={switchingToBranch === branch.name}
isDeleting={deletingBranch === branch.name}
/>
))}
</div>
</div>
)}
{/* Empty state */}
{localBranches.length === 0 && remoteBranches.length === 0 && (
<div className="text-center py-8 text-muted-foreground">
<GitBranch className="h-12 w-12 mx-auto mb-2 opacity-50" />
<p className="text-sm">No branches found</p>
</div>
)}
</div>
)}
</div>
);
}
interface BranchItemProps {
branch: BranchInfo;
onSwitch: (name: string) => void;
onDelete: (name: string) => void;
isSwitching: boolean;
isDeleting: boolean;
}
function BranchItem({ branch, onSwitch, onDelete, isSwitching, isDeleting }: BranchItemProps) {
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
return (
<>
<div
className={cn(
'flex items-center gap-3 p-3 rounded-lg border transition-colors group',
branch.isCurrent
? 'bg-primary/5 border-primary/20'
: 'hover:bg-muted/50 border-transparent'
)}
>
{/* Branch icon and name */}
<div className="flex items-center gap-2 flex-1 min-w-0">
{branch.isCurrent ? (
<Check className="h-4 w-4 text-primary shrink-0" />
) : (
<GitBranch className="h-4 w-4 text-muted-foreground shrink-0" />
)}
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span
className={cn(
'font-mono text-sm truncate',
branch.isCurrent && 'font-semibold text-primary'
)}
>
{branch.name}
</span>
{branch.isRemote && (
<ArrowUpRight className="h-3 w-3 text-muted-foreground shrink-0" />
)}
</div>
{branch.commitId && (
<div className="text-xs text-muted-foreground font-mono">
{branch.commitId.substring(0, 7)}
</div>
)}
</div>
</div>
{/* Current badge */}
{branch.isCurrent && (
<Badge variant="secondary" className="shrink-0">
Current
</Badge>
)}
{/* Actions */}
{!branch.isCurrent && !branch.isRemote && (
<div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0">
<Button
variant="ghost"
size="sm"
className="h-8 px-2"
onClick={() => onSwitch(branch.name)}
disabled={isSwitching || isDeleting}
>
{isSwitching ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<>
<GitBranch className="h-4 w-4 mr-1" />
Switch
</>
)}
</Button>
<Button
variant="ghost"
size="sm"
className="h-8 px-2 text-destructive hover:text-destructive hover:bg-destructive/10"
onClick={() => setShowDeleteDialog(true)}
disabled={isSwitching || isDeleting}
>
{isDeleting ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Trash2 className="h-4 w-4" />
)}
</Button>
</div>
)}
</div>
{/* Delete confirmation dialog */}
<AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete Branch</AlertDialogTitle>
<AlertDialogDescription>
Are you sure you want to delete the branch <strong>{branch.name}</strong>?
This action cannot be undone.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={() => {
onDelete(branch.name);
setShowDeleteDialog(false);
}}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
Delete Branch
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
);
}
+352
View File
@@ -0,0 +1,352 @@
import { useState, useEffect, useCallback } from 'react';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { GitCompare, Loader2, GitCommit, FileIcon } from 'lucide-react';
import { useGit } from '@/hooks/useGit';
import { useFSPaths } from '@/hooks/useFSPaths';
import { useToast } from '@/hooks/useToast';
import { DiffViewer } from './DiffViewer';
interface CompareViewProps {
projectId: string;
}
interface CommitInfo {
oid: string;
message: string;
author: string;
timestamp: number;
}
export function CompareView({ projectId }: CompareViewProps) {
const [branches, setBranches] = useState<string[]>([]);
const [commits, setCommits] = useState<CommitInfo[]>([]);
const [baseRef, setBaseRef] = useState<string>('');
const [compareRef, setCompareRef] = useState<string>('');
const [isLoading, setIsLoading] = useState(true);
const [isComparing, setIsComparing] = useState(false);
const [comparisonStats, setComparisonStats] = useState<{
ahead: number;
behind: number;
filesChanged: number;
} | null>(null);
const { git } = useGit();
const { projectsPath } = useFSPaths();
const { toast } = useToast();
const projectPath = `${projectsPath}/${projectId}`;
const loadReferences = useCallback(async () => {
setIsLoading(true);
try {
// Get all branches
const localBranches = await git.listBranches({ dir: projectPath });
setBranches(localBranches);
// Set defaults
const currentBranch = await git.currentBranch({ dir: projectPath }).catch(() => null);
if (currentBranch) {
setCompareRef(currentBranch);
}
// Set base to main/master if available
if (localBranches.includes('main')) {
setBaseRef('main');
} else if (localBranches.includes('master')) {
setBaseRef('master');
} else if (localBranches.length > 0) {
setBaseRef(localBranches[0]);
}
} catch (error) {
console.error('Failed to load references:', error);
toast({
title: 'Failed to load branches',
description: error instanceof Error ? error.message : 'Unknown error',
variant: 'destructive',
});
} finally {
setIsLoading(false);
}
}, [git, projectPath, toast]);
const performComparison = useCallback(async () => {
if (!baseRef || !compareRef) return;
setIsComparing(true);
try {
// Get commits in compareRef that are not in baseRef
const baseCommits = await git.log({ dir: projectPath, ref: baseRef, depth: 100 });
const compareCommits = await git.log({ dir: projectPath, ref: compareRef, depth: 100 });
const baseCommitIds = new Set(baseCommits.map(c => c.oid));
const compareCommitIds = new Set(compareCommits.map(c => c.oid));
// Commits ahead (in compare but not in base)
const aheadCommits = compareCommits.filter(c => !baseCommitIds.has(c.oid));
// Commits behind (in base but not in compare)
const behindCommits = baseCommits.filter(c => !compareCommitIds.has(c.oid));
// Get list of changed files
const baseFiles = await git.listFiles({ dir: projectPath, ref: baseRef });
const compareFiles = await git.listFiles({ dir: projectPath, ref: compareRef });
const changedFiles = new Set<string>();
// Check files in compare ref
for (const file of compareFiles) {
try {
const baseBlob = await git.readBlob({ dir: projectPath, oid: baseRef, filepath: file });
const compareBlob = await git.readBlob({ dir: projectPath, oid: compareRef, filepath: file });
if (Buffer.from(baseBlob.blob).toString() !== Buffer.from(compareBlob.blob).toString()) {
changedFiles.add(file);
}
} catch {
// File exists in one but not the other
changedFiles.add(file);
}
}
// Check for deleted files
for (const file of baseFiles) {
if (!compareFiles.includes(file)) {
changedFiles.add(file);
}
}
setComparisonStats({
ahead: aheadCommits.length,
behind: behindCommits.length,
filesChanged: changedFiles.size,
});
// Set commit info for display
const commitInfos: CommitInfo[] = aheadCommits.map(c => ({
oid: c.oid,
message: c.commit.message,
author: c.commit.author.name,
timestamp: c.commit.author.timestamp,
}));
setCommits(commitInfos);
} catch (error) {
console.error('Failed to compare:', error);
toast({
title: 'Comparison failed',
description: error instanceof Error ? error.message : 'Unknown error',
variant: 'destructive',
});
} finally {
setIsComparing(false);
}
}, [baseRef, compareRef, git, projectPath, toast]);
useEffect(() => {
loadReferences();
}, [projectId, loadReferences]);
useEffect(() => {
if (baseRef && compareRef && baseRef !== compareRef) {
performComparison();
}
}, [baseRef, compareRef, performComparison]);
const formatDate = (timestamp: number) => {
const date = new Date(timestamp * 1000);
const now = new Date();
const diffMs = now.getTime() - date.getTime();
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
if (diffDays === 0) {
return 'today';
} else if (diffDays === 1) {
return 'yesterday';
} else if (diffDays < 7) {
return `${diffDays} days ago`;
} else {
return date.toLocaleDateString();
}
};
if (isLoading) {
return (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
);
}
return (
<div className="space-y-6">
{/* Comparison selectors */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<GitCompare className="h-5 w-5" />
Compare Branches
</CardTitle>
<CardDescription>
Select two branches to compare changes
</CardDescription>
</CardHeader>
<CardContent>
<div className="flex items-center gap-4">
<div className="flex-1">
<label className="text-sm font-medium mb-2 block">Base Branch</label>
<Select value={baseRef} onValueChange={setBaseRef}>
<SelectTrigger>
<SelectValue placeholder="Select base branch" />
</SelectTrigger>
<SelectContent>
{branches.map((branch) => (
<SelectItem key={branch} value={branch}>
{branch}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="pt-6">
<GitCompare className="h-5 w-5 text-muted-foreground" />
</div>
<div className="flex-1">
<label className="text-sm font-medium mb-2 block">Compare Branch</label>
<Select value={compareRef} onValueChange={setCompareRef}>
<SelectTrigger>
<SelectValue placeholder="Select compare branch" />
</SelectTrigger>
<SelectContent>
{branches.map((branch) => (
<SelectItem key={branch} value={branch}>
{branch}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
{/* Comparison stats */}
{comparisonStats && !isComparing && (
<div className="mt-6 grid grid-cols-3 gap-4">
<div className="bg-muted/30 rounded-lg p-4 text-center">
<div className="text-2xl font-bold text-green-600">
{comparisonStats.ahead}
</div>
<div className="text-sm text-muted-foreground mt-1">
Commits Ahead
</div>
</div>
<div className="bg-muted/30 rounded-lg p-4 text-center">
<div className="text-2xl font-bold text-orange-600">
{comparisonStats.behind}
</div>
<div className="text-sm text-muted-foreground mt-1">
Commits Behind
</div>
</div>
<div className="bg-muted/30 rounded-lg p-4 text-center">
<div className="text-2xl font-bold text-blue-600">
{comparisonStats.filesChanged}
</div>
<div className="text-sm text-muted-foreground mt-1">
Files Changed
</div>
</div>
</div>
)}
{isComparing && (
<div className="mt-6 flex items-center justify-center py-8">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground mr-2" />
<span className="text-muted-foreground">Comparing branches...</span>
</div>
)}
</CardContent>
</Card>
{/* Comparison results */}
{baseRef && compareRef && baseRef !== compareRef && !isComparing && (
<Tabs defaultValue="commits" className="w-full">
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="commits" className="gap-2">
<GitCommit className="h-4 w-4" />
Commits ({commits.length})
</TabsTrigger>
<TabsTrigger value="files" className="gap-2">
<FileIcon className="h-4 w-4" />
Files ({comparisonStats?.filesChanged || 0})
</TabsTrigger>
</TabsList>
{/* Commits tab */}
<TabsContent value="commits" className="mt-6">
{commits.length > 0 ? (
<Card>
<CardHeader>
<CardTitle className="text-base">
Commits in {compareRef} not in {baseRef}
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
{commits.map((commit) => (
<div
key={commit.oid}
className="flex items-start gap-3 p-3 rounded-lg border hover:bg-muted/50 transition-colors"
>
<GitCommit className="h-5 w-5 text-muted-foreground shrink-0 mt-0.5" />
<div className="flex-1 min-w-0">
<p className="font-medium text-sm">
{commit.message.split('\n')[0]}
</p>
<div className="flex items-center gap-3 mt-1 text-xs text-muted-foreground">
<span>{commit.author}</span>
<span>•</span>
<span>{formatDate(commit.timestamp)}</span>
<span>•</span>
<span className="font-mono">{commit.oid.substring(0, 7)}</span>
</div>
</div>
</div>
))}
</CardContent>
</Card>
) : (
<Card>
<CardContent className="py-12 text-center">
<GitCommit className="h-12 w-12 mx-auto mb-4 text-muted-foreground opacity-50" />
<p className="text-muted-foreground">
No commits difference between branches
</p>
</CardContent>
</Card>
)}
</TabsContent>
{/* Files tab */}
<TabsContent value="files" className="mt-6">
<Card>
<CardContent className="p-0">
<DiffViewer
projectId={projectId}
compareFrom={baseRef}
compareTo={compareRef}
/>
</CardContent>
</Card>
</TabsContent>
</Tabs>
)}
</div>
);
}
+558
View File
@@ -0,0 +1,558 @@
import { useState, useEffect, useCallback } from 'react';
import { Button } from '@/components/ui/button';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
FileIcon,
Plus,
Minus,
Edit,
Loader2,
SplitSquareHorizontal,
ListTree,
Copy,
Check,
} from 'lucide-react';
import { useGit } from '@/hooks/useGit';
import { useFSPaths } from '@/hooks/useFSPaths';
import { useFS } from '@/hooks/useFS';
import { useToast } from '@/hooks/useToast';
import { cn } from '@/lib/utils';
interface DiffHunk {
oldStart: number;
oldLines: number;
newStart: number;
newLines: number;
lines: DiffLine[];
}
interface DiffLine {
type: 'add' | 'delete' | 'context';
content: string;
oldLineNumber?: number;
newLineNumber?: number;
}
interface FileDiff {
filepath: string;
status: 'modified' | 'added' | 'deleted';
hunks: DiffHunk[];
oldContent?: string;
newContent?: string;
}
interface DiffViewerProps {
projectId: string;
compareFrom?: string; // commit, branch, or 'HEAD'
compareTo?: string; // commit, branch, or working directory
filepath?: string; // If provided, show only this file
}
export function DiffViewer({ projectId, compareFrom = 'HEAD', compareTo, filepath }: DiffViewerProps) {
const [diffs, setDiffs] = useState<FileDiff[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [selectedFile, setSelectedFile] = useState<string | null>(null);
const [viewMode, setViewMode] = useState<'unified' | 'split'>('split');
const [copiedHunk, setCopiedHunk] = useState<number | null>(null);
const { git } = useGit();
const { projectsPath } = useFSPaths();
const { fs } = useFS();
const { toast } = useToast();
const projectPath = `${projectsPath}/${projectId}`;
const getChangedFilesBetweenRefs = useCallback(async (from: string, to: string): Promise<string[]> => {
// Get list of files from both refs and find differences
const filesFrom = await git.listFiles({ dir: projectPath, ref: from });
const filesTo = await git.listFiles({ dir: projectPath, ref: to });
const changedFiles = new Set<string>();
// Check files that exist in 'to'
for (const file of filesTo) {
try {
const blobFrom = await git.readBlob({ dir: projectPath, oid: from, filepath: file });
const blobTo = await git.readBlob({ dir: projectPath, oid: to, filepath: file });
// Compare content
if (Buffer.from(blobFrom.blob).toString() !== Buffer.from(blobTo.blob).toString()) {
changedFiles.add(file);
}
} catch {
// File exists in one but not the other
changedFiles.add(file);
}
}
// Check files that were deleted
for (const file of filesFrom) {
if (!filesTo.includes(file)) {
changedFiles.add(file);
}
}
return Array.from(changedFiles);
}, [git, projectPath]);
const generateFileDiff = useCallback(async (
file: string,
from: string,
to?: string
): Promise<FileDiff | null> => {
try {
let oldContent = '';
let newContent = '';
let status: 'modified' | 'added' | 'deleted' = 'modified';
// Get old content
try {
const blob = await git.readBlob({ dir: projectPath, oid: from, filepath: file });
oldContent = Buffer.from(blob.blob).toString('utf-8');
} catch {
// File didn't exist in old version
status = 'added';
}
// Get new content
try {
if (to) {
const blob = await git.readBlob({ dir: projectPath, oid: to, filepath: file });
newContent = Buffer.from(blob.blob).toString('utf-8');
} else {
// Working directory
const content = await fs.readFile(`${projectPath}/${file}`, { encoding: 'utf8' });
newContent = content;
}
} catch {
// File doesn't exist in new version
if (status !== 'added') {
status = 'deleted';
}
}
// Generate hunks
const hunks = generateDiffHunks(oldContent, newContent);
return {
filepath: file,
status,
hunks,
oldContent,
newContent,
};
} catch (error) {
console.error(`Error generating diff for ${file}:`, error);
return null;
}
}, [git, projectPath, fs]);
const generateDiffHunks = (oldContent: string, newContent: string): DiffHunk[] => {
const oldLines = oldContent.split('\n');
const newLines = newContent.split('\n');
// Simple line-by-line diff
const hunks: DiffHunk[] = [];
let currentHunk: DiffHunk | null = null;
let oldIndex = 0;
let newIndex = 0;
while (oldIndex < oldLines.length || newIndex < newLines.length) {
const oldLine = oldLines[oldIndex];
const newLine = newLines[newIndex];
if (oldLine === newLine) {
// Context line
if (currentHunk) {
currentHunk.lines.push({
type: 'context',
content: oldLine || '',
oldLineNumber: oldIndex + 1,
newLineNumber: newIndex + 1,
});
}
oldIndex++;
newIndex++;
} else {
// Start a new hunk if needed
if (!currentHunk) {
currentHunk = {
oldStart: oldIndex + 1,
oldLines: 0,
newStart: newIndex + 1,
newLines: 0,
lines: [],
};
// Add context before the change
const contextStart = Math.max(0, oldIndex - 3);
for (let i = contextStart; i < oldIndex; i++) {
currentHunk.lines.push({
type: 'context',
content: oldLines[i] || '',
oldLineNumber: i + 1,
newLineNumber: i + 1,
});
}
}
// Determine if this is an addition, deletion, or modification
if (oldIndex >= oldLines.length) {
// Addition
currentHunk.lines.push({
type: 'add',
content: newLine || '',
newLineNumber: newIndex + 1,
});
currentHunk.newLines++;
newIndex++;
} else if (newIndex >= newLines.length) {
// Deletion
currentHunk.lines.push({
type: 'delete',
content: oldLine || '',
oldLineNumber: oldIndex + 1,
});
currentHunk.oldLines++;
oldIndex++;
} else {
// Changed line - show as delete + add
currentHunk.lines.push({
type: 'delete',
content: oldLine || '',
oldLineNumber: oldIndex + 1,
});
currentHunk.lines.push({
type: 'add',
content: newLine || '',
newLineNumber: newIndex + 1,
});
currentHunk.oldLines++;
currentHunk.newLines++;
oldIndex++;
newIndex++;
}
// Check if we should close this hunk
const contextAfter = 3;
let contextCount = 0;
let tempOldIndex = oldIndex;
let tempNewIndex = newIndex;
while (
contextCount < contextAfter &&
tempOldIndex < oldLines.length &&
tempNewIndex < newLines.length
) {
if (oldLines[tempOldIndex] === newLines[tempNewIndex]) {
currentHunk.lines.push({
type: 'context',
content: oldLines[tempOldIndex] || '',
oldLineNumber: tempOldIndex + 1,
newLineNumber: tempNewIndex + 1,
});
contextCount++;
tempOldIndex++;
tempNewIndex++;
} else {
break;
}
}
if (contextCount >= contextAfter || tempOldIndex >= oldLines.length) {
hunks.push(currentHunk);
currentHunk = null;
oldIndex = tempOldIndex;
newIndex = tempNewIndex;
}
}
}
// Close any remaining hunk
if (currentHunk) {
hunks.push(currentHunk);
}
return hunks;
};
const loadDiffs = useCallback(async () => {
setIsLoading(true);
try {
let files: string[] = [];
if (filepath) {
files = [filepath];
} else if (compareTo) {
// Compare two commits/branches
files = await getChangedFilesBetweenRefs(compareFrom, compareTo);
} else {
// Compare against working directory
const statusMatrix = await git.statusMatrix({ dir: projectPath });
files = statusMatrix
.filter(([, head, workdir]) => head !== workdir)
.map(([file]) => file);
}
const fileDiffs: FileDiff[] = [];
for (const file of files) {
try {
const diff = await generateFileDiff(file, compareFrom, compareTo);
if (diff) {
fileDiffs.push(diff);
}
} catch (error) {
console.warn(`Failed to generate diff for ${file}:`, error);
}
}
setDiffs(fileDiffs);
if (fileDiffs.length > 0 && !selectedFile) {
setSelectedFile(fileDiffs[0].filepath);
}
} catch (error) {
console.error('Failed to load diffs:', error);
toast({
title: 'Failed to load diffs',
description: error instanceof Error ? error.message : 'Unknown error',
variant: 'destructive',
});
} finally {
setIsLoading(false);
}
}, [compareFrom, compareTo, filepath, git, projectPath, selectedFile, toast, getChangedFilesBetweenRefs, generateFileDiff]);
useEffect(() => {
loadDiffs();
}, [projectId, compareFrom, compareTo, filepath, loadDiffs]);
const copyHunkToClipboard = async (hunk: DiffHunk, index: number) => {
const hunkText = hunk.lines.map(line => line.content).join('\n');
await navigator.clipboard.writeText(hunkText);
setCopiedHunk(index);
setTimeout(() => setCopiedHunk(null), 2000);
};
const selectedDiff = diffs.find(d => d.filepath === selectedFile);
if (isLoading) {
return (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
);
}
if (diffs.length === 0) {
return (
<div className="flex flex-col items-center justify-center py-12 text-center">
<FileIcon className="h-12 w-12 text-muted-foreground mb-4" />
<p className="text-muted-foreground">No changes to display</p>
</div>
);
}
return (
<div className="flex h-full">
{/* File list sidebar */}
<div className="w-64 border-r">
<div className="p-4 border-b">
<h3 className="font-semibold text-sm">Changed Files</h3>
<p className="text-xs text-muted-foreground mt-1">
{diffs.length} file{diffs.length !== 1 ? 's' : ''} changed
</p>
</div>
<ScrollArea className="h-[calc(100%-73px)]">
<div className="p-2 space-y-1">
{diffs.map((diff) => (
<button
key={diff.filepath}
onClick={() => setSelectedFile(diff.filepath)}
className={cn(
'w-full flex items-center gap-2 p-2 rounded-lg text-left transition-colors',
selectedFile === diff.filepath
? 'bg-primary/10 text-primary'
: 'hover:bg-muted/50'
)}
>
{diff.status === 'added' && <Plus className="h-4 w-4 text-green-600 shrink-0" />}
{diff.status === 'deleted' && <Minus className="h-4 w-4 text-red-600 shrink-0" />}
{diff.status === 'modified' && <Edit className="h-4 w-4 text-blue-600 shrink-0" />}
<span className="font-mono text-sm truncate">{diff.filepath}</span>
</button>
))}
</div>
</ScrollArea>
</div>
{/* Diff content */}
<div className="flex-1 flex flex-col">
{selectedDiff && (
<>
{/* Header */}
<div className="p-4 border-b flex items-center justify-between">
<div className="flex items-center gap-3">
<h3 className="font-mono text-sm font-medium">{selectedDiff.filepath}</h3>
<Badge
variant="outline"
className={cn(
selectedDiff.status === 'added' && 'border-green-600 text-green-600',
selectedDiff.status === 'deleted' && 'border-red-600 text-red-600',
selectedDiff.status === 'modified' && 'border-blue-600 text-blue-600'
)}
>
{selectedDiff.status}
</Badge>
</div>
<Tabs value={viewMode} onValueChange={(v) => setViewMode(v as 'unified' | 'split')}>
<TabsList>
<TabsTrigger value="split" className="gap-2">
<SplitSquareHorizontal className="h-4 w-4" />
Split
</TabsTrigger>
<TabsTrigger value="unified" className="gap-2">
<ListTree className="h-4 w-4" />
Unified
</TabsTrigger>
</TabsList>
</Tabs>
</div>
{/* Diff content */}
<ScrollArea className="flex-1">
<div className="p-4">
{selectedDiff.hunks.map((hunk, hunkIndex) => (
<div key={hunkIndex} className="mb-6 border rounded-lg overflow-hidden">
{/* Hunk header */}
<div className="bg-muted/50 px-4 py-2 flex items-center justify-between border-b">
<span className="font-mono text-xs text-muted-foreground">
@@ -{hunk.oldStart},{hunk.oldLines} +{hunk.newStart},{hunk.newLines} @@
</span>
<Button
variant="ghost"
size="sm"
className="h-6 px-2"
onClick={() => copyHunkToClipboard(hunk, hunkIndex)}
>
{copiedHunk === hunkIndex ? (
<>
<Check className="h-3 w-3 mr-1" />
Copied
</>
) : (
<>
<Copy className="h-3 w-3 mr-1" />
Copy
</>
)}
</Button>
</div>
{/* Hunk lines */}
{viewMode === 'split' ? (
<SplitDiffView hunk={hunk} filepath={selectedDiff.filepath} />
) : (
<UnifiedDiffView hunk={hunk} filepath={selectedDiff.filepath} />
)}
</div>
))}
</div>
</ScrollArea>
</>
)}
</div>
</div>
);
}
function SplitDiffView({ hunk }: { hunk: DiffHunk; filepath: string }) {
return (
<div className="grid grid-cols-2 divide-x font-mono text-sm">
{/* Old (left) side */}
<div>
{hunk.lines.map((line, i) => (
line.type !== 'add' && (
<div
key={i}
className={cn(
'flex',
line.type === 'delete' && 'bg-red-50 dark:bg-red-950/20'
)}
>
<span className="px-2 py-1 text-muted-foreground select-none w-12 text-right shrink-0">
{line.oldLineNumber}
</span>
<pre className="px-2 py-1 flex-1 overflow-x-auto">
<code
className={cn(line.type === 'delete' && 'text-red-700 dark:text-red-400')}
dangerouslySetInnerHTML={{ __html: line.content }}
/>
</pre>
</div>
)
))}
</div>
{/* New (right) side */}
<div>
{hunk.lines.map((line, i) => (
line.type !== 'delete' && (
<div
key={i}
className={cn(
'flex',
line.type === 'add' && 'bg-green-50 dark:bg-green-950/20'
)}
>
<span className="px-2 py-1 text-muted-foreground select-none w-12 text-right shrink-0">
{line.newLineNumber}
</span>
<pre className="px-2 py-1 flex-1 overflow-x-auto">
<code
className={cn(line.type === 'add' && 'text-green-700 dark:text-green-400')}
dangerouslySetInnerHTML={{ __html: line.content }}
/>
</pre>
</div>
)
))}
</div>
</div>
);
}
function UnifiedDiffView({ hunk }: { hunk: DiffHunk; filepath: string }) {
return (
<div className="font-mono text-sm">
{hunk.lines.map((line, i) => (
<div
key={i}
className={cn(
'flex',
line.type === 'add' && 'bg-green-50 dark:bg-green-950/20',
line.type === 'delete' && 'bg-red-50 dark:bg-red-950/20'
)}
>
<span className="px-2 py-1 text-muted-foreground select-none w-12 text-right shrink-0">
{line.oldLineNumber || line.newLineNumber}
</span>
<span className="px-2 py-1 select-none w-6 shrink-0">
{line.type === 'add' ? '+' : line.type === 'delete' ? '-' : ' '}
</span>
<pre className="px-2 py-1 flex-1 overflow-x-auto">
<code
className={cn(
line.type === 'add' && 'text-green-700 dark:text-green-400',
line.type === 'delete' && 'text-red-700 dark:text-red-400'
)}
dangerouslySetInnerHTML={{ __html: line.content }}
/>
</pre>
</div>
))}
</div>
);
}
+168
View File
@@ -0,0 +1,168 @@
import { useState, useEffect } from 'react';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { ScrollArea } from '@/components/ui/scroll-area';
import {
GitBranch,
GitCompare,
Settings,
GitPullRequest,
} from 'lucide-react';
import { BranchManager } from './BranchManager';
import { CompareView } from './CompareView';
import { DiffViewer } from './DiffViewer';
import { PullRequestForm } from './PullRequestForm';
import { useGitStatus } from '@/hooks/useGitStatus';
import { useGit } from '@/hooks/useGit';
import { useFSPaths } from '@/hooks/useFSPaths';
interface GitManagementDialogProps{
projectId: string;
children?: React.ReactNode;
open?: boolean;
onOpenChange?: (open: boolean) => void;
defaultTab?: string;
}
export function GitManagementDialog({
projectId,
children,
open,
onOpenChange,
defaultTab = 'branches',
}: GitManagementDialogProps) {
const [activeTab, setActiveTab] = useState(defaultTab);
const [remoteUrl, setRemoteUrl] = useState<string | null>(null);
const { git } = useGit();
const { projectsPath } = useFSPaths();
const projectPath = `${projectsPath}/${projectId}`;
const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId);
useEffect(() => {
const loadRemoteUrl = async () => {
try {
const url = await git.getRemoteURL(projectPath, 'origin');
setRemoteUrl(url);
} catch {
setRemoteUrl(null);
}
};
if (open) {
loadRemoteUrl();
}
}, [open, git, projectPath]);
const handleBranchChange = () => {
// Refetch git status when branches change
refetchGitStatus();
};
return (
<>
<Dialog open={open} onOpenChange={onOpenChange}>
{children && <DialogTrigger asChild>{children}</DialogTrigger>}
<DialogContent className="max-w-6xl h-[90vh] p-0 flex flex-col gap-0">
{/* Fixed Header */}
<DialogHeader className="px-6 pt-6 pb-4 border-b shrink-0">
<DialogTitle className="flex items-center gap-2">
<GitBranch className="h-5 w-5" />
Git Management
</DialogTitle>
</DialogHeader>
{/* Tabs Container - takes remaining space */}
<div className="flex-1 flex flex-col min-h-0">
<Tabs value={activeTab} onValueChange={setActiveTab} className="flex-1 flex flex-col">
{/* Fixed Tab List */}
<div className="border-b px-6 shrink-0">
<TabsList className="h-auto p-0 bg-transparent">
<TabsTrigger
value="branches"
className="gap-2 data-[state=active]:border-b-2 data-[state=active]:border-primary rounded-none"
>
<GitBranch className="h-4 w-4" />
Branches
</TabsTrigger>
<TabsTrigger
value="changes"
className="gap-2 data-[state=active]:border-b-2 data-[state=active]:border-primary rounded-none"
>
<Settings className="h-4 w-4" />
Changes
</TabsTrigger>
<TabsTrigger
value="compare"
className="gap-2 data-[state=active]:border-b-2 data-[state=active]:border-primary rounded-none"
>
<GitCompare className="h-4 w-4" />
Compare
</TabsTrigger>
{remoteUrl && (
<TabsTrigger
value="pr"
className="gap-2 data-[state=active]:border-b-2 data-[state=active]:border-primary rounded-none"
>
<GitPullRequest className="h-4 w-4" />
Pull Request
</TabsTrigger>
)}
</TabsList>
</div>
{/* Scrollable Tab Content */}
<TabsContent value="branches" className="flex-1 m-0 data-[state=active]:flex data-[state=active]:flex-col">
<ScrollArea className="flex-1">
<div className="p-6">
<BranchManager
projectId={projectId}
currentBranch={gitStatus?.currentBranch || null}
onBranchChange={handleBranchChange}
/>
</div>
</ScrollArea>
</TabsContent>
<TabsContent value="changes" className="flex-1 m-0 data-[state=active]:flex data-[state=active]:flex-col min-h-0">
<div className="flex-1 min-h-0">
<DiffViewer
projectId={projectId}
compareFrom="HEAD"
/>
</div>
</TabsContent>
<TabsContent value="compare" className="flex-1 m-0 data-[state=active]:flex data-[state=active]:flex-col">
<ScrollArea className="flex-1">
<div className="p-6">
<CompareView projectId={projectId} />
</div>
</ScrollArea>
</TabsContent>
{remoteUrl && (
<TabsContent value="pr" className="flex-1 m-0 data-[state=active]:flex data-[state=active]:flex-col">
<ScrollArea className="flex-1">
<div className="p-6">
<PullRequestForm
projectId={projectId}
currentBranch={gitStatus?.currentBranch || null}
remoteUrl={remoteUrl}
/>
</div>
</ScrollArea>
</TabsContent>
)}
</Tabs>
</div>
</DialogContent>
</Dialog>
</>
);
}
+576
View File
@@ -0,0 +1,576 @@
import { useState, useEffect, useCallback } from 'react';
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
DialogFooter,
} from '@/components/ui/dialog';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent } from '@/components/ui/card';
import {
GitMerge,
Loader2,
AlertCircle,
CheckCircle,
GitCommit,
AlertTriangle,
} from 'lucide-react';
import { useGit } from '@/hooks/useGit';
import { useFSPaths } from '@/hooks/useFSPaths';
import { useToast } from '@/hooks/useToast';
import { useSearchParams } from 'react-router-dom';
interface MergeDialogProps {
projectId: string;
currentBranch: string | null;
sourceBranch?: string;
targetBranch?: string;
open?: boolean;
onOpenChange?: (open: boolean) => void;
onMergeComplete?: () => void;
}
interface MergePreview {
sourceBranch: string;
targetBranch: string;
commitsToMerge: Array<{
oid: string;
message: string;
author: string;
timestamp: number;
}>;
filesChanged: string[];
canFastForward: boolean;
hasConflicts: boolean;
conflictingFiles: string[];
}
export function MergeDialog({
projectId,
currentBranch,
sourceBranch: initialSourceBranch,
targetBranch: _initialTargetBranch,
open,
onOpenChange,
onMergeComplete,
}: MergeDialogProps) {
const [isOpen, setIsOpen] = useState(open ?? false);
const [branches, setBranches] = useState<string[]>([]);
const [sourceBranch, setSourceBranch] = useState<string>(initialSourceBranch || '');
const [isLoadingBranches, setIsLoadingBranches] = useState(false);
const [isLoadingPreview, setIsLoadingPreview] = useState(false);
const [isMerging, setIsMerging] = useState(false);
const [mergePreview, setMergePreview] = useState<MergePreview | null>(null);
const [error, setError] = useState<string | null>(null);
const [mergeComplete, setMergeComplete] = useState(false);
const { git } = useGit();
const { projectsPath } = useFSPaths();
const { toast } = useToast();
const [searchParams, setSearchParams] = useSearchParams();
const projectPath = `${projectsPath}/${projectId}`;
useEffect(() => {
if (open !== undefined) {
setIsOpen(open);
}
}, [open]);
const loadBranches = useCallback(async () => {
setIsLoadingBranches(true);
try {
const localBranches = await git.listBranches({ dir: projectPath });
// Filter out current branch from source options
const availableBranches = localBranches.filter(b => b !== currentBranch);
setBranches(availableBranches);
// Set default source branch
if (availableBranches.length > 0) {
setSourceBranch(availableBranches[0]);
}
} catch (err) {
console.error('Failed to load branches:', err);
toast({
title: 'Failed to load branches',
description: err instanceof Error ? err.message : 'Unknown error',
variant: 'destructive',
});
} finally {
setIsLoadingBranches(false);
}
}, [git, projectPath, currentBranch, toast]);
const loadMergePreview = useCallback(async () => {
if (!sourceBranch || !currentBranch) return;
setIsLoadingPreview(true);
setError(null);
try {
// Get commits that will be merged
const sourceCommits = await git.log({ dir: projectPath, ref: sourceBranch, depth: 50 });
const targetCommits = await git.log({ dir: projectPath, ref: currentBranch, depth: 50 });
const targetCommitIds = new Set(targetCommits.map(c => c.oid));
const commitsToMerge = sourceCommits.filter(c => !targetCommitIds.has(c.oid));
// Get changed files
const sourceFiles = await git.listFiles({ dir: projectPath, ref: sourceBranch });
const targetFiles = await git.listFiles({ dir: projectPath, ref: currentBranch });
const changedFiles = new Set<string>();
for (const file of [...sourceFiles, ...targetFiles]) {
try {
const sourceBlob = await git.readBlob({
dir: projectPath,
oid: sourceBranch,
filepath: file,
}).catch(() => null);
const targetBlob = await git.readBlob({
dir: projectPath,
oid: currentBranch,
filepath: file,
}).catch(() => null);
if (!sourceBlob || !targetBlob ||
Buffer.from(sourceBlob.blob).toString() !== Buffer.from(targetBlob.blob).toString()) {
changedFiles.add(file);
}
} catch {
changedFiles.add(file);
}
}
// Check if can fast-forward
const sourceOid = await git.resolveRef({ dir: projectPath, ref: sourceBranch });
const targetOid = await git.resolveRef({ dir: projectPath, ref: currentBranch });
const canFastForward = await git.isDescendent({
dir: projectPath,
oid: sourceOid,
ancestor: targetOid,
}).catch(() => false);
// Try to detect conflicts (simplified - real detection happens during merge)
const conflictingFiles: string[] = [];
// For now, we'll set this during actual merge
setMergePreview({
sourceBranch,
targetBranch: currentBranch,
commitsToMerge: commitsToMerge.map(c => ({
oid: c.oid,
message: c.commit.message,
author: c.commit.author.name,
timestamp: c.commit.author.timestamp,
})),
filesChanged: Array.from(changedFiles),
canFastForward,
hasConflicts: false,
conflictingFiles,
});
} catch (err) {
console.error('Failed to load merge preview:', err);
setError(err instanceof Error ? err.message : 'Unknown error');
} finally {
setIsLoadingPreview(false);
}
}, [sourceBranch, currentBranch, git, projectPath]);
useEffect(() => {
if (isOpen) {
loadBranches();
}
}, [isOpen, loadBranches]);
useEffect(() => {
if (sourceBranch && currentBranch && sourceBranch !== currentBranch) {
loadMergePreview();
} else {
setMergePreview(null);
}
}, [sourceBranch, currentBranch, loadMergePreview]);
const performMerge = async () => {
if (!sourceBranch || !currentBranch) return;
setIsMerging(true);
setError(null);
try {
// Check if can fast-forward
const sourceOid = await git.resolveRef({ dir: projectPath, ref: sourceBranch });
const targetOid = await git.resolveRef({ dir: projectPath, ref: currentBranch });
const canFastForward = await git.isDescendent({
dir: projectPath,
oid: sourceOid,
ancestor: targetOid,
}).catch(() => false);
if (canFastForward) {
// Fast-forward merge: update the current branch to point to source branch commit
await git.writeRef({
dir: projectPath,
ref: `refs/heads/${currentBranch}`,
value: sourceOid,
force: true,
});
// Update working directory to match the new HEAD
await git.checkout({
dir: projectPath,
ref: currentBranch,
force: true,
});
toast({
title: 'Fast-forward merge successful',
description: `Successfully fast-forwarded ${currentBranch} to ${sourceBranch}`,
});
} else {
// Three-way merge
const result = await git.merge({
dir: projectPath,
ours: currentBranch,
theirs: sourceBranch,
author: {
name: 'shakespeare.diy',
email: '[email protected]',
},
message: `Merge branch '${sourceBranch}' into ${currentBranch}`,
});
if (result.alreadyMerged) {
toast({
title: 'Already merged',
description: 'The branches are already merged',
});
setMergeComplete(true);
onMergeComplete?.();
return;
}
// The merge result contains the new tree OID
// We need to create a commit with this tree
const mergeCommitOid = await git.commit({
dir: projectPath,
message: `Merge branch '${sourceBranch}' into ${currentBranch}`,
parent: [targetOid, sourceOid], // Two parents for merge commit
tree: result.tree,
});
console.log('Created merge commit:', mergeCommitOid);
// Update working directory to match the merge
await git.checkout({
dir: projectPath,
ref: currentBranch,
force: true,
});
toast({
title: 'Merge successful',
description: `Successfully merged ${sourceBranch} into ${currentBranch}`,
});
}
setMergeComplete(true);
// Trigger rebuild
setTimeout(() => {
const newSearchParams = new URLSearchParams(searchParams);
newSearchParams.set('build', '');
setSearchParams(newSearchParams);
}, 500);
onMergeComplete?.();
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error';
if (errorMessage.includes('conflict') || errorMessage.includes('CONFLICT')) {
setError('Merge conflicts detected. Please resolve conflicts manually using the terminal.');
} else {
setError(errorMessage);
}
toast({
title: 'Merge failed',
description: errorMessage,
variant: 'destructive',
duration: Infinity,
});
} finally {
setIsMerging(false);
}
};
const formatDate = (timestamp: number) => {
const date = new Date(timestamp * 1000);
const now = new Date();
const diffMs = now.getTime() - date.getTime();
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
if (diffDays === 0) {
return 'today';
} else if (diffDays === 1) {
return 'yesterday';
} else if (diffDays < 7) {
return `${diffDays} days ago`;
} else {
return date.toLocaleDateString();
}
};
const handleOpenChange = (newOpen: boolean) => {
setIsOpen(newOpen);
onOpenChange?.(newOpen);
if (!newOpen) {
setSourceBranch('');
setMergePreview(null);
setError(null);
setMergeComplete(false);
}
};
if (!currentBranch) {
return null;
}
return (
<Dialog open={isOpen} onOpenChange={handleOpenChange}>
<DialogTrigger asChild>
<Button variant="outline" className="gap-2">
<GitMerge className="h-4 w-4" />
Merge Branch
</Button>
</DialogTrigger>
<DialogContent className="max-w-2xl max-h-[90vh]">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<GitMerge className="h-5 w-5" />
Merge Branch
</DialogTitle>
<DialogDescription>
Merge changes from another branch into {currentBranch}
</DialogDescription>
</DialogHeader>
{mergeComplete ? (
// Success state
<div className="py-8 text-center space-y-4">
<CheckCircle className="h-16 w-16 text-green-600 mx-auto" />
<div>
<h3 className="text-lg font-semibold mb-2">Merge Complete!</h3>
<p className="text-muted-foreground">
Successfully merged {sourceBranch} into {currentBranch}
</p>
</div>
<Button onClick={() => handleOpenChange(false)}>
Close
</Button>
</div>
) : (
<ScrollArea className="max-h-[60vh]">
<div className="space-y-6 pr-4">
{/* Source branch selection */}
<div className="space-y-2">
<label className="text-sm font-medium">Source Branch</label>
<Select
value={sourceBranch}
onValueChange={setSourceBranch}
disabled={isLoadingBranches || isMerging}
>
<SelectTrigger>
<SelectValue placeholder="Select branch to merge from" />
</SelectTrigger>
<SelectContent>
{branches.map((branch) => (
<SelectItem key={branch} value={branch}>
{branch}
</SelectItem>
))}
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
The branch to merge into {currentBranch}
</p>
</div>
{/* Merge direction visualization */}
{sourceBranch && (
<div className="bg-muted/30 rounded-lg p-4">
<div className="flex items-center gap-2 justify-center text-sm">
<Badge variant="outline" className="font-mono">
{sourceBranch}
</Badge>
<GitMerge className="h-4 w-4 text-muted-foreground" />
<Badge variant="default" className="font-mono">
{currentBranch}
</Badge>
</div>
</div>
)}
{/* Error alert */}
{error && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{/* Loading preview */}
{isLoadingPreview && (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground mr-2" />
<span className="text-muted-foreground">Loading merge preview...</span>
</div>
)}
{/* Merge preview */}
{mergePreview && !isLoadingPreview && (
<div className="space-y-4">
{/* Stats */}
<div className="grid grid-cols-2 gap-4">
<Card>
<CardContent className="pt-6 text-center">
<div className="text-2xl font-bold text-green-600">
{mergePreview.commitsToMerge.length}
</div>
<div className="text-sm text-muted-foreground mt-1">
Commits to Merge
</div>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6 text-center">
<div className="text-2xl font-bold text-blue-600">
{mergePreview.filesChanged.length}
</div>
<div className="text-sm text-muted-foreground mt-1">
Files Changed
</div>
</CardContent>
</Card>
</div>
{/* Fast-forward badge */}
{mergePreview.canFastForward && (
<Alert>
<CheckCircle className="h-4 w-4" />
<AlertDescription>
This merge can be fast-forwarded (no merge commit needed)
</AlertDescription>
</Alert>
)}
{/* Commits to merge */}
{mergePreview.commitsToMerge.length > 0 && (
<div>
<h4 className="text-sm font-medium mb-3">Commits to be merged:</h4>
<div className="space-y-2 max-h-60 overflow-y-auto">
{mergePreview.commitsToMerge.slice(0, 10).map((commit) => (
<div
key={commit.oid}
className="flex items-start gap-3 p-3 rounded-lg border bg-card"
>
<GitCommit className="h-4 w-4 text-muted-foreground shrink-0 mt-0.5" />
<div className="flex-1 min-w-0">
<p className="text-sm font-medium">
{commit.message.split('\n')[0]}
</p>
<div className="flex items-center gap-2 mt-1 text-xs text-muted-foreground">
<span>{commit.author}</span>
<span>•</span>
<span>{formatDate(commit.timestamp)}</span>
</div>
</div>
</div>
))}
{mergePreview.commitsToMerge.length > 10 && (
<p className="text-xs text-muted-foreground text-center py-2">
+ {mergePreview.commitsToMerge.length - 10} more commits
</p>
)}
</div>
</div>
)}
{/* No changes */}
{mergePreview.commitsToMerge.length === 0 && (
<Alert>
<CheckCircle className="h-4 w-4" />
<AlertDescription>
No new commits to merge. The branches are already in sync.
</AlertDescription>
</Alert>
)}
{/* Warning about conflicts */}
{mergePreview.hasConflicts && (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>
Conflicts detected in {mergePreview.conflictingFiles.length} file(s).
You may need to resolve conflicts manually.
</AlertDescription>
</Alert>
)}
</div>
)}
</div>
</ScrollArea>
)}
{!mergeComplete && (
<DialogFooter>
<Button
variant="outline"
onClick={() => handleOpenChange(false)}
disabled={isMerging}
>
Cancel
</Button>
<Button
onClick={performMerge}
disabled={
isMerging ||
isLoadingPreview ||
!mergePreview ||
mergePreview.commitsToMerge.length === 0
}
>
{isMerging ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Merging...
</>
) : (
<>
<GitMerge className="h-4 w-4 mr-2" />
Merge Branch
</>
)}
</Button>
</DialogFooter>
)}
</DialogContent>
</Dialog>
);
}
File diff suppressed because it is too large. Load diff
+565
View File
@@ -0,0 +1,565 @@
import { useState, useEffect, useCallback } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Badge } from '@/components/ui/badge';
import {
GitPullRequest,
Loader2,
AlertCircle,
CheckCircle,
ExternalLink,
GitCompare,
GitFork,
} from 'lucide-react';
import { useGit } from '@/hooks/useGit';
import { useFSPaths } from '@/hooks/useFSPaths';
import { useGitSettings } from '@/hooks/useGitSettings';
import { useToast } from '@/hooks/useToast';
import { findCredentialsForRepo } from '@/lib/gitCredentials';
interface PullRequestFormProps {
projectId: string;
currentBranch: string | null;
remoteUrl: string;
}
interface RemoteInfo {
owner: string;
repo: string;
platform: 'github' | 'gitlab';
apiUrl: string;
}
interface ForkInfo {
needsFork: boolean;
forkOwner?: string;
forkRepo?: string;
forkUrl?: string;
}
export function PullRequestForm({ projectId, currentBranch, remoteUrl }: PullRequestFormProps) {
const [title, setTitle] = useState('');
const [description, setDescription] = useState('');
const [targetBranch, setTargetBranch] = useState('main');
const [remoteBranches, setRemoteBranches] = useState<string[]>([]);
const [isCreating, setIsCreating] = useState(false);
const [remoteInfo, setRemoteInfo] = useState<RemoteInfo | null>(null);
const [forkInfo, setForkInfo] = useState<ForkInfo>({ needsFork: false });
const [isCheckingPermissions, setIsCheckingPermissions] = useState(false);
const [createdPrUrl, setCreatedPrUrl] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const { git } = useGit();
const { projectsPath } = useFSPaths();
const { settings } = useGitSettings();
const { toast } = useToast();
const projectPath = `${projectsPath}/${projectId}`;
// All the helper functions from PullRequestDialog can be reused here
// (parseRemoteUrl, checkPushPermissions, ensureFork, etc.)
// For brevity, I'll import them or duplicate the core logic
const parseRemoteUrl = useCallback((url: string) => {
// Same implementation as PullRequestDialog
setError(null);
try {
let match;
let owner = '';
let repo = '';
let platform: 'github' | 'gitlab' = 'github';
let apiUrl = '';
const normalizedUrl = url.replace(/\.git$/, '');
// GitHub SSH/HTTPS
match = normalizedUrl.match(/git@github\.com:([^/]+)\/(.+)$/) ||
normalizedUrl.match(/https?:\/\/github\.com\/([^/]+)\/(.+)$/);
if (match) {
owner = match[1];
repo = match[2];
platform = 'github';
apiUrl = 'https://api.github.com';
}
// GitLab SSH/HTTPS
if (!match) {
match = normalizedUrl.match(/git@gitlab\.com:([^/]+)\/(.+)$/) ||
normalizedUrl.match(/https?:\/\/gitlab\.com\/([^/]+)\/(.+)$/);
if (match) {
owner = match[1];
repo = match[2];
platform = 'gitlab';
apiUrl = 'https://gitlab.com/api/v4';
}
}
if (owner && repo) {
setRemoteInfo({ owner, repo, platform, apiUrl });
} else {
setError('Unsupported remote URL format');
}
} catch {
setError('Failed to parse remote URL');
}
}, []);
const loadRemoteBranches = useCallback(async () => {
try {
const branches = await git.listBranches({
dir: projectPath,
remote: 'origin',
});
setRemoteBranches(branches);
if (branches.includes('main')) {
setTargetBranch('main');
} else if (branches.includes('master')) {
setTargetBranch('master');
} else if (branches.length > 0) {
setTargetBranch(branches[0]);
}
} catch {
setRemoteBranches(['main', 'master', 'develop']);
}
}, [git, projectPath]);
const checkPermissionsAndFork = useCallback(async () => {
if (!remoteInfo) return;
setIsCheckingPermissions(true);
try {
const credentials = findCredentialsForRepo(remoteUrl, settings.credentials);
if (!credentials) {
setForkInfo({ needsFork: false });
return;
}
// Simplified permission check - assume fork needed if we get 403/404
// Full implementation would use the helper functions from PullRequestDialog
setForkInfo({ needsFork: false });
} catch {
setForkInfo({ needsFork: false });
} finally {
setIsCheckingPermissions(false);
}
}, [remoteInfo, remoteUrl, settings.credentials]);
useEffect(() => {
if (remoteUrl) {
parseRemoteUrl(remoteUrl);
loadRemoteBranches();
checkPermissionsAndFork();
}
}, [remoteUrl, parseRemoteUrl, loadRemoteBranches, checkPermissionsAndFork]);
const createPullRequest = async () => {
if (!remoteInfo || !currentBranch) return;
if (!title.trim()) {
toast({
title: 'Title required',
description: 'Please enter a title for the pull request',
variant: 'destructive',
});
return;
}
setIsCreating(true);
setError(null);
try {
const credentials = findCredentialsForRepo(remoteUrl, settings.credentials);
if (!credentials) {
throw new Error('No credentials found. Please add credentials in Settings > Git');
}
// Check if user is on main/master - if so, create a feature branch
let branchToUse = currentBranch;
const isOnDefaultBranch = currentBranch === 'main' || currentBranch === 'master';
if (isOnDefaultBranch) {
console.log(`User is on default branch '${currentBranch}', creating feature branch`);
// Generate branch name from PR title
const sanitizedTitle = title
.toLowerCase()
.replace(/[^a-z0-9\s-]/g, '')
.replace(/\s+/g, '-')
.replace(/-+/g, '-')
.replace(/^-|-$/g, '')
.substring(0, 50);
const baseName = sanitizedTitle || 'feature';
const featureBranchName = `${baseName}-${Date.now().toString(36).slice(-4)}`;
console.log(`Creating feature branch: ${featureBranchName}`);
try {
// Check for uncommitted changes BEFORE creating branch
const statusMatrix = await git.statusMatrix({ dir: projectPath });
const hasUncommittedChanges = statusMatrix.some(([, head, workdir]) => head !== workdir);
// Create and checkout branch first
await git.branch({
dir: projectPath,
ref: featureBranchName,
checkout: true,
});
branchToUse = featureBranchName;
console.log(`Successfully created and checked out branch: ${featureBranchName}`);
// If there were uncommitted changes, commit them to the new branch
if (hasUncommittedChanges) {
console.log('Committing changes to new branch');
for (const [filepath, , workdir] of statusMatrix) {
if ((workdir as number) === 0) {
await git.remove({ dir: projectPath, filepath });
} else if ((workdir as number) !== 0) {
await git.add({ dir: projectPath, filepath });
}
}
await git.commit({
dir: projectPath,
message: title,
});
console.log('Committed changes to new branch');
}
toast({
title: 'Feature branch created',
description: `Created branch '${featureBranchName}' for your changes`,
});
} catch (branchError) {
console.error('Failed to create feature branch:', branchError);
throw new Error(
`Cannot create PR from '${currentBranch}' branch.\n\n` +
`Failed to create a feature branch automatically.\n` +
`Please create a new branch manually in the Branches tab first.\n\n` +
`Error: ${branchError instanceof Error ? branchError.message : 'Unknown error'}`
);
}
}
// If fork is needed, push the branch first
const headRef = forkInfo.needsFork && forkInfo.forkOwner
? `${forkInfo.forkOwner}:${branchToUse}`
: branchToUse;
console.log('PR head ref will be:', headRef);
console.log('PR base ref will be:', targetBranch);
if (forkInfo.needsFork && forkInfo.forkUrl) {
console.log(`Pushing branch ${branchToUse} to fork ${forkInfo.forkUrl}`);
// Check current remotes
const remotes = await git.listRemotes({ dir: projectPath });
const originRemote = remotes.find(r => r.remote === 'origin');
const forkRemote = remotes.find(r => r.url === forkInfo.forkUrl);
let pushRemote = 'origin';
if (originRemote?.url !== forkInfo.forkUrl) {
if (forkRemote) {
pushRemote = forkRemote.remote;
} else {
await git.addRemote({
dir: projectPath,
remote: 'fork',
url: forkInfo.forkUrl,
});
pushRemote = 'fork';
}
}
try {
await git.push({
dir: projectPath,
remote: pushRemote,
ref: branchToUse,
onAuth: () => credentials,
});
console.log('Successfully pushed to fork');
} catch (pushError) {
const errorMsg = pushError instanceof Error ? pushError.message : 'Unknown error';
throw new Error(
`Failed to push branch '${branchToUse}' to your fork.\n\n` +
`This usually means:\n` +
`1. The branch hasn't been committed yet\n` +
`2. Network/authentication issues\n\n` +
`Error: ${errorMsg}\n\n` +
`Try committing and pushing manually first.`
);
}
}
const url = `${remoteInfo.apiUrl}/repos/${remoteInfo.owner}/${remoteInfo.repo}/pulls`;
const prData = {
title,
body: description,
head: headRef,
base: targetBranch,
maintainer_can_modify: true,
};
console.log('Creating PR with data:', prData);
const response = await fetch(url, {
method: 'POST',
headers: {
'Authorization': `token ${credentials.password}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(prData),
});
if (!response.ok) {
const errorText = await response.text();
console.error('PR creation failed:', errorText);
let error;
try {
error = JSON.parse(errorText);
} catch {
error = { message: errorText || 'Unknown error' };
}
// Extract detailed error messages
let errorMessage = error.message || `API error: ${response.status} - ${response.statusText}`;
if (error.errors && Array.isArray(error.errors)) {
const errorDetails = error.errors.map((e: { message?: string; field?: string; code?: string }) => {
if (e.message) return e.message;
if (e.field && e.code) return `${e.field}: ${e.code}`;
return JSON.stringify(e);
}).join('; ');
errorMessage = `${errorMessage}\n\nDetails: ${errorDetails}`;
}
if (error.documentation_url) {
errorMessage = `${errorMessage}\n\nSee: ${error.documentation_url}`;
}
throw new Error(errorMessage);
}
const data = await response.json();
setCreatedPrUrl(data.html_url);
toast({
title: 'Pull request created',
description: 'Successfully created pull request',
});
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error';
setError(errorMessage);
toast({
title: 'Failed to create pull request',
description: errorMessage,
variant: 'destructive',
});
} finally {
setIsCreating(false);
}
};
if (!currentBranch) {
return (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
No branch selected. Please select or create a branch first.
</AlertDescription>
</Alert>
);
}
if (createdPrUrl) {
return (
<div className="text-center space-y-4">
<CheckCircle className="h-16 w-16 text-green-600 mx-auto" />
<div>
<h3 className="text-lg font-semibold mb-2">Pull Request Created!</h3>
<p className="text-muted-foreground">
Your pull request has been created successfully
</p>
</div>
<Button
onClick={() => window.open(createdPrUrl, '_blank')}
className="gap-2"
>
View Pull Request
<ExternalLink className="h-4 w-4" />
</Button>
<Button
variant="outline"
onClick={() => {
setCreatedPrUrl(null);
setTitle('');
setDescription('');
}}
>
Create Another
</Button>
</div>
);
}
return (
<div className="space-y-6">
{/* Permission/Fork info */}
{isCheckingPermissions && (
<Alert>
<Loader2 className="h-4 w-4 animate-spin" />
<AlertDescription>Checking repository permissions...</AlertDescription>
</Alert>
)}
{forkInfo.needsFork && forkInfo.forkOwner && (
<Alert>
<AlertDescription>
You don't have push access. Your changes will be pushed to your fork at <strong>{forkInfo.forkOwner}/{forkInfo.forkRepo}</strong>.
</AlertDescription>
</Alert>
)}
{/* Auto-branch creation notice */}
{currentBranch && (currentBranch === 'main' || currentBranch === 'master') && (
<Alert>
<AlertDescription>
You're on the <strong>{currentBranch}</strong> branch. A feature branch will be automatically created from your PR title for this contribution.
</AlertDescription>
</Alert>
)}
{/* Branch comparison */}
<div className="bg-muted/30 rounded-lg p-4">
<div className="flex items-center gap-2 text-sm">
<Badge variant="outline" className="font-mono">
{targetBranch}
</Badge>
<GitCompare className="h-4 w-4 text-muted-foreground" />
<Badge variant="outline" className="font-mono">
{currentBranch}
</Badge>
</div>
<p className="text-xs text-muted-foreground mt-2">
Merge {currentBranch} into {targetBranch}
</p>
{(currentBranch === 'main' || currentBranch === 'master') && (
<p className="text-xs text-blue-600 dark:text-blue-400 mt-1">
Note: A new branch will be created automatically
</p>
)}
</div>
{/* Error alert */}
{error && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription className="whitespace-pre-wrap">{error}</AlertDescription>
</Alert>
)}
{/* Target branch */}
<div className="space-y-2">
<Label htmlFor="target-branch">Target Branch</Label>
<Select value={targetBranch} onValueChange={setTargetBranch} disabled={isCreating}>
<SelectTrigger id="target-branch">
<SelectValue />
</SelectTrigger>
<SelectContent>
{remoteBranches.map((branch) => (
<SelectItem key={branch} value={branch}>
{branch}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Title */}
<div className="space-y-2">
<Label htmlFor="pr-title">Title *</Label>
<Input
id="pr-title"
placeholder="Brief description of your changes"
value={title}
onChange={(e) => setTitle(e.target.value)}
disabled={isCreating}
/>
</div>
{/* Description */}
<div className="space-y-2">
<Label htmlFor="pr-description">Description</Label>
<Textarea
id="pr-description"
placeholder="Provide more details about your changes (supports Markdown)"
value={description}
onChange={(e) => setDescription(e.target.value)}
rows={8}
disabled={isCreating}
className="font-mono text-sm"
/>
</div>
{/* Create button */}
<Button
onClick={createPullRequest}
disabled={isCreating || isCheckingPermissions}
className="w-full"
>
{isCreating ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
{forkInfo.needsFork ? 'Creating fork & PR...' : 'Creating...'}
</>
) : forkInfo.needsFork ? (
<>
<GitFork className="h-4 w-4 mr-2" />
Fork & Create PR
</>
) : (
<>
<GitPullRequest className="h-4 w-4 mr-2" />
Create Pull Request
</>
)}
</Button>
{/* Repository info */}
{remoteInfo && (
<div className="bg-muted/30 rounded-lg p-3">
<div className="text-sm space-y-1">
<div className="flex items-center justify-between">
<span className="text-muted-foreground">Repository:</span>
<span className="font-medium">
{remoteInfo.owner}/{remoteInfo.repo}
</span>
</div>
<div className="flex items-center justify-between">
<span className="text-muted-foreground">Platform:</span>
<Badge variant="outline" className="capitalize">
{remoteInfo.platform}
</Badge>
</div>
</div>
</div>
)}
</div>
);
}
+7
View File
@@ -0,0 +1,7 @@
export { AnnounceRepositoryDialog } from './AnnounceRepositoryDialog';
export { BranchManager } from './BranchManager';
export { CompareView } from './CompareView';
export { DiffViewer } from './DiffViewer';
export { GitManagementDialog } from './GitManagementDialog';
export { MergeDialog } from './MergeDialog';
export { PullRequestDialog } from './PullRequestDialog';
+53 -94
View File
@@ -3,9 +3,11 @@ import { render, screen, fireEvent } from '@testing-library/react';
import { BrowserAddressBar } from './browser-address-bar';
describe('BrowserAddressBar', () => {
it('renders address input and refresh button', () => {
render(<BrowserAddressBar onRefresh={vi.fn()} />);
it('renders navigation buttons and address input', () => {
render(<BrowserAddressBar />);
expect(screen.getByTitle('Go back')).toBeInTheDocument();
expect(screen.getByTitle('Go forward')).toBeInTheDocument();
expect(screen.getByTitle('Refresh')).toBeInTheDocument();
expect(screen.getByPlaceholderText('Enter path (e.g., /, /about)')).toBeInTheDocument();
});
@@ -21,30 +23,65 @@ describe('BrowserAddressBar', () => {
expect(onNavigate).toHaveBeenCalledWith('/about');
});
it('disables input when no onNavigate handler is provided', () => {
render(<BrowserAddressBar />);
it('disables back/forward buttons based on canGoBack/canGoForward props and handlers', () => {
// Test with handlers provided
const onBack = vi.fn();
const onForward = vi.fn();
// Input should be disabled when no onNavigate handler is provided
render(
<BrowserAddressBar
onBack={onBack}
onForward={onForward}
canGoBack={false}
canGoForward={true}
/>
);
expect(screen.getByTitle('Go back')).toBeDisabled(); // disabled because canGoBack=false
expect(screen.getByTitle('Go forward')).not.toBeDisabled(); // enabled because canGoForward=true and handler provided
});
it('disables buttons when no handlers are provided', () => {
render(
<BrowserAddressBar
canGoBack={true}
canGoForward={true}
/>
);
// All buttons should be disabled when no handlers are provided
expect(screen.getByTitle('Go back')).toBeDisabled();
expect(screen.getByTitle('Go forward')).toBeDisabled();
expect(screen.getByTitle('Refresh')).toBeDisabled();
// Input should also be disabled when no onNavigate handler is provided
expect(screen.getByPlaceholderText('Enter path (e.g., /, /about)')).toBeDisabled();
});
it('shows refresh button inside input when onRefresh handler is provided', () => {
it('calls navigation handlers when buttons are clicked', () => {
const onBack = vi.fn();
const onForward = vi.fn();
const onRefresh = vi.fn();
render(<BrowserAddressBar onRefresh={onRefresh} />);
const refreshButton = screen.getByTitle('Refresh');
expect(refreshButton).toBeInTheDocument();
render(
<BrowserAddressBar
onBack={onBack}
onForward={onForward}
onRefresh={onRefresh}
canGoBack={true}
canGoForward={true}
/>
);
fireEvent.click(refreshButton);
fireEvent.click(screen.getByTitle('Go back'));
fireEvent.click(screen.getByTitle('Go forward'));
fireEvent.click(screen.getByTitle('Refresh'));
expect(onBack).toHaveBeenCalled();
expect(onForward).toHaveBeenCalled();
expect(onRefresh).toHaveBeenCalled();
});
it('does not show refresh button when no onRefresh handler is provided', () => {
render(<BrowserAddressBar />);
expect(screen.queryByTitle('Refresh')).not.toBeInTheDocument();
});
it('updates input value when currentPath prop changes', () => {
const { rerender } = render(<BrowserAddressBar currentPath="/" />);
@@ -61,82 +98,4 @@ describe('BrowserAddressBar', () => {
expect(input).toHaveValue('/contact');
});
it('shows navigation history dropdown when input is focused', () => {
const navigationHistory = ['/', '/about', '/contact'];
render(
<BrowserAddressBar
navigationHistory={navigationHistory}
onNavigate={vi.fn()}
/>
);
const input = screen.getByPlaceholderText('Enter path (e.g., /, /about)');
fireEvent.focus(input);
// History should be shown in reverse order (most recent first)
expect(screen.getByText('/contact')).toBeInTheDocument();
expect(screen.getByText('/about')).toBeInTheDocument();
expect(screen.getByText('/')).toBeInTheDocument();
});
it('does not show history dropdown when navigationHistory is empty', () => {
render(
<BrowserAddressBar
navigationHistory={[]}
onNavigate={vi.fn()}
/>
);
const input = screen.getByPlaceholderText('Enter path (e.g., /, /about)');
fireEvent.focus(input);
// No history items should be visible
expect(screen.queryByRole('button', { name: /\// })).not.toBeInTheDocument();
});
it('navigates when clicking a history item', () => {
const onNavigate = vi.fn();
const navigationHistory = ['/', '/about', '/contact'];
render(
<BrowserAddressBar
navigationHistory={navigationHistory}
onNavigate={onNavigate}
/>
);
const input = screen.getByPlaceholderText('Enter path (e.g., /, /about)');
fireEvent.focus(input);
const aboutButton = screen.getByText('/about');
fireEvent.click(aboutButton);
expect(onNavigate).toHaveBeenCalledWith('/about');
});
it('removes duplicate paths from history', () => {
const navigationHistory = ['/', '/about', '/', '/contact', '/about'];
render(
<BrowserAddressBar
navigationHistory={navigationHistory}
onNavigate={vi.fn()}
/>
);
const input = screen.getByPlaceholderText('Enter path (e.g., /, /about)');
fireEvent.focus(input);
// Should only show unique paths
const allButtons = screen.getAllByRole('button');
// Filter out the refresh button if present, only count history items
const historyButtons = allButtons.filter(btn =>
btn.textContent === '/' ||
btn.textContent === '/about' ||
btn.textContent === '/contact'
);
expect(historyButtons).toHaveLength(3);
});
});
+58 -108
View File
@@ -1,55 +1,40 @@
import { useState, useEffect, useRef, useMemo } from 'react';
import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { CheckIcon, RefreshCw } from 'lucide-react';
import { ChevronLeft, ChevronRight, RefreshCw } from 'lucide-react';
import { cn } from '@/lib/utils';
import { DeviceToggle, type DeviceMode } from '@/components/ui/device-toggle';
import { ReactNode } from 'react';
interface BrowserAddressBarProps {
currentPath?: string;
onNavigate?: (path: string) => void;
onRefresh?: () => void;
onBack?: () => void;
onForward?: () => void;
canGoBack?: boolean;
canGoForward?: boolean;
className?: string;
navigationHistory?: string[];
deviceMode?: DeviceMode;
onDeviceModeChange?: (mode: DeviceMode) => void;
extraContent?: ReactNode;
}
export function BrowserAddressBar({
currentPath = '/',
onNavigate,
onRefresh,
onBack,
onForward,
canGoBack = false,
canGoForward = false,
className,
navigationHistory = [],
deviceMode,
onDeviceModeChange,
extraContent,
}: BrowserAddressBarProps) {
const [inputValue, setInputValue] = useState(currentPath);
const [showHistory, setShowHistory] = useState(false);
const inputRef = useRef<HTMLInputElement>(null);
const dropdownRef = useRef<HTMLDivElement>(null);
// Update input value when currentPath changes (e.g., when iframe navigates)
useEffect(() => {
setInputValue(currentPath);
}, [currentPath]);
// Close dropdown when clicking outside
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
const target = event.target as Node | null;
const dropdownElement = dropdownRef.current;
const inputElement = inputRef.current;
if (target && !dropdownElement?.contains(target) && !inputElement?.contains(target)) {
setShowHistory(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (!onNavigate) return;
@@ -62,100 +47,65 @@ export function BrowserAddressBar({
}
onNavigate(path);
setShowHistory(false);
};
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setInputValue(e.target.value);
};
const handleInputFocus = () => {
if (navigationHistory.length > 0) {
setShowHistory(true);
}
};
const handleHistoryItemClick = (path: string) => {
if (onNavigate) {
onNavigate(path);
setShowHistory(false);
inputRef.current?.blur();
}
};
// Get unique history items (reverse to show most recent first, remove duplicates)
const uniqueHistory = useMemo(() => Array.from(new Set([...navigationHistory].reverse())), [navigationHistory]);
return (
<form onSubmit={handleSubmit} className={className}>
{/* Device toggle on left side - only visible on large screens */}
{deviceMode && onDeviceModeChange && (
<div className="hidden md:block absolute left-1 top-1/2 -translate-y-1/2 z-10">
<DeviceToggle
mode={deviceMode}
onModeChange={onDeviceModeChange}
className="size-6 p-0 hover:bg-muted/50 rounded-full transition-colors group"
/>
</div>
)}
<Input
ref={inputRef}
type="text"
value={inputValue}
onChange={handleInputChange}
onFocus={handleInputFocus}
placeholder="Enter path (e.g., /, /about)"
className={cn(
"h-7 text-xs md:text-xs bg-muted/50 border-muted-foreground/20 focus:bg-background rounded-full",
{
"md:pl-9": deviceMode && onDeviceModeChange,
"pr-9": onRefresh,
}
)}
disabled={!onNavigate}
/>
{/* Refresh button on right side */}
{onRefresh && (
<div className={cn(
"flex items-center gap-1 p-2 border-b bg-background w-full",
className
)}>
{/* Navigation buttons */}
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="sm"
onClick={onBack}
disabled={!canGoBack || !onBack}
className="h-8 w-8 p-0"
title="Go back"
>
<ChevronLeft className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={onForward}
disabled={!canGoForward || !onForward}
className="h-8 w-8 p-0"
title="Go forward"
>
<ChevronRight className="h-4 w-4" />
</Button>
<Button
type="button"
variant="ghost"
size="sm"
onClick={onRefresh}
className="size-6 absolute right-1 top-1/2 -translate-y-1/2 hover:bg-muted/50 rounded-full transition-colors group"
disabled={!onRefresh}
className="h-8 w-8 p-0"
title="Refresh"
>
<RefreshCw className="size-3 text-muted-foreground transition-colors group-hover:text-foreground" />
<RefreshCw className="h-4 w-4" />
</Button>
)}
</div>
{/* Navigation history dropdown */}
{showHistory && uniqueHistory.length > 0 && (
<div
ref={dropdownRef}
className="absolute top-full left-1/2 -translate-x-1/2 mt-1 bg-background border rounded-lg shadow-lg overflow-hidden z-50 max-h-64 w-full overflow-y-auto"
>
{uniqueHistory.map((path, index) => (
<button
key={index}
type="button"
onClick={() => handleHistoryItemClick(path)}
className={cn(
"w-full p-3 text-left text-xs hover:bg-muted/50 transition-colors flex items-center gap-2 border-b last:border-b-0",
{
"bg-muted/30 font-medium": path === currentPath,
},
)}
>
<span className="truncate">{path}</span>
{path === currentPath && (
<CheckIcon className="size-3 text-muted-foreground ml-auto" />
)}
</button>
))}
</div>
)}
</form>
{/* Address bar */}
<form onSubmit={handleSubmit} className="flex-1 mx-auto px-4 max-w-2xl">
<Input
type="text"
value={inputValue}
onChange={handleInputChange}
placeholder="Enter path (e.g., /, /about)"
className="h-8 bg-muted/50 border-muted-foreground/20 focus:bg-background"
disabled={!onNavigate}
/>
</form>
{/* Extra content */}
{extraContent}
</div>
);
}
+1 -1
View File
@@ -1,7 +1,7 @@
import { cva } from "class-variance-authority"
export const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0",
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
{
variants: {
variant: {
+1 -1
View File
@@ -115,7 +115,7 @@ const CommandItem = React.forwardRef<
<CommandPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-muted data-[disabled=true]:opacity-50",
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50",
className
)}
{...props}
-41
View File
@@ -1,41 +0,0 @@
import { Button } from '@/components/ui/button';
import { Laptop, Tablet, Smartphone } from 'lucide-react';
export type DeviceMode = 'laptop' | 'tablet' | 'phone';
interface DeviceToggleProps {
mode: DeviceMode;
onModeChange: (mode: DeviceMode) => void;
className?: string;
}
const devices: DeviceMode[] = ['laptop', 'tablet', 'phone'];
const deviceIcons = {
laptop: Laptop,
tablet: Tablet,
phone: Smartphone,
};
export function DeviceToggle({ mode, onModeChange, className }: DeviceToggleProps) {
const handleClick = () => {
const currentIndex = devices.indexOf(mode);
const nextIndex = (currentIndex + 1) % devices.length;
onModeChange(devices[nextIndex]);
};
const Icon = deviceIcons[mode];
return (
<Button
type="button"
variant="ghost"
size="sm"
onClick={handleClick}
className={className}
title={`Current: ${mode} (click to toggle)`}
>
<Icon className="size-3 text-muted-foreground transition-colors group-hover:text-foreground" />
</Button>
);
}
+4 -4
View File
@@ -25,7 +25,7 @@ const DropdownMenuSubTrigger = React.forwardRef<
<DropdownMenuPrimitive.SubTrigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-muted data-[state=open]:bg-muted",
"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",
inset && "pl-8",
className
)}
@@ -81,7 +81,7 @@ const DropdownMenuItem = React.forwardRef<
<DropdownMenuPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-muted data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
inset && "pl-8",
className
)}
@@ -97,7 +97,7 @@ const DropdownMenuCheckboxItem = React.forwardRef<
<DropdownMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-muted data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
checked={checked}
@@ -121,7 +121,7 @@ const DropdownMenuRadioItem = React.forwardRef<
<DropdownMenuPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-muted data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
-100
View File
@@ -1,100 +0,0 @@
import { forwardRef, useState, useEffect, useRef } from "react"
import { Eye, EyeOff, ExternalLink } from "lucide-react"
import { cn } from "@/lib/utils"
interface ExternalInputProps extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'type'> {
/** The type of input - either 'text' or 'password' */
type: 'text' | 'password';
/** URL to open when the external link button is clicked. If not provided, button won't be shown. */
url?: string;
/** Title/label for the external link button. If not provided, button won't be shown. */
urlTitle?: string;
}
const ExternalInput = forwardRef<HTMLInputElement, ExternalInputProps>(
({ className, type, url, urlTitle, value, ...props }, ref) => {
const [showPassword, setShowPassword] = useState(false)
const [isFocused, setIsFocused] = useState(false)
const [buttonWidth, setButtonWidth] = useState(0)
const buttonRef = useRef<HTMLButtonElement>(null)
// Determine if we have a value (works for both controlled and uncontrolled)
const hasValue = Boolean(value || (props.defaultValue && !value))
const isPasswordType = type === 'password'
const showEyeToggle = isPasswordType && hasValue
const showExternalButton = url && urlTitle && !hasValue
// Measure the button width when it's rendered
useEffect(() => {
if (showExternalButton && buttonRef.current) {
const width = buttonRef.current.offsetWidth
setButtonWidth(width)
} else {
setButtonWidth(0)
}
}, [showExternalButton, urlTitle])
// Calculate padding-right based on what's showing
const paddingRight = showEyeToggle
? '2.5rem' // 40px for eye toggle
: showExternalButton && buttonWidth > 0
? `${buttonWidth + 8}px` // button width + 8px spacing
: undefined
return (
<div className={cn("relative", className)}>
<input
type={isPasswordType && !showPassword ? "password" : "text"}
className={cn(
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
{
"ring-2 ring-ring ring-offset-2": isFocused,
},
)}
style={{ paddingRight }}
ref={ref}
value={value}
onFocus={(e) => {
setIsFocused(true)
props.onFocus?.(e)
}}
onBlur={(e) => {
setIsFocused(false)
props.onBlur?.(e)
}}
{...props}
/>
{showEyeToggle && (
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground focus:outline-none disabled:cursor-not-allowed disabled:opacity-50"
disabled={props.disabled}
aria-label={showPassword ? "Hide password" : "Show password"}
>
{showPassword ? (
<EyeOff className="h-4 w-4" />
) : (
<Eye className="h-4 w-4" />
)}
</button>
)}
{showExternalButton && (
<button
ref={buttonRef}
type="button"
className="absolute right-1 top-1/2 -translate-y-1/2 inline-flex items-center gap-1 px-2 py-1 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors rounded-md hover:bg-muted"
onClick={() => window.open(url, '_blank')}
>
{urlTitle}
<ExternalLink className="h-3 w-3" />
</button>
)}
</div>
)
}
)
ExternalInput.displayName = "ExternalInput"
export { ExternalInput }
+2 -2
View File
@@ -65,7 +65,7 @@ export function FileAttachment({
size="sm"
onClick={handleButtonClick}
disabled={disabled}
className="h-8 w-8 p-0 rounded-full hover:bg-muted/50"
className="h-8 w-8 p-0 rounded-full hover:bg-muted/50 dark:hover:text-sidebar-primary"
aria-label="Attach files"
data-testid="paperclip-button"
>
@@ -90,7 +90,7 @@ export function FileAttachment({
onClick={() => handleRemoveFile(file)}
className="h-3 w-3 p-0 hover:bg-muted/70"
>
<X className="size-3" />
<X className="h-2 w-2" />
</Button>
)}
</div>
+2 -50
View File
@@ -2,57 +2,10 @@ import * as React from "react"
import { cn } from "@/lib/utils"
export interface TextareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
/**
* Callback fired when an image is pasted into the textarea.
* If both onPaste and onPasteImage are provided, onPaste takes precedence.
*/
onPasteImage?: (file: File) => void;
}
export type TextareaProps = React.TextareaHTMLAttributes<HTMLTextAreaElement>
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
({ className, onPaste, onPasteImage, ...props }, ref) => {
const handlePaste = React.useCallback(
async (e: React.ClipboardEvent<HTMLTextAreaElement>) => {
// If onPaste is provided, use it and skip image handling
if (onPaste) {
onPaste(e);
return;
}
// If onPasteImage is provided, handle image pasting
if (onPasteImage) {
const items = e.clipboardData?.items;
if (!items) return;
for (let i = 0; i < items.length; i++) {
const item = items[i];
// Check if the item is an image
if (item.type.startsWith('image/')) {
e.preventDefault(); // Prevent default paste behavior for images
const file = item.getAsFile();
if (file) {
// Generate a filename with timestamp
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const extension = file.type.split('/')[1] || 'png';
const filename = `pasted-image-${timestamp}.${extension}`;
// Create a new File object with the generated name
const namedFile = new File([file], filename, { type: file.type });
// Call the onPasteImage callback
onPasteImage(namedFile);
}
break; // Only handle the first image found
}
}
}
},
[onPaste, onPasteImage]
);
({ className, ...props }, ref) => {
return (
<textarea
className={cn(
@@ -60,7 +13,6 @@ const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
className
)}
ref={ref}
onPaste={onPaste || onPasteImage ? handlePaste : undefined}
{...props}
/>
)
-1
View File
@@ -36,7 +36,6 @@ export interface AISettingsContextType {
setMCPServer: (name: string, server: MCPServer) => void;
removeMCPServer: (name: string) => void;
isConfigured: boolean;
isLoading: boolean;
}
export const AISettingsContext = createContext<AISettingsContextType | undefined>(undefined);
+2 -11
View File
@@ -9,13 +9,6 @@ export interface RelayMetadata {
updatedAt: number;
}
export interface GraspMetadata {
/** List of grasp server relays */
relays: { url: string }[];
/** Unix timestamp of when the grasp list was last updated */
updatedAt: number;
}
export interface ProjectTemplate {
/** Template name */
name: string;
@@ -30,8 +23,6 @@ export interface AppConfig {
theme: Theme;
/** NIP-65 relay list metadata */
relayMetadata: RelayMetadata;
/** NIP-34 grasp server list metadata */
graspMetadata: GraspMetadata;
/** Available project templates */
templates: ProjectTemplate[];
/** ESM CDN URL for package imports */
@@ -40,8 +31,6 @@ export interface AppConfig {
corsProxy: string;
/** Favicon URL template (e.g., "https://external-content.duckduckgo.com/ip3/{hostname}.ico") */
faviconUrl: string;
/** Nostr Git web URL template (e.g., "https://nostrhub.io/{naddr}") */
ngitWebUrl: string;
/** Preview domain for iframe sandboxing (e.g., "local-shakespeare.dev") */
previewDomain: string;
/** Selected language */
@@ -50,6 +39,8 @@ export interface AppConfig {
showcaseEnabled: boolean;
/** Npub of the showcase moderator */
showcaseModerator: string;
/** Nostr Git Servers (hostnames) */
ngitServers: string[];
/** VFS path for projects directory */
fsPathProjects: string;
/** VFS path for config directory */
+15 -7
View File
@@ -1,15 +1,20 @@
import { createContext } from 'react';
export interface GitCredential {
id: string; // UUID generated with crypto.randomUUID()
name: string; // Display name for the credential
origin: string; // Full origin URL (e.g., "https://github.com")
username: string;
password: string;
}
export interface GitHostToken {
token: string;
username?: string;
scopes?: string[];
createdAt?: number;
}
export interface GitSettings {
credentials: GitCredential[];
credentials: Record<string, GitCredential>; // keyed by origin
hostTokens: Record<string, GitHostToken>; // keyed by host domain (e.g., 'github.com')
name?: string;
email?: string;
coAuthorEnabled?: boolean;
@@ -18,9 +23,12 @@ export interface GitSettings {
export interface GitSettingsContextType {
settings: GitSettings;
updateSettings: (settings: Partial<GitSettings>) => void;
addCredential: (credential: GitCredential) => void;
removeCredential: (id: string) => void;
setCredentials: (credentials: GitCredential[]) => void;
addCredential: (origin: string, credential: GitCredential) => void;
removeCredential: (origin: string) => void;
updateCredential: (origin: string, credential: Partial<GitCredential>) => void;
addHostToken: (host: string, token: GitHostToken) => void;
removeHostToken: (host: string) => void;
updateHostToken: (host: string, token: Partial<GitHostToken>) => void;
isConfigured: boolean;
isInitialized: boolean;
}
+2 -20
View File
@@ -64,14 +64,10 @@ describe('useGenerateProjectInfo', () => {
esmUrl: 'https://esm.sh',
corsProxy: 'https://proxy.example.com/{href}',
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'local-shakespeare.dev',
showcaseEnabled: true,
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
graspMetadata: {
relays: [{ url: 'wss://git.shakespeare.diy/' }, { url: 'wss://relay.ngit.dev/' }],
updatedAt: 0,
},
ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'],
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
@@ -130,7 +126,6 @@ describe('useGenerateProjectInfo', () => {
mockUseAISettings.mockReturnValue({
settings: { providers: [], recentlyUsedModels: [], mcpServers: {} },
isConfigured: false,
isLoading: false,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
@@ -150,7 +145,6 @@ describe('useGenerateProjectInfo', () => {
mockUseAISettings.mockReturnValue({
settings: { providers: [], recentlyUsedModels: [], mcpServers: {} },
isConfigured: false,
isLoading: false,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
@@ -177,7 +171,6 @@ describe('useGenerateProjectInfo', () => {
mcpServers: {}
},
isConfigured: true,
isLoading: false,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
@@ -204,7 +197,6 @@ describe('useGenerateProjectInfo', () => {
mcpServers: {}
},
isConfigured: true,
isLoading: false,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
@@ -225,14 +217,10 @@ describe('useGenerateProjectInfo', () => {
esmUrl: 'https://esm.sh',
corsProxy: 'https://proxy.example.com/{href}',
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'local-shakespeare.dev',
showcaseEnabled: true,
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
graspMetadata: {
relays: [{ url: 'wss://git.shakespeare.diy/' }, { url: 'wss://relay.ngit.dev/' }],
updatedAt: 0,
},
ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'],
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
@@ -264,7 +252,6 @@ describe('useGenerateProjectInfo', () => {
mcpServers: {}
},
isConfigured: true,
isLoading: false,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
@@ -306,7 +293,6 @@ describe('useGenerateProjectInfo', () => {
mcpServers: {}
},
isConfigured: true,
isLoading: false,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
@@ -360,7 +346,6 @@ describe('useGenerateProjectInfo', () => {
mcpServers: {}
},
isConfigured: true,
isLoading: false,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
@@ -397,7 +382,6 @@ describe('useGenerateProjectInfo', () => {
mcpServers: {}
},
isConfigured: true,
isLoading: false,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
@@ -436,7 +420,6 @@ describe('useGenerateProjectInfo', () => {
mcpServers: {}
},
isConfigured: true,
isLoading: false,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
@@ -469,7 +452,6 @@ describe('useGenerateProjectInfo', () => {
mcpServers: {}
},
isConfigured: true,
isLoading: false,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
+1 -5
View File
@@ -41,11 +41,10 @@ function createWrapper(corsProxy: string) {
esmUrl: 'https://esm.test',
corsProxy,
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'local-test.dev',
showcaseEnabled: true,
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
graspMetadata: { relays: [{ url: 'wss://git.shakespeare.diy/' }, { url: 'wss://relay.ngit.dev/' }], updatedAt: 0 },
ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'],
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
@@ -94,7 +93,6 @@ describe('useGit', () => {
nostr: mockNostr,
corsProxy: 'https://cors.isomorphic-git.org',
ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'],
onAuth: expect.any(Function),
});
expect(result.current).toEqual({ git: expect.any(Object) });
});
@@ -109,7 +107,6 @@ describe('useGit', () => {
nostr: mockNostr,
corsProxy: 'https://custom-cors.example.com',
ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'],
onAuth: expect.any(Function),
});
expect(result.current).toEqual({ git: expect.any(Object) });
});
@@ -124,7 +121,6 @@ describe('useGit', () => {
nostr: mockNostr,
corsProxy: 'https://cors.isomorphic-git.org',
ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'],
onAuth: expect.any(Function),
});
// Rerender with a different wrapper (different CORS proxy)
+4 -32
View File
@@ -1,11 +1,8 @@
import { useCallback, useMemo } from 'react';
import { useMemo } from 'react';
import { Git } from '@/lib/git';
import { useFS } from '@/hooks/useFS';
import { useNostr } from '@nostrify/react';
import { useAppContext } from '@/hooks/useAppContext';
import { findCredentialsForRepo } from '@/lib/gitCredentials';
import { useGitSettings } from './useGitSettings';
import { useCurrentUser } from './useCurrentUser';
/**
* Hook that provides a Git instance configured with the virtual filesystem
@@ -13,38 +10,13 @@ import { useCurrentUser } from './useCurrentUser';
*/
export function useGit(): { git: Git } {
const { fs } = useFS();
const { user } = useCurrentUser();
const { nostr } = useNostr();
const { config } = useAppContext();
const { settings } = useGitSettings();
const { corsProxy, graspMetadata } = config;
const ngitServers = useMemo(() => {
// Extract hostnames from grasp relay URLs for backwards compatibility with Git class
return graspMetadata.relays.map(r => {
try {
const url = new URL(r.url);
return url.hostname;
} catch {
return undefined;
}
}).filter((hostname): hostname is string => Boolean(hostname));
}, [graspMetadata.relays]);
const onAuth = useCallback((url: string) => {
return findCredentialsForRepo(url, settings.credentials);
}, [settings.credentials]);
const { corsProxy, ngitServers } = config;
const git = useMemo(() => {
return new Git({
fs,
nostr,
corsProxy,
ngitServers,
onAuth,
signer: user?.signer,
});
}, [fs, nostr, corsProxy, ngitServers, onAuth, user?.signer]);
return new Git({ fs, nostr, corsProxy, ngitServers });
}, [fs, nostr, corsProxy, ngitServers]);
return { git };
}
+720
View File
@@ -0,0 +1,720 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { renderHook, waitFor } from '@testing-library/react';
import { useGitFetch } from './useGitFetch';
import { TestApp } from '@/test/TestApp';
// Create mocks that can be reconfigured per test
const mockGit = {
findRoot: vi.fn(),
listRemotes: vi.fn(),
currentBranch: vi.fn(),
resolveRef: vi.fn(),
fetch: vi.fn(),
};
const mockToast = vi.fn();
const mockInvalidateQueries = vi.fn();
// Mock the git operations
vi.mock('./useGit', () => ({
useGit: () => ({
git: mockGit,
}),
}));
vi.mock('./useGitSettings', () => ({
useGitSettings: () => ({
settings: {
credentials: [],
},
}),
}));
vi.mock('./useFSPaths', () => ({
useFSPaths: () => ({
projectsPath: '/projects',
}),
}));
vi.mock('./useToast', () => ({
useToast: () => ({
toast: mockToast,
}),
}));
// Mock QueryClient to track invalidateQueries calls
vi.mock('@tanstack/react-query', async () => {
const actual = await vi.importActual('@tanstack/react-query');
return {
...actual,
useQueryClient: () => ({
invalidateQueries: mockInvalidateQueries,
}),
};
});
describe('useGitFetch', () => {
beforeEach(() => {
vi.clearAllMocks();
mockToast.mockClear();
mockInvalidateQueries.mockClear();
});
it('returns null state when projectId is null', async () => {
const { result } = renderHook(() => useGitFetch(null), {
wrapper: TestApp,
});
// When projectId is null, the query is disabled and won't fetch
// So we just check the initial state
expect(result.current.data).toBeUndefined();
expect(result.current.isLoading).toBe(false);
expect(result.current.isSuccess).toBe(false);
});
it('fetches remote updates successfully when default branch is checked out', async () => {
// Setup mocks for default branch scenario
mockGit.findRoot.mockResolvedValue('/projects/test-project');
mockGit.listRemotes.mockResolvedValue([
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
]);
mockGit.currentBranch.mockResolvedValue('main');
mockGit.fetch.mockResolvedValue(undefined);
// Mock resolveRef calls in order:
// 1. Read symbolic ref for default branch (returns the ref path)
// 2. Get default branch OID before fetch
// 3. Get current branch OID before fetch
// 4. Get default branch OID after fetch
// 5. Get current branch OID after fetch
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
.mockResolvedValueOnce('abc123') // before default
.mockResolvedValueOnce('abc123') // before current (same as default)
.mockResolvedValueOnce('abc123') // after default
.mockResolvedValueOnce('abc123'); // after current (same as default)
const { result } = renderHook(() => useGitFetch('test-project'), {
wrapper: TestApp,
});
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
expect(result.current.data).toMatchObject({
defaultBranch: 'main',
currentBranch: 'main',
remoteUrl: 'https://github.com/test/repo.git',
hasChanges: false,
});
// Verify fetch was called
expect(mockGit.fetch).toHaveBeenCalledWith(
expect.objectContaining({
dir: '/projects/test-project',
remote: 'origin',
})
);
});
it('fetches remote updates successfully when non-default branch is checked out', async () => {
// Setup mocks for non-default branch scenario
mockGit.findRoot.mockResolvedValue('/projects/test-project');
mockGit.listRemotes.mockResolvedValue([
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
]);
mockGit.currentBranch.mockResolvedValue('feature-branch');
mockGit.fetch.mockResolvedValue(undefined);
// Mock resolveRef calls in order:
// 1. Read symbolic ref for default branch (returns the ref path)
// 2. Get default branch OID before fetch
// 3. Get current branch OID before fetch
// 4. Get default branch OID after fetch
// 5. Get current branch OID after fetch
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
.mockResolvedValueOnce('abc123') // before default (main)
.mockResolvedValueOnce('def456') // before current (feature-branch)
.mockResolvedValueOnce('abc123') // after default (main)
.mockResolvedValueOnce('def456'); // after current (feature-branch)
const { result } = renderHook(() => useGitFetch('test-project'), {
wrapper: TestApp,
});
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
expect(result.current.data).toMatchObject({
defaultBranch: 'main',
currentBranch: 'feature-branch',
remoteUrl: 'https://github.com/test/repo.git',
hasChanges: false,
});
// Verify fetch was called
expect(mockGit.fetch).toHaveBeenCalledWith(
expect.objectContaining({
dir: '/projects/test-project',
remote: 'origin',
})
);
});
it('detects changes on default branch when checked out', async () => {
// Setup mocks
mockGit.findRoot.mockResolvedValue('/projects/test-project');
mockGit.listRemotes.mockResolvedValue([
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
]);
mockGit.currentBranch.mockResolvedValue('main');
mockGit.fetch.mockResolvedValue(undefined);
// Mock resolveRef to simulate changes on default branch
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
.mockResolvedValueOnce('abc123') // before default
.mockResolvedValueOnce('abc123') // before current (same as default)
.mockResolvedValueOnce('xyz789') // after default (changed!)
.mockResolvedValueOnce('xyz789'); // after current (changed!)
const { result } = renderHook(() => useGitFetch('test-project'), {
wrapper: TestApp,
});
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
expect(result.current.data).toMatchObject({
defaultBranch: 'main',
currentBranch: 'main',
hasChanges: true, // Changes detected on default branch
});
});
it('detects changes on non-default branch when checked out', async () => {
// Setup mocks
mockGit.findRoot.mockResolvedValue('/projects/test-project');
mockGit.listRemotes.mockResolvedValue([
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
]);
mockGit.currentBranch.mockResolvedValue('feature-branch');
mockGit.fetch.mockResolvedValue(undefined);
// Mock resolveRef to simulate changes on non-default branch
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
.mockResolvedValueOnce('abc123') // before default
.mockResolvedValueOnce('def456') // before current
.mockResolvedValueOnce('abc123') // after default (no change)
.mockResolvedValueOnce('xyz789'); // after current (changed!)
const { result } = renderHook(() => useGitFetch('test-project'), {
wrapper: TestApp,
});
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
expect(result.current.data).toMatchObject({
defaultBranch: 'main',
currentBranch: 'feature-branch',
hasChanges: true, // Changes detected on current branch
});
});
it('detects changes on both default and non-default branches', async () => {
// Setup mocks
mockGit.findRoot.mockResolvedValue('/projects/test-project');
mockGit.listRemotes.mockResolvedValue([
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
]);
mockGit.currentBranch.mockResolvedValue('feature-branch');
mockGit.fetch.mockResolvedValue(undefined);
// Mock resolveRef to simulate changes on both branches
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
.mockResolvedValueOnce('abc123') // before default
.mockResolvedValueOnce('def456') // before current
.mockResolvedValueOnce('new111') // after default (changed!)
.mockResolvedValueOnce('new222'); // after current (changed!)
const { result } = renderHook(() => useGitFetch('test-project'), {
wrapper: TestApp,
});
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
expect(result.current.data).toMatchObject({
defaultBranch: 'main',
currentBranch: 'feature-branch',
hasChanges: true, // Changes detected on both branches
});
});
it('detects changes on default branch when non-default branch is checked out', async () => {
// Setup mocks
mockGit.findRoot.mockResolvedValue('/projects/test-project');
mockGit.listRemotes.mockResolvedValue([
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
]);
mockGit.currentBranch.mockResolvedValue('feature-branch');
mockGit.fetch.mockResolvedValue(undefined);
// Mock resolveRef to simulate changes on default branch only
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
.mockResolvedValueOnce('abc123') // before default
.mockResolvedValueOnce('def456') // before current
.mockResolvedValueOnce('xyz789') // after default (changed!)
.mockResolvedValueOnce('def456'); // after current (no change)
const { result } = renderHook(() => useGitFetch('test-project'), {
wrapper: TestApp,
});
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
expect(result.current.data).toMatchObject({
defaultBranch: 'main',
currentBranch: 'feature-branch',
hasChanges: true, // Changes detected on default branch
});
});
it('can be manually refetched', async () => {
// Setup mocks
mockGit.findRoot.mockResolvedValue('/projects/test-project');
mockGit.listRemotes.mockResolvedValue([
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
]);
mockGit.currentBranch.mockResolvedValue('main');
mockGit.fetch.mockResolvedValue(undefined);
// Mock resolveRef for initial fetch
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123');
const { result } = renderHook(() => useGitFetch('test-project'), {
wrapper: TestApp,
});
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
const firstFetchTime = result.current.data?.fetchedAt;
// Setup mocks for refetch
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123');
// Manually trigger refetch
await result.current.refetch();
await waitFor(() => {
expect(result.current.data?.fetchedAt).toBeGreaterThanOrEqual(firstFetchTime || 0);
});
// Verify fetch was called twice (initial + refetch)
expect(mockGit.fetch).toHaveBeenCalledTimes(2);
});
describe('Toast Notifications', () => {
it('shows toast when default branch changes (on default branch)', async () => {
// Setup mocks for initial fetch (no changes)
mockGit.findRoot.mockResolvedValue('/projects/test-project');
mockGit.listRemotes.mockResolvedValue([
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
]);
mockGit.currentBranch.mockResolvedValue('main');
mockGit.fetch.mockResolvedValue(undefined);
// Initial fetch - no changes
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123');
const { result } = renderHook(() => useGitFetch('test-project'), {
wrapper: TestApp,
});
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
// No toast on initial load
expect(mockToast).not.toHaveBeenCalled();
// Setup for refetch with changes
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('xyz789') // Changed!
.mockResolvedValueOnce('xyz789');
// Trigger refetch
await result.current.refetch();
await waitFor(() => {
expect(mockToast).toHaveBeenCalledTimes(1);
});
// Verify toast message
expect(mockToast).toHaveBeenCalledWith({
title: 'Remote changes detected',
description: 'The main branch has new commits available.',
variant: 'default',
});
// Verify git status was invalidated
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
(call) => call[0]?.queryKey?.[0] === 'git-status'
);
expect(gitStatusCalls).toHaveLength(1);
expect(gitStatusCalls[0][0]).toEqual({
queryKey: ['git-status', 'test-project'],
});
});
it('shows toast when non-default branch changes (on non-default branch)', async () => {
// Setup mocks for initial fetch (no changes)
mockGit.findRoot.mockResolvedValue('/projects/test-project');
mockGit.listRemotes.mockResolvedValue([
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
]);
mockGit.currentBranch.mockResolvedValue('feature-branch');
mockGit.fetch.mockResolvedValue(undefined);
// Initial fetch - no changes
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('def456')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('def456');
const { result } = renderHook(() => useGitFetch('test-project'), {
wrapper: TestApp,
});
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
// No toast on initial load
expect(mockToast).not.toHaveBeenCalled();
// Setup for refetch with changes on feature branch
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('def456')
.mockResolvedValueOnce('abc123') // main unchanged
.mockResolvedValueOnce('xyz789'); // feature-branch changed!
// Trigger refetch
await result.current.refetch();
await waitFor(() => {
expect(mockToast).toHaveBeenCalledTimes(1);
});
// Verify toast message for feature branch
expect(mockToast).toHaveBeenCalledWith({
title: 'Remote changes detected',
description: 'The feature-branch branch has new commits available.',
variant: 'default',
});
// Verify git status was invalidated
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
(call) => call[0]?.queryKey?.[0] === 'git-status'
);
expect(gitStatusCalls).toHaveLength(1);
expect(gitStatusCalls[0][0]).toEqual({
queryKey: ['git-status', 'test-project'],
});
});
it('shows toast when default branch changes (on non-default branch)', async () => {
// Setup mocks for initial fetch (no changes)
mockGit.findRoot.mockResolvedValue('/projects/test-project');
mockGit.listRemotes.mockResolvedValue([
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
]);
mockGit.currentBranch.mockResolvedValue('feature-branch');
mockGit.fetch.mockResolvedValue(undefined);
// Initial fetch - no changes
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('def456')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('def456');
const { result } = renderHook(() => useGitFetch('test-project'), {
wrapper: TestApp,
});
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
// No toast on initial load
expect(mockToast).not.toHaveBeenCalled();
// Setup for refetch with changes on main branch only
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('def456')
.mockResolvedValueOnce('xyz789') // main changed!
.mockResolvedValueOnce('def456'); // feature-branch unchanged
// Trigger refetch
await result.current.refetch();
await waitFor(() => {
expect(mockToast).toHaveBeenCalledTimes(1);
});
// Verify toast message for main branch
expect(mockToast).toHaveBeenCalledWith({
title: 'Remote changes detected',
description: 'The main branch has new commits available.',
variant: 'default',
});
// Verify git status was invalidated
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
(call) => call[0]?.queryKey?.[0] === 'git-status'
);
expect(gitStatusCalls).toHaveLength(1);
expect(gitStatusCalls[0][0]).toEqual({
queryKey: ['git-status', 'test-project'],
});
});
it('shows two toasts when both branches change (on non-default branch)', async () => {
// Setup mocks for initial fetch (no changes)
mockGit.findRoot.mockResolvedValue('/projects/test-project');
mockGit.listRemotes.mockResolvedValue([
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
]);
mockGit.currentBranch.mockResolvedValue('feature-branch');
mockGit.fetch.mockResolvedValue(undefined);
// Initial fetch - no changes
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('def456')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('def456');
const { result } = renderHook(() => useGitFetch('test-project'), {
wrapper: TestApp,
});
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
// No toast on initial load
expect(mockToast).not.toHaveBeenCalled();
// Setup for refetch with changes on both branches
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('def456')
.mockResolvedValueOnce('new111') // main changed!
.mockResolvedValueOnce('new222'); // feature-branch changed!
// Trigger refetch
await result.current.refetch();
await waitFor(() => {
expect(mockToast).toHaveBeenCalledTimes(2);
});
// Verify both toast messages
expect(mockToast).toHaveBeenCalledWith({
title: 'Remote changes detected',
description: 'The main branch has new commits available.',
variant: 'default',
});
expect(mockToast).toHaveBeenCalledWith({
title: 'Remote changes detected',
description: 'The feature-branch branch has new commits available.',
variant: 'default',
});
// Verify git status was invalidated twice (once per toast)
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
(call) => call[0]?.queryKey?.[0] === 'git-status'
);
expect(gitStatusCalls).toHaveLength(2);
});
it('does not show toast on initial load', async () => {
// Setup mocks
mockGit.findRoot.mockResolvedValue('/projects/test-project');
mockGit.listRemotes.mockResolvedValue([
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
]);
mockGit.currentBranch.mockResolvedValue('main');
mockGit.fetch.mockResolvedValue(undefined);
// Initial fetch with changes detected in the fetch itself
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('xyz789') // Changed from before to after fetch
.mockResolvedValueOnce('xyz789');
const { result } = renderHook(() => useGitFetch('test-project'), {
wrapper: TestApp,
});
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
// Should report changes in data
expect(result.current.data?.hasChanges).toBe(true);
// But no toast on initial load
expect(mockToast).not.toHaveBeenCalled();
});
it('does not show toast when no changes detected', async () => {
// Setup mocks for initial fetch
mockGit.findRoot.mockResolvedValue('/projects/test-project');
mockGit.listRemotes.mockResolvedValue([
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
]);
mockGit.currentBranch.mockResolvedValue('main');
mockGit.fetch.mockResolvedValue(undefined);
// Initial fetch - no changes
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123');
const { result } = renderHook(() => useGitFetch('test-project'), {
wrapper: TestApp,
});
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
// Setup for refetch with no changes
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123');
// Trigger refetch
await result.current.refetch();
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
// No toast should be shown
expect(mockToast).not.toHaveBeenCalled();
// Verify git status was not invalidated (filter out other queries like 'nostr')
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
(call) => call[0]?.queryKey?.[0] === 'git-status'
);
expect(gitStatusCalls).toHaveLength(0);
});
it('does not show duplicate toast for same branch when default equals current', async () => {
// Setup mocks for initial fetch
mockGit.findRoot.mockResolvedValue('/projects/test-project');
mockGit.listRemotes.mockResolvedValue([
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
]);
mockGit.currentBranch.mockResolvedValue('main');
mockGit.fetch.mockResolvedValue(undefined);
// Initial fetch - no changes
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123');
const { result } = renderHook(() => useGitFetch('test-project'), {
wrapper: TestApp,
});
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
// Setup for refetch with changes (both default and current are 'main')
mockGit.resolveRef
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('abc123')
.mockResolvedValueOnce('xyz789')
.mockResolvedValueOnce('xyz789');
// Trigger refetch
await result.current.refetch();
await waitFor(() => {
expect(mockToast).toHaveBeenCalledTimes(1);
});
// Should only show one toast (for default branch), not two
expect(mockToast).toHaveBeenCalledWith({
title: 'Remote changes detected',
description: 'The main branch has new commits available.',
variant: 'default',
});
// Should only invalidate once
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
(call) => call[0]?.queryKey?.[0] === 'git-status'
);
expect(gitStatusCalls).toHaveLength(1);
});
});
});
+370
View File
@@ -0,0 +1,370 @@
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useGit } from './useGit';
import { useFSPaths } from './useFSPaths';
import { useGitSettings } from './useGitSettings';
import { useToast } from './useToast';
import { findCredentialsForRepo } from '@/lib/gitCredentials';
import { useEffect, useRef } from 'react';
interface FetchResult {
defaultBranch: string | null;
defaultBranchOid: string | null;
currentBranch: string | null;
currentBranchOid: string | null;
fetchedAt: number;
hasChanges: boolean;
remoteUrl: string | null;
}
/**
* Hook to fetch updates from remote repository and detect changes.
* Polls every 60 seconds and shows toast notifications when changes are detected.
*
* @param projectId - The project ID to fetch for
* @returns Query result with manual refetch capability
*/
export function useGitFetch(projectId: string | null) {
const { git } = useGit();
const { projectsPath } = useFSPaths();
const { settings } = useGitSettings();
const { toast } = useToast();
const queryClient = useQueryClient();
// Track previous state to detect changes
const previousStateRef = useRef<{
defaultBranchOid: string | null;
currentBranchOid: string | null;
dataUpdatedAt: number;
} | null>(null);
const query = useQuery({
queryKey: ['git-fetch', projectId],
queryFn: async (): Promise<FetchResult> => {
console.log('=== GIT FETCH STARTING ===');
console.log('Project ID:', projectId);
if (!projectId) {
console.log('No project ID, returning empty result');
return {
defaultBranch: null,
defaultBranchOid: null,
currentBranch: null,
currentBranchOid: null,
fetchedAt: Date.now(),
hasChanges: false,
remoteUrl: null,
};
}
try {
const cwd = `${projectsPath}/${projectId}`;
console.log('Working directory:', cwd);
// Check if we're in a git repository
try {
await git.findRoot({ filepath: cwd });
console.log('Git repository found');
} catch {
console.log('Not a git repository');
return {
defaultBranch: null,
defaultBranchOid: null,
currentBranch: null,
currentBranchOid: null,
fetchedAt: Date.now(),
hasChanges: false,
remoteUrl: null,
};
}
// Get remotes
const remotes = await git.listRemotes({ dir: cwd });
console.log('Remotes found:', remotes);
if (remotes.length === 0) {
console.log('No remotes configured');
return {
defaultBranch: null,
defaultBranchOid: null,
currentBranch: null,
currentBranchOid: null,
fetchedAt: Date.now(),
hasChanges: false,
remoteUrl: null,
};
}
const remote = remotes[0]; // Use first remote (usually 'origin')
const remoteUrl = remote.url || null;
console.log('Using remote:', remote.remote, 'URL:', remoteUrl);
if (!remoteUrl) {
console.log('No remote URL found');
return {
defaultBranch: null,
defaultBranchOid: null,
currentBranch: null,
currentBranchOid: null,
fetchedAt: Date.now(),
hasChanges: false,
remoteUrl: null,
};
}
// Get credentials for authentication
const credentials = findCredentialsForRepo(remoteUrl, settings.credentials);
console.log('Credentials found:', !!credentials);
// Get current branch before fetch
let currentBranch: string | null = null;
try {
const branch = await git.currentBranch({
dir: cwd,
fullname: false,
});
currentBranch = (branch && branch.trim() !== '') ? branch : null;
console.log('Current branch:', currentBranch);
} catch (error) {
console.warn('Could not get current branch:', error);
}
// Store OIDs before fetch
let beforeDefaultOid: string | null = null;
let beforeCurrentOid: string | null = null;
// Get default branch from local symbolic ref
let defaultBranch: string | null = null;
try {
console.log('Reading default branch from local symbolic ref...');
// Read the symbolic ref file directly
// The file contains something like: "ref: refs/remotes/origin/main"
try {
const symbolicRefContent = await git.resolveRef({
dir: cwd,
ref: `remotes/${remote.remote}/HEAD`,
depth: 1,
});
// Remove "ref: " prefix and extract the branch name
// Content looks like: "ref: refs/remotes/origin/main"
const refValue = symbolicRefContent.replace(/^ref:\s*/, '').trim();
const match = refValue.match(/refs\/remotes\/[^/]+\/(.+)/);
if (match) {
defaultBranch = match[1].trim();
console.log('Default branch from local symbolic ref:', defaultBranch);
} else {
console.log('Could not get default branch from local symbolic ref value:', refValue);
}
} catch {
console.log('No local symbolic ref found, will be set after fetch');
}
// If we have a default branch, try to get its OID before fetch
if (defaultBranch) {
try {
beforeDefaultOid = await git.resolveRef({
dir: cwd,
ref: `${remote.remote}/${defaultBranch}`,
});
console.log('Default branch OID before fetch:', beforeDefaultOid);
} catch {
console.log('Remote default branch not in local repo yet');
}
}
} catch (error) {
console.warn('Could not read default branch from local data:', error);
}
// Get current branch OID before fetch
if (currentBranch) {
try {
beforeCurrentOid = await git.resolveRef({
dir: cwd,
ref: `${remote.remote}/${currentBranch}`,
});
console.log('Current branch OID before fetch:', beforeCurrentOid);
} catch {
console.log('Remote current branch not in local repo yet');
}
}
// Perform fetch
try {
console.log('Fetching from remote...');
await git.fetch({
dir: cwd,
remote: remote.remote,
...(credentials && {
onAuth: () => ({
username: credentials.username,
password: credentials.password,
}),
}),
});
console.log('Fetch completed successfully');
} catch (error) {
console.error('Failed to fetch from remote:', error);
throw error;
}
// Get OIDs after fetch
let afterDefaultOid: string | null = null;
let afterCurrentOid: string | null = null;
// Re-read default branch from symbolic ref in case it was just created by fetch
if (!defaultBranch) {
try {
const symbolicRefContent = await git.resolveRef({
dir: cwd,
ref: `remotes/${remote.remote}/HEAD`,
depth: 1,
});
// Remove "ref: " prefix and extract the branch name
// Content looks like: "ref: refs/remotes/origin/main"
const refValue = symbolicRefContent.replace(/^ref:\s*/, '').trim();
const match = refValue.match(/refs\/remotes\/[^/]+\/(.+)/);
if (match) {
defaultBranch = match[1].trim();
console.log('Default branch from local symbolic ref:', defaultBranch);
}
} catch {
console.log('No local symbolic ref found, will be set after fetch');
}
}
if (defaultBranch) {
try {
afterDefaultOid = await git.resolveRef({
dir: cwd,
ref: `${remote.remote}/${defaultBranch}`,
});
console.log('Default branch OID after fetch:', afterDefaultOid);
} catch {
console.log('Could not resolve default branch after fetch');
}
}
if (currentBranch) {
try {
afterCurrentOid = await git.resolveRef({
dir: cwd,
ref: `${remote.remote}/${currentBranch}`,
});
console.log('Current branch OID after fetch:', afterCurrentOid);
} catch {
console.log('Could not resolve current branch after fetch');
}
}
// Detect changes
const defaultBranchChanged = beforeDefaultOid !== null &&
afterDefaultOid !== null &&
beforeDefaultOid !== afterDefaultOid;
const currentBranchChanged = beforeCurrentOid !== null &&
afterCurrentOid !== null &&
beforeCurrentOid !== afterCurrentOid &&
currentBranch !== defaultBranch; // Don't double-report if they're the same
const hasChanges = defaultBranchChanged || currentBranchChanged;
console.log('Changes detected:', {
defaultBranchChanged,
currentBranchChanged,
hasChanges,
});
const result = {
defaultBranch,
defaultBranchOid: afterDefaultOid,
currentBranch,
currentBranchOid: afterCurrentOid,
fetchedAt: Date.now(),
hasChanges,
remoteUrl,
};
console.log('=== GIT FETCH COMPLETE ===');
console.log('Result:', result);
return result;
} catch (error) {
console.error('Error fetching from remote:', error);
throw error;
}
},
enabled: !!projectId,
refetchInterval: 60000, // Fetch every 60 seconds
staleTime: 30000, // Consider data stale after 30 seconds
retry: 1, // Only retry once on failure
});
// Show toast notifications when changes are detected
useEffect(() => {
if (!query.data || !query.isSuccess || query.dataUpdatedAt === undefined) {
return;
}
const currentState = {
defaultBranchOid: query.data.defaultBranchOid,
currentBranchOid: query.data.currentBranchOid,
dataUpdatedAt: query.dataUpdatedAt,
};
// Initialize on first load or after component remount
if (previousStateRef.current === null) {
previousStateRef.current = currentState;
return;
}
const prevState = previousStateRef.current;
// Skip if this is the same data we've already seen (same dataUpdatedAt timestamp)
// This prevents showing toasts when navigating back to a project with cached data
if (prevState.dataUpdatedAt === currentState.dataUpdatedAt) {
return;
}
// Detect default branch changes
const defaultBranchChanged =
prevState.defaultBranchOid !== null &&
currentState.defaultBranchOid !== null &&
prevState.defaultBranchOid !== currentState.defaultBranchOid;
// Detect current branch changes
const currentBranchChanged =
prevState.currentBranchOid !== null &&
currentState.currentBranchOid !== null &&
prevState.currentBranchOid !== currentState.currentBranchOid &&
query.data.currentBranch !== query.data.defaultBranch;
// Show toast for default branch changes
if (defaultBranchChanged && query.data.defaultBranch) {
toast({
title: 'Remote changes detected',
description: `The ${query.data.defaultBranch} branch has new commits available.`,
variant: 'default',
});
// Invalidate git status to show new ahead/behind counts
queryClient.invalidateQueries({ queryKey: ['git-status', projectId] });
}
// Show toast for current branch changes (if different from default)
if (currentBranchChanged && query.data.currentBranch) {
toast({
title: 'Remote changes detected',
description: `The ${query.data.currentBranch} branch has ${query.data.currentBranchOid === null ? 'been deleted' : 'new commits available'}.`,
variant: 'default',
});
// Invalidate git status to show new ahead/behind counts
queryClient.invalidateQueries({ queryKey: ['git-status', projectId] });
}
// Update previous state
previousStateRef.current = currentState;
}, [query.data, query.isSuccess, query.dataUpdatedAt, toast, queryClient, projectId]);
return query;
}
+14 -7
View File
@@ -2,6 +2,7 @@ import { useCallback } from 'react';
import { useOAuth, type OAuthConfig, type OAuthResult } from './useOAuth';
import { useGitSettings } from './useGitSettings';
import { proxyUrl } from '@/lib/proxyUrl';
import type { GitHostToken } from '@/contexts/GitSettingsContext';
interface GitHubUserInfo {
login: string;
@@ -17,7 +18,7 @@ interface GitHubUserInfo {
* Uses the generic useOAuth hook with GitHub-specific configuration.
*/
export function useGitHubOAuth() {
const { addCredential, isInitialized } = useGitSettings();
const { addCredential, addHostToken, isInitialized } = useGitSettings();
// GitHub OAuth configuration
const config: OAuthConfig = {
@@ -70,17 +71,23 @@ export function useGitHubOAuth() {
return false;
}
// Store the credentials
addCredential({
id: crypto.randomUUID(),
name: 'GitHub',
origin: 'https://github.com',
// Store the credentials (legacy format for existing push/pull operations)
addCredential('https://github.com', {
username: result.username || 'git',
password: result.accessToken,
});
// Also store as host token for PR/contribution operations
const hostToken: GitHostToken = {
token: result.accessToken,
username: result.username || 'git',
scopes: result.scopes || [],
createdAt: Date.now(),
};
addHostToken('github.com', hostToken);
return true;
}, [oauth, addCredential, isInitialized]);
}, [oauth, addCredential, addHostToken, isInitialized]);
return {
...oauth,
+4
View File
@@ -91,6 +91,10 @@ export function usePlugins() {
dir: pluginDir,
singleBranch: true,
fastForward: true,
author: {
name: 'shakespeare.diy',
email: '[email protected]',
},
});
return pluginName;
+3 -7
View File
@@ -1,5 +1,5 @@
import { Decimal } from 'decimal.js';
import { useState, useMemo } from 'react';
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useAISettings } from '@/hooks/useAISettings';
import { useCurrentUser } from '@/hooks/useCurrentUser';
@@ -40,7 +40,7 @@ export function useProviderModels(): ModelFetchResult {
const [error, setError] = useState<string | null>(null);
const {
data,
data: models = [],
isLoading,
refetch,
} = useQuery({
@@ -56,7 +56,7 @@ export function useProviderModels(): ModelFetchResult {
// Fetch models with timeout
try {
const response = await openai.models.list({
signal: AbortSignal.timeout(8_000),
signal: AbortSignal.timeout(10_000),
});
// Transform models to our format
@@ -147,10 +147,6 @@ export function useProviderModels(): ModelFetchResult {
retry: false, // Don't retry on failure
});
// Memoize the models array to prevent unnecessary re-renders
// This ensures the same empty array reference is returned when there's no data
const models = useMemo(() => data ?? [], [data]);
return {
models,
isLoading,
+456
View File
@@ -0,0 +1,456 @@
import { useQuery } from '@tanstack/react-query';
import { useGitSettings } from '@/hooks/useGitSettings';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostr } from '@nostrify/react';
import { findCredentialsForRepo } from '@/lib/gitCredentials';
import { nip19 } from 'nostr-tools';
import type { NostrEvent } from '@nostrify/nostrify';
export interface PullRequest {
id: number | string;
number: number | string;
title: string;
state: 'open' | 'closed' | 'merged';
author: string;
authorPubkey?: string; // For Nostr patches
url: string;
createdAt: string;
sourceBranch: string;
targetBranch: string;
isOwner?: boolean; // Whether current user is the PR creator
}
interface RemoteInfo {
owner: string;
repo: string;
platform: 'github' | 'gitlab' | 'nostr';
apiUrl: string;
}
function parseRemoteUrl(url: string): RemoteInfo | null {
try {
// Nostr git: nostr://<pubkey>/<repo-id>
if (url.startsWith('nostr://')) {
const match = url.match(/^nostr:\/\/([^/]+)\/(.+)$/);
if (match) {
const pubkeyOrNpub = match[1];
const repo = match[2];
// Convert npub to hex if needed
let owner = pubkeyOrNpub;
if (pubkeyOrNpub.startsWith('npub1')) {
try {
const decoded = nip19.decode(pubkeyOrNpub);
if (decoded.type === 'npub') {
owner = decoded.data; // hex pubkey
}
} catch (err) {
console.error('Failed to decode npub:', err);
return null;
}
}
return { owner, repo, platform: 'nostr', apiUrl: '' };
}
}
// Normalize URL - remove .git suffix if present
const normalizedUrl = url.replace(/\.git$/, '');
let match;
let owner = '';
let repo = '';
let platform: 'github' | 'gitlab' = 'github';
let apiUrl = '';
// GitHub SSH: [email protected]:owner/repo
match = normalizedUrl.match(/git@github\.com:([^/]+)\/(.+)$/);
if (match) {
owner = match[1];
repo = match[2];
platform = 'github';
apiUrl = 'https://api.github.com';
}
// GitHub HTTPS: https://github.com/owner/repo
if (!match) {
match = normalizedUrl.match(/https?:\/\/github\.com\/([^/]+)\/(.+)$/);
if (match) {
owner = match[1];
repo = match[2];
platform = 'github';
apiUrl = 'https://api.github.com';
}
}
// GitLab SSH: [email protected]:owner/repo
if (!match) {
match = normalizedUrl.match(/git@gitlab\.com:([^/]+)\/(.+)$/);
if (match) {
owner = match[1];
repo = match[2];
platform = 'gitlab';
apiUrl = 'https://gitlab.com/api/v4';
}
}
// GitLab HTTPS: https://gitlab.com/owner/repo
if (!match) {
match = normalizedUrl.match(/https?:\/\/gitlab\.com\/([^/]+)\/(.+)$/);
if (match) {
owner = match[1];
repo = match[2];
platform = 'gitlab';
apiUrl = 'https://gitlab.com/api/v4';
}
}
if (owner && repo) {
return { owner, repo, platform, apiUrl };
}
return null;
} catch {
return null;
}
}
async function fetchGitHubPRs(info: RemoteInfo, token?: string, currentUsername?: string, isRepoOwner?: boolean): Promise<PullRequest[]> {
const url = `${info.apiUrl}/repos/${info.owner}/${info.repo}/pulls?state=open`;
const headers: Record<string, string> = {
'Accept': 'application/vnd.github.v3+json',
};
if (token) {
headers['Authorization'] = `token ${token}`;
}
const response = await fetch(url, { headers });
if (!response.ok) {
throw new Error(`Failed to fetch GitHub PRs: ${response.status}`);
}
const data = await response.json();
interface GitHubPR {
id: number;
number: number;
title: string;
state: string;
user: { login: string };
html_url: string;
created_at: string;
head: { ref: string };
base: { ref: string };
body?: string;
}
const allPRs = data.map((pr: GitHubPR) => ({
id: pr.id,
number: pr.number,
title: pr.title,
state: pr.state,
author: pr.user.login,
url: pr.html_url,
createdAt: pr.created_at,
sourceBranch: pr.head.ref,
targetBranch: pr.base.ref,
isOwner: pr.user.login === currentUsername,
}));
// If repo owner, return all PRs. Otherwise, return only user's PRs
if (isRepoOwner) {
return allPRs;
} else if (currentUsername) {
return allPRs.filter((pr: PullRequest) => pr.author === currentUsername);
}
return [];
}
async function fetchGitLabMRs(info: RemoteInfo, token?: string, currentUsername?: string, isRepoOwner?: boolean): Promise<PullRequest[]> {
// Get project ID first
const projectUrl = `${info.apiUrl}/projects/${encodeURIComponent(`${info.owner}/${info.repo}`)}`;
const projectHeaders: Record<string, string> = {};
if (token) {
projectHeaders['PRIVATE-TOKEN'] = token;
}
const projectResponse = await fetch(projectUrl, { headers: projectHeaders });
if (!projectResponse.ok) {
throw new Error(`Failed to fetch GitLab project: ${projectResponse.status}`);
}
const project = await projectResponse.json();
// Fetch merge requests
const mrUrl = `${info.apiUrl}/projects/${project.id}/merge_requests?state=opened`;
const mrHeaders: Record<string, string> = {};
if (token) {
mrHeaders['PRIVATE-TOKEN'] = token;
}
const response = await fetch(mrUrl, { headers: mrHeaders });
if (!response.ok) {
throw new Error(`Failed to fetch GitLab MRs: ${response.status}`);
}
const data = await response.json();
interface GitLabMR {
id: number;
iid: number;
title: string;
state: string;
author: { username: string };
web_url: string;
created_at: string;
source_branch: string;
target_branch: string;
description?: string;
}
const allMRs = data.map((mr: GitLabMR) => ({
id: mr.id,
number: mr.iid,
title: mr.title,
state: mr.state === 'opened' ? 'open' : mr.state,
author: mr.author.username,
url: mr.web_url,
createdAt: mr.created_at,
sourceBranch: mr.source_branch,
targetBranch: mr.target_branch,
isOwner: mr.author.username === currentUsername,
}));
// If repo owner, return all MRs. Otherwise, return only user's MRs
if (isRepoOwner) {
return allMRs;
} else if (currentUsername) {
return allMRs.filter((mr: PullRequest) => mr.author === currentUsername);
}
return [];
}
interface NostrInterface {
query: (filters: unknown[], options?: { signal?: AbortSignal }) => Promise<unknown[]>;
}
async function fetchNostrPatches(
info: RemoteInfo,
currentUserPubkey: string | undefined,
nostr: NostrInterface,
signal: AbortSignal,
isRepoOwner?: boolean
): Promise<PullRequest[]> {
console.log('=== FETCHING NOSTR PATCHES ===');
console.log('Repository:', `${info.owner}/${info.repo}`);
console.log('Current user pubkey:', currentUserPubkey);
console.log('Is repo owner:', isRepoOwner);
if (!currentUserPubkey && !isRepoOwner) {
console.log('No current user, returning empty array');
return [];
}
try {
// Build query filter based on whether user is repo owner or contributor
interface PatchFilter {
kinds: number[];
'#a': string[];
limit: number;
authors?: string[];
}
const filter: PatchFilter = {
kinds: [1617],
'#a': [`30617:${info.owner}:${info.repo}`],
limit: 50,
};
// If not repo owner, only fetch user's own patches
if (!isRepoOwner && currentUserPubkey) {
filter.authors = [currentUserPubkey];
}
console.log('Querying patches with filter:', filter);
const patches = await nostr.query([filter], { signal });
console.log(`Found ${patches.length} patches`);
if (patches.length > 0) {
console.log('Sample patch:', patches[0]);
}
// Query for status events (kind 1630-1633) to determine patch state
const patchIds = patches.map((p: NostrEvent) => p.id);
let statusEvents: NostrEvent[] = [];
if (patchIds.length > 0) {
const events = await nostr.query([
{
kinds: [1630, 1631, 1632, 1633], // Open, Applied/Merged, Closed, Draft
'#e': patchIds,
}
], { signal });
statusEvents = events as NostrEvent[];
console.log(`Found ${statusEvents.length} status events`);
}
// Build a map of patch ID to latest status
const patchStatus = new Map<string, string>();
statusEvents.forEach((statusEvent: NostrEvent) => {
const patchId = statusEvent.tags.find(t => t[0] === 'e' && t[3] === 'root')?.[1];
if (patchId) {
// Status event kinds: 1630=Open, 1631=Applied/Merged, 1632=Closed, 1633=Draft
const status = statusEvent.kind === 1631 ? 'merged' : statusEvent.kind === 1632 ? 'closed' : 'open';
// Only update if we don't have a status or this event is newer
const existing = patchStatus.get(patchId);
if (!existing || statusEvent.created_at > (statusEvents.find(e => e.tags.find(t => t[1] === patchId))?.created_at || 0)) {
patchStatus.set(patchId, status);
}
}
});
// Convert Nostr patches to PullRequest format
const pullRequests: PullRequest[] = patches.map((patch: NostrEvent) => {
const subject = patch.tags.find(t => t[0] === 'subject')?.[1] || 'Untitled patch';
// Get status from status events, default to 'open'
const state = patchStatus.get(patch.id) || 'open';
// Extract source/target branches from content if available
const contentLines = patch.content.split('\n');
let sourceBranch = 'unknown';
let targetBranch = 'main';
for (const line of contentLines) {
if (line.startsWith('From:')) {
sourceBranch = line.replace('From:', '').trim();
}
if (line.startsWith('To:')) {
targetBranch = line.replace('To:', '').trim();
}
}
return {
id: patch.id,
number: patch.id.slice(0, 8),
title: subject,
state: state as 'open' | 'closed' | 'merged',
author: nip19.npubEncode(patch.pubkey),
authorPubkey: patch.pubkey,
url: `nostr:${patch.id}`,
createdAt: new Date(patch.created_at * 1000).toISOString(),
sourceBranch,
targetBranch,
isOwner: patch.pubkey === currentUserPubkey,
};
});
console.log('Converted patches to PRs:', pullRequests);
return pullRequests;
} catch (error) {
console.error('Failed to fetch Nostr patches:', error);
throw error;
}
}
export function usePullRequests(remoteUrl?: string) {
const { settings } = useGitSettings();
const { user } = useCurrentUser();
const { nostr } = useNostr();
return useQuery({
queryKey: ['pull-requests', remoteUrl, user?.pubkey],
queryFn: async ({ signal }) => {
if (!remoteUrl) {
return [];
}
const remoteInfo = parseRemoteUrl(remoteUrl);
if (!remoteInfo) {
throw new Error('Invalid remote URL format');
}
// Determine if current user is the repo owner
let isRepoOwner = false;
let currentUsername: string | undefined;
if (remoteInfo.platform === 'nostr') {
// For Nostr, check if user's pubkey matches repo owner
isRepoOwner = user?.pubkey === remoteInfo.owner;
} else if (remoteInfo.platform === 'github') {
// For GitHub, fetch current username
const credentials = findCredentialsForRepo(remoteUrl, settings.credentials);
const token = credentials?.password;
if (token) {
try {
const userResponse = await fetch(`${remoteInfo.apiUrl}/user`, {
headers: {
'Authorization': `token ${token}`,
'Accept': 'application/vnd.github.v3+json',
},
});
if (userResponse.ok) {
const userData = await userResponse.json();
currentUsername = userData.login;
isRepoOwner = currentUsername === remoteInfo.owner;
}
} catch (error) {
console.warn('Failed to fetch current GitHub user:', error);
}
}
} else {
// GitLab
const credentials = findCredentialsForRepo(remoteUrl, settings.credentials);
const token = credentials?.password;
if (token) {
try {
const userResponse = await fetch(`${remoteInfo.apiUrl}/user`, {
headers: {
'PRIVATE-TOKEN': token,
},
});
if (userResponse.ok) {
const userData = await userResponse.json();
currentUsername = userData.username;
isRepoOwner = currentUsername === remoteInfo.owner;
}
} catch (error) {
console.warn('Failed to fetch current GitLab user:', error);
}
}
}
console.log('Fetching PRs - isRepoOwner:', isRepoOwner, 'currentUser:', currentUsername || user?.pubkey);
// Fetch PRs based on platform
if (remoteInfo.platform === 'nostr') {
return await fetchNostrPatches(remoteInfo, user?.pubkey, nostr, signal, isRepoOwner);
} else if (remoteInfo.platform === 'github') {
const credentials = findCredentialsForRepo(remoteUrl, settings.credentials);
const token = credentials?.password;
return await fetchGitHubPRs(remoteInfo, token, currentUsername, isRepoOwner);
} else {
// GitLab
const credentials = findCredentialsForRepo(remoteUrl, settings.credentials);
const token = credentials?.password;
return await fetchGitLabMRs(remoteInfo, token, currentUsername, isRepoOwner);
}
},
enabled: !!remoteUrl,
refetchInterval: 60000, // Refetch every minute
staleTime: 30000, // Consider data stale after 30 seconds
});
}
+16
View File
@@ -251,6 +251,22 @@
max-height: 100dvh;
}
/* Mobile navigation button styles - text/icon highlighting only */
.mobile-nav-button,
.mobile-nav-button:hover,
.mobile-nav-button:active,
.mobile-nav-button-active,
.mobile-nav-button-active:hover,
.mobile-nav-button-active:active {
background-color: transparent !important;
}
.mobile-nav-button-active,
.mobile-nav-button-active:hover,
.mobile-nav-button-active:active {
color: hsl(var(--primary)) !important;
}
pre.shiki {
background-color: transparent !important;
}
+140 -9
View File
@@ -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}`);
-283
View File
@@ -1,283 +0,0 @@
import { describe, it, expect } from 'vitest';
import { nip19 } from 'nostr-tools';
import { NostrURI } from './NostrURI';
describe('NostrURI', () => {
const testPubkey = 'a'.repeat(64); // Valid hex pubkey
const testNpub = nip19.npubEncode(testPubkey);
const testIdentifier = 'my-repo';
const testRelay = 'wss://relay.example.com/';
describe('constructor', () => {
it('creates a NostrURI from parts without relay', () => {
const uri = new NostrURI({
pubkey: testPubkey,
identifier: testIdentifier,
});
expect(uri.pubkey).toBe(testPubkey);
expect(uri.identifier).toBe(testIdentifier);
expect(uri.relay).toBeUndefined();
});
it('creates a NostrURI from parts with relay', () => {
const uri = new NostrURI({
pubkey: testPubkey,
identifier: testIdentifier,
relay: testRelay,
});
expect(uri.pubkey).toBe(testPubkey);
expect(uri.identifier).toBe(testIdentifier);
expect(uri.relay).toBe(testRelay);
});
});
describe('parse', () => {
it('parses a simple nostr URI without relay', async () => {
const uriString = `nostr://${testNpub}/${testIdentifier}`;
const uri = await NostrURI.parse(uriString);
expect(uri.pubkey).toBe(testPubkey);
expect(uri.identifier).toBe(testIdentifier);
expect(uri.relay).toBeUndefined();
});
it('parses a nostr URI with relay', async () => {
const uriString = `nostr://${testNpub}/relay.example.com/${testIdentifier}`;
const uri = await NostrURI.parse(uriString);
expect(uri.pubkey).toBe(testPubkey);
expect(uri.identifier).toBe(testIdentifier);
expect(uri.relay).toBe('wss://relay.example.com/');
});
it('parses a nostr URI with wss:// relay', async () => {
const uriString = `nostr://${testNpub}/wss://relay.example.com/${testIdentifier}`;
const uri = await NostrURI.parse(uriString);
expect(uri.pubkey).toBe(testPubkey);
expect(uri.identifier).toBe(testIdentifier);
expect(uri.relay).toBe('wss://relay.example.com/');
});
it('throws on invalid URI prefix', async () => {
await expect(NostrURI.parse('https://example.com')).rejects.toThrow(
'Invalid Nostr URI: must start with "nostr://"'
);
});
it('throws on too few path segments', async () => {
await expect(NostrURI.parse('nostr://npub1abc')).rejects.toThrow(
'Invalid Nostr URI: must have at least pubkey/identifier'
);
});
it('throws on too many path segments', async () => {
await expect(
NostrURI.parse(`nostr://${testNpub}/relay/identifier/extra`)
).rejects.toThrow('Invalid Nostr URI: too many path segments');
});
it('throws on invalid npub', async () => {
await expect(NostrURI.parse('nostr://invalid/identifier')).rejects.toThrow(
'Invalid Nostr URI: identifier must be npub or NIP-05 address'
);
});
});
describe('toString', () => {
it('converts to string without relay', () => {
const uri = new NostrURI({
pubkey: testPubkey,
identifier: testIdentifier,
});
const str = uri.toString();
expect(str).toBe(`nostr://${testNpub}/${testIdentifier}`);
});
it('converts to string with relay', () => {
const uri = new NostrURI({
pubkey: testPubkey,
identifier: testIdentifier,
relay: testRelay,
});
const str = uri.toString();
expect(str).toBe(`nostr://${testNpub}/relay.example.com/${testIdentifier}`);
});
it('removes wss:// prefix and trailing slash from relay', () => {
const uri = new NostrURI({
pubkey: testPubkey,
identifier: testIdentifier,
relay: 'wss://relay.example.com/',
});
const str = uri.toString();
expect(str).toBe(`nostr://${testNpub}/relay.example.com/${testIdentifier}`);
});
});
describe('toNaddr', () => {
it('converts to naddr without relay', () => {
const uri = new NostrURI({
pubkey: testPubkey,
identifier: testIdentifier,
});
const naddr = uri.toNaddr();
const decoded = nip19.decode(naddr);
expect(decoded.type).toBe('naddr');
if (decoded.type === 'naddr') {
expect(decoded.data.pubkey).toBe(testPubkey);
expect(decoded.data.identifier).toBe(testIdentifier);
expect(decoded.data.kind).toBe(30617);
// nip19.naddrEncode returns an empty array when no relays are provided
expect(decoded.data.relays).toEqual([]);
}
});
it('converts to naddr with relay', () => {
const uri = new NostrURI({
pubkey: testPubkey,
identifier: testIdentifier,
relay: testRelay,
});
const naddr = uri.toNaddr();
const decoded = nip19.decode(naddr);
expect(decoded.type).toBe('naddr');
if (decoded.type === 'naddr') {
expect(decoded.data.pubkey).toBe(testPubkey);
expect(decoded.data.identifier).toBe(testIdentifier);
expect(decoded.data.kind).toBe(30617);
expect(decoded.data.relays).toEqual([testRelay]);
}
});
it('uses default kind 30617 when not specified', () => {
const uri = new NostrURI({
pubkey: testPubkey,
identifier: testIdentifier,
});
const naddr = uri.toNaddr();
const decoded = nip19.decode(naddr);
expect(decoded.type).toBe('naddr');
if (decoded.type === 'naddr') {
expect(decoded.data.kind).toBe(30617);
}
});
});
describe('fromNaddr', () => {
it('creates NostrURI from naddr without relay', () => {
const naddr = nip19.naddrEncode({
kind: 30617,
pubkey: testPubkey,
identifier: testIdentifier,
});
const uri = NostrURI.fromNaddr(naddr);
expect(uri.pubkey).toBe(testPubkey);
expect(uri.identifier).toBe(testIdentifier);
expect(uri.relay).toBeUndefined();
});
it('creates NostrURI from naddr with relay', () => {
const naddr = nip19.naddrEncode({
kind: 30617,
pubkey: testPubkey,
identifier: testIdentifier,
relays: [testRelay],
});
const uri = NostrURI.fromNaddr(naddr);
expect(uri.pubkey).toBe(testPubkey);
expect(uri.identifier).toBe(testIdentifier);
expect(uri.relay).toBe(testRelay);
});
it('uses first relay when multiple relays provided', () => {
const naddr = nip19.naddrEncode({
kind: 30617,
pubkey: testPubkey,
identifier: testIdentifier,
relays: [testRelay, 'wss://another-relay.com/'],
});
const uri = NostrURI.fromNaddr(naddr);
expect(uri.relay).toBe(testRelay);
});
it('throws on invalid naddr', () => {
expect(() => NostrURI.fromNaddr('invalid')).toThrow('Failed to parse naddr');
});
it('throws on non-naddr identifier', () => {
const npub = nip19.npubEncode(testPubkey);
expect(() => NostrURI.fromNaddr(npub)).toThrow(
'Invalid naddr: must be an addressable event pointer'
);
});
});
describe('toJSON', () => {
it('returns the component parts', () => {
const uri = new NostrURI({
pubkey: testPubkey,
identifier: testIdentifier,
relay: testRelay,
});
const parts = uri.toJSON();
expect(parts).toEqual({
pubkey: testPubkey,
identifier: testIdentifier,
relay: testRelay,
});
});
});
describe('round-trip conversions', () => {
it('parse -> toString round-trip works', async () => {
const original = `nostr://${testNpub}/${testIdentifier}`;
const uri = await NostrURI.parse(original);
const result = uri.toString();
expect(result).toBe(original);
});
it('parse -> toString round-trip works with relay', async () => {
const original = `nostr://${testNpub}/relay.example.com/${testIdentifier}`;
const uri = await NostrURI.parse(original);
const result = uri.toString();
expect(result).toBe(original);
});
it('toNaddr -> fromNaddr round-trip works', () => {
const uri = new NostrURI({
pubkey: testPubkey,
identifier: testIdentifier,
relay: testRelay,
});
const naddr = uri.toNaddr();
const result = NostrURI.fromNaddr(naddr);
expect(result.pubkey).toBe(uri.pubkey);
expect(result.identifier).toBe(uri.identifier);
expect(result.relay).toBe(uri.relay);
});
});
});
-248
View File
@@ -1,248 +0,0 @@
import { NIP05 } from '@nostrify/nostrify';
import { nip19 } from 'nostr-tools';
/**
* Represents a parsed Nostr URI with its components
*/
export interface NostrURIParts {
/** The public key (hex format) */
pubkey: string;
/** The identifier (d-tag value) */
identifier: string;
/** Optional relay URL */
relay?: string;
}
/**
* NostrURI class for parsing and constructing Nostr URIs
*
* Supports formats:
* - nostr://npub/identifier
* - nostr://npub/relay/identifier
* - nostr://nip05@domain/identifier
* - nostr://nip05@domain/relay/identifier
*
* @example
* ```ts
* // Construct from parts
* const uri = new NostrURI({
* pubkey: 'abc123...',
* identifier: 'my-repo',
* relay: 'relay.example.com'
* });
*
* // Parse from string
* const uri = await NostrURI.parse('nostr://npub1.../my-repo');
* ```
*/
export class NostrURI {
public readonly pubkey: string;
public readonly identifier: string;
public readonly relay?: string;
/**
* Construct a NostrURI from its component parts
*/
constructor(parts: NostrURIParts) {
this.pubkey = parts.pubkey;
this.identifier = parts.identifier;
this.relay = parts.relay;
}
/**
* Parse a Nostr URI string into a NostrURI instance
*
* @param uri - The Nostr URI string to parse
* @returns A NostrURI instance
* @throws Error if the URI format is invalid
*
* @example
* ```ts
* const uri = await NostrURI.parse('nostr://npub1abc.../my-repo');
* console.log(uri.pubkey); // hex pubkey
* console.log(uri.identifier); // 'my-repo'
* ```
*/
static async parse(uri: string): Promise<NostrURI> {
if (!uri.startsWith('nostr://')) {
throw new Error('Invalid Nostr URI: must start with "nostr://"');
}
const path = uri.slice(8); // Remove 'nostr://' prefix
const parts = path.split('/');
if (parts.length < 2) {
throw new Error('Invalid Nostr URI: must have at least pubkey/identifier');
}
const identifierPart = parts[0];
let pubkey: string;
// Try to decode as npub first
try {
const decoded = nip19.decode(identifierPart);
if (decoded.type === 'npub') {
pubkey = decoded.data;
} else {
throw new Error('Invalid Nostr URI: identifier must be npub or NIP-05 address');
}
} catch {
// If decoding fails, check if it's a NIP-05 identifier
if (identifierPart.includes('@')) {
try {
const pointer = await NIP05.lookup(identifierPart, {
signal: AbortSignal.timeout(3000),
});
pubkey = pointer.pubkey;
} catch (error) {
throw new Error(`Invalid Nostr URI: failed to resolve NIP-05 identifier: ${error}`);
}
} else {
throw new Error('Invalid Nostr URI: identifier must be npub or NIP-05 address');
}
}
// Parse the remaining parts based on length
if (parts.length === 2) {
// Format: nostr://npub/identifier
return new NostrURI({
pubkey,
identifier: parts[1],
});
} else if (parts.length === 3) {
// Format: nostr://npub/relay/identifier
const relay = parts[1].startsWith('wss://') ? parts[1] : `wss://${parts[1]}/`;
return new NostrURI({
pubkey,
relay,
identifier: parts[2],
});
} else {
// Handle the case where wss:// is included in the URI
// When split by /, wss://relay.example.com becomes ['wss:', '', 'relay.example.com']
// So we need to reconstruct the relay URL
// Find where 'wss:' appears in the parts array
const wssIndex = parts.findIndex(part => part === 'wss:');
if (wssIndex > 0 && parts.length > wssIndex + 2) {
// Reconstruct the relay URL: wss://hostname/
const hostname = parts[wssIndex + 2]; // Skip the empty string after wss:
const relay = `wss://${hostname}/`;
const identifier = parts[wssIndex + 3];
return new NostrURI({
pubkey,
relay,
identifier,
});
}
throw new Error('Invalid Nostr URI: too many path segments');
}
}
/**
* Convert the NostrURI to a string representation
*
* @returns The Nostr URI as a string
*
* @example
* ```ts
* const uri = new NostrURI({ pubkey: 'abc...', identifier: 'my-repo' });
* console.log(uri.toString()); // 'nostr://npub1.../my-repo'
* ```
*/
toString(): string {
const npub = nip19.npubEncode(this.pubkey);
if (this.relay) {
try {
const url = new URL(this.relay);
return `nostr://${npub}/${url.hostname}/${this.identifier}`;
} catch {
// fallthrough
}
}
return `nostr://${npub}/${this.identifier}`;
}
/**
* Convert to an naddr (NIP-19 addressable event identifier)
*
* @returns An naddr string
*
* @example
* ```ts
* const uri = new NostrURI({ pubkey: 'abc...', identifier: 'my-repo' });
* const naddr = uri.toNaddr();
* ```
*/
toNaddr(): string {
const data: {
kind: number;
pubkey: string;
identifier: string;
relays?: string[];
} = {
kind: 30617,
pubkey: this.pubkey,
identifier: this.identifier,
};
// Only add relays if we have a relay (avoid empty array)
if (this.relay) {
data.relays = [this.relay];
}
return nip19.naddrEncode(data);
}
/**
* Create a NostrURI from an naddr (NIP-19 addressable event identifier)
*
* @param naddr - The naddr string to parse
* @returns A NostrURI instance
* @throws Error if the naddr is invalid or not an addressable event pointer
*
* @example
* ```ts
* const uri = NostrURI.fromNaddr('naddr1...');
* console.log(uri.pubkey);
* console.log(uri.identifier);
* ```
*/
static fromNaddr(naddr: string): NostrURI {
try {
const decoded = nip19.decode(naddr);
if (decoded.type !== 'naddr') {
throw new Error('Invalid naddr: must be an addressable event pointer');
}
const data = decoded.data;
return new NostrURI({
pubkey: data.pubkey,
identifier: data.identifier,
relay: data.relays?.[0], // Use first relay if available
});
} catch (error) {
throw new Error(`Failed to parse naddr: ${error}`);
}
}
/**
* Convert to a JSON-serializable object with the component parts
*
* @returns The component parts of the URI
*/
toJSON(): NostrURIParts {
return {
pubkey: this.pubkey,
identifier: this.identifier,
relay: this.relay,
};
}
}
+2 -8
View File
@@ -457,10 +457,7 @@ describe('ProjectsManager', () => {
Object.assign(projectsManager, { git: mockGit });
// Attempt to clone a project
await expect(projectsManager.cloneProject({
name: 'test-project',
repoUrl: 'https://github.com/test/repo.git',
}))
await expect(projectsManager.cloneProject('test-project', 'https://github.com/test/repo.git'))
.rejects.toThrow('Clone failed');
// Verify that the project directory was cleaned up
@@ -491,10 +488,7 @@ describe('ProjectsManager', () => {
try {
// Attempt to clone a project
await expect(projectsManager.cloneProject({
name: 'test-project',
repoUrl: 'https://github.com/test/repo.git',
}))
await expect(projectsManager.cloneProject('test-project', 'https://github.com/test/repo.git'))
.rejects.toThrow('Clone failed');
// Should have logged a cleanup warning
+2 -11
View File
@@ -494,14 +494,7 @@ export class ProjectsManager {
}
}
async cloneProject(options: {
name: string;
repoUrl: string;
customId?: string;
depth?: number;
fork?: boolean;
}): Promise<Project> {
const { name, repoUrl, customId, depth, fork = false } = options;
async cloneProject(name: string, repoUrl: string, customId?: string, options?: { depth?: number }): Promise<Project> {
const id = customId || await this.generateUniqueProjectId(name);
// Check if project with this ID already exists when using custom ID
@@ -515,13 +508,11 @@ export class ProjectsManager {
try {
// Clone the repository (Git class now handles Nostr URIs automatically)
// When forking, use 'upstream' as the remote name instead of 'origin'
await this.git.clone({
dir: projectPath,
url: repoUrl,
singleBranch: true,
depth, // Use depth if provided, otherwise clone full history
remote: fork ? 'upstream' : undefined, // Use 'upstream' for forks, otherwise defaults to 'origin'
depth: options?.depth, // Use depth if provided, otherwise clone full history
});
// Get filesystem stats for timestamps
+1 -2
View File
@@ -44,12 +44,11 @@ const testConfig: AppConfig = {
esmUrl: 'https://esm.shakespeare.diy',
corsProxy: 'https://proxy.shakespeare.diy/?url={href}',
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'local-shakespeare.dev',
language: 'en',
showcaseEnabled: true,
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
graspMetadata: { relays: [{ url: 'wss://git.shakespeare.diy/' }, { url: 'wss://relay.ngit.dev/' }], updatedAt: 0 },
ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'],
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
+2 -2
View File
@@ -340,14 +340,14 @@ export class SessionManager {
const stripImageUrls = (msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[]): OpenAI.Chat.Completions.ChatCompletionMessageParam[] => {
return msgs.map(msg => {
if (msg.role === 'user' && typeof msg.content !== 'string' && Array.isArray(msg.content)) {
// Keep only text parts (this includes "Added file: <filename>" paths)
// Keep only text parts (this includes "Added file: /tmp/..." paths)
const textParts = msg.content.filter(part => part.type === 'text');
// If we had images, convert to string content (or empty if no text)
if (textParts.length > 0) {
return {
...msg,
content: textParts,
content: textParts.map(part => (part as OpenAI.Chat.Completions.ChatCompletionContentPartText).text).join('\n')
};
}
+20 -4
View File
@@ -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}`);
}
+9
View File
@@ -1,8 +1,11 @@
import type { JSRuntimeFS } from "../../JSRuntime";
import type { ShellCommandResult } from "../ShellCommand";
import type { NostrSigner } from "@nostrify/nostrify";
import { createSuccessResult, createErrorResult } from "../ShellCommand";
import type { GitSubcommand, GitSubcommandOptions } from "../git";
import type { Git } from "../../git";
import { findCredentialsForRepo } from "@/lib/gitCredentials";
import { readGitSettings } from "@/lib/configUtils";
export class GitPushCommand implements GitSubcommand {
name = 'push';
@@ -11,10 +14,12 @@ export class GitPushCommand implements GitSubcommand {
private git: Git;
private fs: JSRuntimeFS;
private signer?: NostrSigner;
constructor(options: GitSubcommandOptions) {
this.git = options.git;
this.fs = options.fs;
this.signer = options.signer;
}
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
@@ -59,6 +64,8 @@ export class GitPushCommand implements GitSubcommand {
return createErrorResult(`fatal: '${remote}' does not appear to be a git repository`);
}
const settings = await readGitSettings(this.fs);
try {
await this.git.push({
dir: cwd,
@@ -66,6 +73,8 @@ export class GitPushCommand implements GitSubcommand {
ref: targetBranch,
remoteRef: targetBranch,
force: options.force,
onAuth: (url) => findCredentialsForRepo(url, settings.credentials),
signer: this.signer,
});
return createSuccessResult(`To ${remoteUrl}\n ${targetBranch} -> ${targetBranch}\n`);
+10 -62
View File
@@ -154,77 +154,24 @@ describe('configUtils', () => {
});
describe('Git Settings', () => {
const sampleGitSettingsNew: GitSettings = {
credentials: [
{
id: crypto.randomUUID(),
name: 'GitHub',
origin: 'https://github.com',
username: 'user',
password: 'token123',
},
],
};
const sampleGitSettingsOld = {
const sampleGitSettings: GitSettings = {
credentials: {
'https://github.com': {
'github.com': {
username: 'user',
password: 'token123',
},
},
hostTokens: {},
};
describe('readGitSettings', () => {
it('should read Git settings from VFS (new format)', async () => {
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(sampleGitSettingsNew));
it('should read Git settings from VFS', async () => {
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(sampleGitSettings));
const result = await readGitSettings(mockFS);
expect(mockFS.readFile).toHaveBeenCalledWith('/config/git.json', 'utf8');
expect(result).toEqual(sampleGitSettingsNew);
});
it('should convert old format to new format', async () => {
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(sampleGitSettingsOld));
const result = await readGitSettings(mockFS);
expect(mockFS.readFile).toHaveBeenCalledWith('/config/git.json', 'utf8');
expect(result.credentials).toHaveLength(1);
expect(result.credentials[0]).toMatchObject({
origin: 'https://github.com',
username: 'user',
password: 'token123',
name: 'GitHub',
});
expect(result.credentials[0].id).toBeDefined();
expect(typeof result.credentials[0].id).toBe('string');
});
it('should handle old format with custom ports', async () => {
const oldFormatWithPort = {
credentials: {
'https://git.example.com:8080': {
username: 'user',
password: 'token456',
},
},
};
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(oldFormatWithPort));
const result = await readGitSettings(mockFS);
expect(result.credentials).toHaveLength(1);
expect(result.credentials[0]).toMatchObject({
origin: 'https://git.example.com:8080',
username: 'user',
password: 'token456',
name: 'git.example.com',
});
expect(result.credentials[0].id).toBeDefined();
expect(typeof result.credentials[0].id).toBe('string');
expect(result).toEqual(sampleGitSettings);
});
it('should return default settings if file does not exist and no localStorage data', async () => {
@@ -234,7 +181,8 @@ describe('configUtils', () => {
const result = await readGitSettings(mockFS);
expect(result).toEqual({
credentials: [],
credentials: {},
hostTokens: {},
coAuthorEnabled: true,
});
});
@@ -246,12 +194,12 @@ describe('configUtils', () => {
vi.mocked(mockFS.mkdir).mockResolvedValue(undefined);
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
await writeGitSettings(mockFS, sampleGitSettingsNew);
await writeGitSettings(mockFS, sampleGitSettings);
expect(mockFS.mkdir).toHaveBeenCalledWith('/config', { recursive: true });
expect(mockFS.writeFile).toHaveBeenCalledWith(
'/config/git.json',
JSON.stringify(sampleGitSettingsNew, null, 2),
JSON.stringify(sampleGitSettings, null, 2),
'utf8'
);
});
+12 -64
View File
@@ -3,7 +3,7 @@ import { filteredArray } from '@/lib/schema';
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
import type { JSRuntimeFS } from '@/lib/JSRuntime';
import type { AISettings, MCPServer } from '@/contexts/AISettingsContext';
import type { GitSettings, GitCredential } from '@/contexts/GitSettingsContext';
import type { GitSettings } from '@/contexts/GitSettingsContext';
import type { DeployProvider, DeploySettings } from '@/contexts/DeploySettingsContext';
/**
@@ -57,27 +57,21 @@ const aiSettingsSchema = z.object({
mcpServers: z.record(z.string(), mcpServerSchema).optional(),
});
// New format for git credentials
const gitCredentialSchema = z.object({
id: z.string(),
name: z.string(),
origin: z.string(),
username: z.string(),
password: z.string(),
});
// Old format (map of origins to credentials)
const gitCredentialOldSchema = z.object({
username: z.string(),
password: z.string(),
const gitHostTokenSchema = z.object({
token: z.string(),
username: z.string().optional(),
scopes: z.array(z.string()).optional(),
createdAt: z.number().optional(),
});
// Schema that accepts both old and new formats
const gitSettingsSchema = z.object({
credentials: z.union([
z.array(gitCredentialSchema), // New format: array
z.record(z.string(), gitCredentialOldSchema), // Old format: map
]),
credentials: z.record(z.string(), gitCredentialSchema),
hostTokens: z.record(z.string(), gitHostTokenSchema).optional(),
name: z.string().optional(),
email: z.string().optional(),
coAuthorEnabled: z.boolean().optional(),
@@ -218,45 +212,6 @@ export async function writeAISettings(fs: JSRuntimeFS, settings: AISettings, con
await fs.writeFile(aiConfigPath, JSON.stringify(settings, null, 2), 'utf8');
}
/**
* Generate a display name for a credential based on its hostname
*/
function generateCredentialName(host: string): string {
const hostname = host.split(':')[0]; // Remove port if present
if (hostname === 'github.com') {
return 'GitHub';
}
if (hostname === 'gitlab.com') {
return 'GitLab';
}
// For other hosts, use the hostname as the name
return hostname;
}
/**
* Convert old format credentials (map) to new format (array)
* This is only used for migrating from the old map-based format
*/
function convertCredentialsToNewFormat(
credentials: Record<string, { username: string; password: string }>
): GitCredential[] {
return Object.entries(credentials).map(([origin, cred]) => {
const url = new URL(origin);
const host = url.host; // Includes port if non-standard
return {
id: crypto.randomUUID(),
name: generateCredentialName(host),
origin,
username: cred.username,
password: cred.password,
};
});
}
/**
* Read Git settings from VFS
* @param fs - Filesystem instance
@@ -264,7 +219,8 @@ function convertCredentialsToNewFormat(
*/
export async function readGitSettings(fs: JSRuntimeFS, configPath = '/config'): Promise<GitSettings> {
const defaultSettings: GitSettings = {
credentials: [],
credentials: {},
hostTokens: {},
coAuthorEnabled: true,
};
@@ -274,18 +230,10 @@ export async function readGitSettings(fs: JSRuntimeFS, configPath = '/config'):
const content = await fs.readFile(gitConfigPath, 'utf8');
const data = JSON.parse(content);
const parsed = gitSettingsSchema.parse(data);
// Convert old format to new format if needed
let credentials: GitCredential[];
if (Array.isArray(parsed.credentials)) {
credentials = parsed.credentials;
} else {
credentials = convertCredentialsToNewFormat(parsed.credentials);
}
// Ensure hostTokens exists even if not in parsed data
return {
...parsed,
credentials,
hostTokens: parsed.hostTokens || {},
};
} catch {
return defaultSettings;
-50
View File
@@ -1,50 +0,0 @@
import { NostrURI } from '@/lib/NostrURI';
import { findCredentialsForRepo } from '@/lib/gitCredentials';
import type { GitCredential } from '@/contexts/GitSettingsContext';
/**
* Detect if a repository URL should be treated as a fork
*
* For Nostr URIs: A repository is a fork if the owner's pubkey differs from the current user's pubkey
* For HTTPS URLs: A repository is a fork if the URL doesn't match ${credential.origin}/${credential.username}/
*
* @param repoUrl - The repository URL (Nostr URI or HTTPS)
* @param currentUserPubkey - The current user's Nostr pubkey (optional)
* @param gitCredentials - Array of Git credentials (optional)
* @returns true if the repository should be treated as a fork, false otherwise
*/
export async function detectFork(
repoUrl: string,
currentUserPubkey?: string,
gitCredentials: GitCredential[] = [],
): Promise<boolean> {
// Default to not a fork
let fork = false;
if (repoUrl.startsWith('nostr://')) {
// For Nostr URIs: check if the repository owner is different from current user
if (currentUserPubkey) {
try {
const nostrURI = await NostrURI.parse(repoUrl);
fork = nostrURI.pubkey !== currentUserPubkey;
} catch {
// If parsing fails, default to fork=false
fork = false;
}
}
} else if (repoUrl.startsWith('http://') || repoUrl.startsWith('https://')) {
// For HTTPS URLs: check if the URL belongs to the user based on credentials
// A repository is NOT a fork if it starts with ${credential.origin}/${credential.username}/
const credential = findCredentialsForRepo(repoUrl, gitCredentials);
if (credential) {
const expectedPrefix = `${credential.origin}/${credential.username}/`;
fork = !repoUrl.startsWith(expectedPrefix);
} else {
// No matching credentials found, treat as fork
fork = true;
}
}
return fork;
}
+16 -1
View File
@@ -22,4 +22,19 @@ export function faviconUrl(template: string, url: string | URL): string {
hash: u.hash,
search: u.search,
});
}
}
/**
* Normalize a URL string to ensure it has a protocol
* @param url - The URL string to normalize
* @returns A fully-qualified URL string
*/
export function normalizeUrl(url: string): string {
// If it already has a protocol, return as-is
if (/^https?:\/\//i.test(url)) {
return url;
}
// Add https:// prefix
return `https://${url}`;
}
+303
View File
@@ -0,0 +1,303 @@
import { proxyUrl } from '../proxyUrl';
import type {
GitHostProvider,
GitHostConfig,
GitRepository,
GitFork,
PullRequest,
PullRequestCheck,
CreatePullRequestOptions,
GitHostUser,
} from './types';
interface GitHubPRResponse {
id: number;
number: number;
state: string;
title: string;
body: string;
html_url: string;
created_at: string;
updated_at: string;
user: { login: string };
head: { ref: string; repo: { full_name: string } };
base: { ref: string; repo: { full_name: string } };
mergeable?: boolean;
merged?: boolean;
}
export class GitHubProvider implements GitHostProvider {
readonly name = 'GitHub';
readonly apiBaseUrl = 'https://api.github.com';
private config: GitHostConfig;
private corsProxy?: string;
constructor(config: GitHostConfig, corsProxy?: string) {
this.config = config;
this.corsProxy = corsProxy;
}
private async fetch<T>(path: string, options: RequestInit = {}): Promise<T> {
const url = `${this.apiBaseUrl}${path}`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
...options,
headers: {
'Accept': 'application/vnd.github.v3+json',
'Authorization': `Bearer ${this.config.token}`,
...options.headers,
},
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`GitHub API error (${response.status}): ${errorText}`);
}
return response.json();
}
async getRepository(owner: string, repo: string): Promise<GitRepository> {
interface GitHubRepo {
owner: { login: string };
name: string;
full_name: string;
default_branch: string;
clone_url: string;
html_url: string;
description: string;
private: boolean;
}
const data = await this.fetch<GitHubRepo>(`/repos/${owner}/${repo}`);
return {
owner: data.owner.login,
name: data.name,
fullName: data.full_name,
defaultBranch: data.default_branch,
cloneUrl: data.clone_url,
webUrl: data.html_url,
description: data.description,
isPrivate: data.private,
};
}
async canUserPush(owner: string, repo: string): Promise<boolean> {
try {
interface GitHubRepoWithPermissions {
permissions?: { push?: boolean; admin?: boolean };
}
const data = await this.fetch<GitHubRepoWithPermissions>(`/repos/${owner}/${repo}`);
return data.permissions?.push === true || data.permissions?.admin === true;
} catch {
// If we can't check permissions, assume no push access
return false;
}
}
async createFork(owner: string, repo: string): Promise<GitFork> {
interface GitHubFork {
owner: { login: string };
name: string;
clone_url: string;
html_url: string;
}
const data = await this.fetch<GitHubFork>(`/repos/${owner}/${repo}/forks`, {
method: 'POST',
});
return {
owner: data.owner.login,
name: data.name,
fullName: `${data.owner.login}/${data.name}`,
cloneUrl: data.clone_url,
webUrl: data.html_url,
parentFullName: `${owner}/${repo}`,
};
}
async getFork(upstreamOwner: string, upstreamRepo: string, username: string): Promise<GitFork | null> {
try {
interface GitHubForkCheck {
fork: boolean;
owner: { login: string };
name: string;
full_name: string;
clone_url: string;
html_url: string;
parent?: { full_name: string };
}
// Check if the fork already exists
const data = await this.fetch<GitHubForkCheck>(`/repos/${username}/${upstreamRepo}`);
// Verify it's actually a fork of the upstream repo
if (data.fork && data.parent?.full_name === `${upstreamOwner}/${upstreamRepo}`) {
return {
owner: data.owner.login,
name: data.name,
fullName: data.full_name,
cloneUrl: data.clone_url,
webUrl: data.html_url,
parentFullName: data.parent.full_name,
};
}
return null;
} catch {
return null;
}
}
async waitForFork(
upstreamOwner: string,
upstreamRepo: string,
username: string,
timeout = 30000
): Promise<GitFork> {
const startTime = Date.now();
const pollInterval = 1000;
while (Date.now() - startTime < timeout) {
const fork = await this.getFork(upstreamOwner, upstreamRepo, username);
if (fork) {
return fork;
}
await new Promise(resolve => setTimeout(resolve, pollInterval));
}
throw new Error('Timeout waiting for fork to be created');
}
async createPullRequest(options: CreatePullRequestOptions): Promise<PullRequest> {
const [baseOwner, baseRepo] = options.baseRepo.split('/');
const [headOwner] = options.headRepo.split('/');
// Format head ref for cross-repo PR
const head = headOwner !== baseOwner
? `${headOwner}:${options.headBranch}`
: options.headBranch;
const data = await this.fetch<GitHubPRResponse>(`/repos/${baseOwner}/${baseRepo}/pulls`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
title: options.title,
body: options.body || '',
head,
base: options.baseBranch,
maintainer_can_modify: options.maintainerCanModify ?? true,
}),
});
return this.transformPullRequest(data);
}
async getPullRequest(owner: string, repo: string, number: number): Promise<PullRequest> {
const data = await this.fetch<GitHubPRResponse>(`/repos/${owner}/${repo}/pulls/${number}`);
return this.transformPullRequest(data);
}
async listPullRequests(
owner: string,
repo: string,
state: 'open' | 'closed' | 'all' = 'open'
): Promise<PullRequest[]> {
const data = await this.fetch<GitHubPRResponse[]>(`/repos/${owner}/${repo}/pulls?state=${state}`);
return data.map(pr => this.transformPullRequest(pr));
}
async updatePullRequest(
owner: string,
repo: string,
number: number,
options: { title?: string; body?: string }
): Promise<PullRequest> {
const data = await this.fetch<GitHubPRResponse>(`/repos/${owner}/${repo}/pulls/${number}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(options),
});
return this.transformPullRequest(data);
}
async closePullRequest(owner: string, repo: string, number: number): Promise<PullRequest> {
const data = await this.fetch<GitHubPRResponse>(`/repos/${owner}/${repo}/pulls/${number}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ state: 'closed' }),
});
return this.transformPullRequest(data);
}
async getCurrentUser(): Promise<GitHostUser> {
interface GitHubUser {
login: string;
name: string;
email: string;
avatar_url: string;
}
const data = await this.fetch<GitHubUser>('/user');
return {
username: data.login,
name: data.name,
email: data.email,
avatarUrl: data.avatar_url,
};
}
getCompareUrl(baseRepo: string, baseBranch: string, headRepo: string, headBranch: string): string {
const [headOwner, headRepoName] = headRepo.split('/');
return `https://github.com/${baseRepo}/compare/${baseBranch}...${headOwner}:${headRepoName}:${headBranch}?expand=1`;
}
private transformPullRequest(data: {
id: number;
number: number;
state: string;
title: string;
body: string;
html_url: string;
created_at: string;
updated_at: string;
user: { login: string };
head: { ref: string; repo: { full_name: string } };
base: { ref: string; repo: { full_name: string } };
mergeable?: boolean;
merged?: boolean;
}): PullRequest {
const state: 'open' | 'closed' | 'merged' = data.merged ? 'merged' : data.state as 'open' | 'closed';
return {
number: data.number,
title: data.title,
body: data.body,
state,
headBranch: data.head.ref,
baseBranch: data.base.ref,
headRepo: data.head.repo?.full_name || '',
baseRepo: data.base.repo.full_name,
url: data.html_url,
createdAt: new Date(data.created_at),
updatedAt: new Date(data.updated_at),
author: data.user.login,
mergeable: data.mergeable,
checks: this.transformChecks(data),
};
}
private transformChecks(_data: unknown): PullRequestCheck[] | undefined {
// GitHub's check runs are in a separate API call, so we don't have them here
// This would need a separate API call to /repos/{owner}/{repo}/commits/{ref}/check-runs
return undefined;
}
}
+328
View File
@@ -0,0 +1,328 @@
import { proxyUrl } from '../proxyUrl';
import type {
GitHostProvider,
GitHostConfig,
GitRepository,
GitFork,
PullRequest,
PullRequestCheck,
CreatePullRequestOptions,
GitHostUser,
} from './types';
interface GitLabMRResponse {
id: number;
iid: number;
state: string;
title: string;
description: string;
web_url: string;
created_at: string;
updated_at: string;
author: { username: string };
source_branch: string;
target_branch: string;
source_project_id: number;
target_project_id: number;
merge_status?: string;
merged_at?: string;
pipeline?: {
status: string;
web_url: string;
};
}
export class GitLabProvider implements GitHostProvider {
readonly name = 'GitLab';
readonly apiBaseUrl = 'https://gitlab.com/api/v4';
private config: GitHostConfig;
private corsProxy?: string;
constructor(config: GitHostConfig, corsProxy?: string) {
this.config = config;
this.corsProxy = corsProxy;
}
private async fetch<T>(path: string, options: RequestInit = {}): Promise<T> {
const url = `${this.apiBaseUrl}${path}`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
...options,
headers: {
'Authorization': `Bearer ${this.config.token}`,
'Content-Type': 'application/json',
...options.headers,
},
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`GitLab API error (${response.status}): ${errorText}`);
}
return response.json();
}
private encodeProjectPath(owner: string, repo: string): string {
return encodeURIComponent(`${owner}/${repo}`);
}
async getRepository(owner: string, repo: string): Promise<GitRepository> {
interface GitLabProject {
namespace: { path: string };
path: string;
path_with_namespace: string;
default_branch: string;
http_url_to_repo: string;
web_url: string;
description: string;
visibility: string;
}
const projectPath = this.encodeProjectPath(owner, repo);
const data = await this.fetch<GitLabProject>(`/projects/${projectPath}`);
return {
owner: data.namespace.path,
name: data.path,
fullName: data.path_with_namespace,
defaultBranch: data.default_branch,
cloneUrl: data.http_url_to_repo,
webUrl: data.web_url,
description: data.description,
isPrivate: data.visibility === 'private',
};
}
async canUserPush(owner: string, repo: string): Promise<boolean> {
try {
interface GitLabProjectWithPermissions {
permissions?: {
project_access?: { access_level?: number };
};
}
const projectPath = this.encodeProjectPath(owner, repo);
const data = await this.fetch<GitLabProjectWithPermissions>(`/projects/${projectPath}`);
// GitLab permissions are more granular
// developer (30), maintainer (40), or owner (50) can push
const accessLevel = data.permissions?.project_access?.access_level || 0;
return accessLevel >= 30;
} catch {
return false;
}
}
async createFork(owner: string, repo: string): Promise<GitFork> {
interface GitLabFork {
namespace: { path: string };
path: string;
path_with_namespace: string;
http_url_to_repo: string;
web_url: string;
forked_from_project?: { path_with_namespace: string };
}
const projectPath = this.encodeProjectPath(owner, repo);
const data = await this.fetch<GitLabFork>(`/projects/${projectPath}/fork`, {
method: 'POST',
});
return {
owner: data.namespace.path,
name: data.path,
fullName: data.path_with_namespace,
cloneUrl: data.http_url_to_repo,
webUrl: data.web_url,
parentFullName: data.forked_from_project?.path_with_namespace || `${owner}/${repo}`,
};
}
async getFork(upstreamOwner: string, upstreamRepo: string, username: string): Promise<GitFork | null> {
try {
interface GitLabForkCheck {
namespace: { path: string };
path: string;
path_with_namespace: string;
http_url_to_repo: string;
web_url: string;
forked_from_project?: { path_with_namespace: string };
}
const forkPath = this.encodeProjectPath(username, upstreamRepo);
const data = await this.fetch<GitLabForkCheck>(`/projects/${forkPath}`);
// Check if it's a fork of the upstream
if (data.forked_from_project?.path_with_namespace === `${upstreamOwner}/${upstreamRepo}`) {
return {
owner: data.namespace.path,
name: data.path,
fullName: data.path_with_namespace,
cloneUrl: data.http_url_to_repo,
webUrl: data.web_url,
parentFullName: data.forked_from_project.path_with_namespace,
};
}
return null;
} catch {
return null;
}
}
async waitForFork(
upstreamOwner: string,
upstreamRepo: string,
username: string,
timeout = 30000
): Promise<GitFork> {
const startTime = Date.now();
const pollInterval = 1000;
while (Date.now() - startTime < timeout) {
const fork = await this.getFork(upstreamOwner, upstreamRepo, username);
if (fork) {
return fork;
}
await new Promise(resolve => setTimeout(resolve, pollInterval));
}
throw new Error('Timeout waiting for fork to be created');
}
async createPullRequest(options: CreatePullRequestOptions): Promise<PullRequest> {
// In GitLab, MRs are created on the source (fork) project
const sourceProjectPath = this.encodeProjectPath(options.headRepo.split('/')[0], options.headRepo.split('/')[1]);
const [targetOwner, targetRepo] = options.baseRepo.split('/');
const data = await this.fetch<GitLabMRResponse>(`/projects/${sourceProjectPath}/merge_requests`, {
method: 'POST',
body: JSON.stringify({
source_branch: options.headBranch,
target_branch: options.baseBranch,
target_project_id: this.encodeProjectPath(targetOwner, targetRepo),
title: options.title,
description: options.body || '',
allow_collaboration: options.maintainerCanModify ?? true,
}),
});
return this.transformMergeRequest(data);
}
async getPullRequest(owner: string, repo: string, number: number): Promise<PullRequest> {
const projectPath = this.encodeProjectPath(owner, repo);
const data = await this.fetch<GitLabMRResponse>(`/projects/${projectPath}/merge_requests/${number}`);
return this.transformMergeRequest(data);
}
async listPullRequests(
owner: string,
repo: string,
state: 'open' | 'closed' | 'all' = 'open'
): Promise<PullRequest[]> {
const projectPath = this.encodeProjectPath(owner, repo);
const stateParam = state === 'all' ? 'all' : state === 'open' ? 'opened' : 'closed';
const data = await this.fetch<GitLabMRResponse[]>(`/projects/${projectPath}/merge_requests?state=${stateParam}`);
return data.map(mr => this.transformMergeRequest(mr));
}
async updatePullRequest(
owner: string,
repo: string,
number: number,
options: { title?: string; body?: string }
): Promise<PullRequest> {
const projectPath = this.encodeProjectPath(owner, repo);
const data = await this.fetch<GitLabMRResponse>(`/projects/${projectPath}/merge_requests/${number}`, {
method: 'PUT',
body: JSON.stringify({
title: options.title,
description: options.body,
}),
});
return this.transformMergeRequest(data);
}
async closePullRequest(owner: string, repo: string, number: number): Promise<PullRequest> {
const projectPath = this.encodeProjectPath(owner, repo);
const data = await this.fetch<GitLabMRResponse>(`/projects/${projectPath}/merge_requests/${number}`, {
method: 'PUT',
body: JSON.stringify({
state_event: 'close',
}),
});
return this.transformMergeRequest(data);
}
async getCurrentUser(): Promise<GitHostUser> {
interface GitLabUser {
username: string;
name: string;
email: string;
avatar_url: string;
}
const data = await this.fetch<GitLabUser>('/user');
return {
username: data.username,
name: data.name,
email: data.email,
avatarUrl: data.avatar_url,
};
}
getCompareUrl(baseRepo: string, baseBranch: string, headRepo: string, headBranch: string): string {
const [headOwner, headRepoName] = headRepo.split('/');
return `https://gitlab.com/${baseRepo}/-/merge_requests/new?merge_request[source_branch]=${headBranch}&merge_request[source_project]=${headOwner}/${headRepoName}&merge_request[target_branch]=${baseBranch}`;
}
private transformMergeRequest(data: GitLabMRResponse): PullRequest {
const state = data.state === 'merged' ? 'merged' : data.state === 'opened' ? 'open' : 'closed';
return {
number: data.iid, // GitLab uses iid (internal id) for MRs
title: data.title,
body: data.description,
state,
headBranch: data.source_branch,
baseBranch: data.target_branch,
headRepo: data.source_project_id?.toString() || '',
baseRepo: data.target_project_id?.toString() || '',
url: data.web_url,
createdAt: new Date(data.created_at),
updatedAt: new Date(data.updated_at),
author: data.author.username,
mergeable: data.merge_status === 'can_be_merged',
checks: this.transformPipeline(data),
};
}
private transformPipeline(data: GitLabMRResponse): PullRequestCheck[] | undefined {
if (!data.pipeline) return undefined;
const mapConclusion = (status: string): PullRequestCheck['conclusion'] => {
switch (status) {
case 'success': return 'success';
case 'failed': return 'failure';
case 'canceled': return 'cancelled';
case 'skipped': return 'skipped';
default: return undefined;
}
};
return [{
name: 'Pipeline',
status: data.pipeline.status === 'running' ? 'pending' :
data.pipeline.status === 'success' ? 'success' : 'failure',
conclusion: mapConclusion(data.pipeline.status),
detailsUrl: data.pipeline.web_url,
}];
}
}
+293
View File
@@ -0,0 +1,293 @@
import { proxyUrl } from '../proxyUrl';
import type {
GitHostProvider,
GitHostConfig,
GitRepository,
GitFork,
PullRequest,
CreatePullRequestOptions,
GitHostUser,
} from './types';
interface GiteaPRResponse {
id: number;
number: number;
state: string;
title: string;
body: string;
html_url: string;
created_at: string;
updated_at: string;
user: { login: string };
head: { ref: string; repo: { full_name: string } };
base: { ref: string; repo: { full_name: string } };
mergeable?: boolean;
merged?: boolean;
}
export class GiteaProvider implements GitHostProvider {
readonly name: string;
readonly apiBaseUrl: string;
private config: GitHostConfig;
private corsProxy?: string;
constructor(config: GitHostConfig, apiBaseUrl: string, name = 'Gitea', corsProxy?: string) {
this.config = config;
this.apiBaseUrl = apiBaseUrl;
this.name = name;
this.corsProxy = corsProxy;
}
private async fetch<T>(path: string, options: RequestInit = {}): Promise<T> {
const url = `${this.apiBaseUrl}${path}`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
...options,
headers: {
'Authorization': `token ${this.config.token}`,
'Content-Type': 'application/json',
...options.headers,
},
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`${this.name} API error (${response.status}): ${errorText}`);
}
return response.json();
}
async getRepository(owner: string, repo: string): Promise<GitRepository> {
interface GiteaRepo {
owner: { login: string };
name: string;
full_name: string;
default_branch: string;
clone_url: string;
html_url: string;
description: string;
private: boolean;
}
const data = await this.fetch<GiteaRepo>(`/repos/${owner}/${repo}`);
return {
owner: data.owner.login,
name: data.name,
fullName: data.full_name,
defaultBranch: data.default_branch,
cloneUrl: data.clone_url,
webUrl: data.html_url,
description: data.description,
isPrivate: data.private,
};
}
async canUserPush(owner: string, repo: string): Promise<boolean> {
try {
interface GiteaRepoWithPermissions {
permissions?: { push?: boolean; admin?: boolean };
}
const data = await this.fetch<GiteaRepoWithPermissions>(`/repos/${owner}/${repo}`);
return data.permissions?.push === true || data.permissions?.admin === true;
} catch {
return false;
}
}
async createFork(owner: string, repo: string): Promise<GitFork> {
interface GiteaFork {
owner: { login: string };
name: string;
full_name: string;
clone_url: string;
html_url: string;
parent?: { full_name: string };
}
const data = await this.fetch<GiteaFork>(`/repos/${owner}/${repo}/forks`, {
method: 'POST',
});
return {
owner: data.owner.login,
name: data.name,
fullName: data.full_name,
cloneUrl: data.clone_url,
webUrl: data.html_url,
parentFullName: data.parent?.full_name || `${owner}/${repo}`,
};
}
async getFork(upstreamOwner: string, upstreamRepo: string, username: string): Promise<GitFork | null> {
try {
interface GiteaForkCheck {
fork: boolean;
owner: { login: string };
name: string;
full_name: string;
clone_url: string;
html_url: string;
parent?: { full_name: string };
}
const data = await this.fetch<GiteaForkCheck>(`/repos/${username}/${upstreamRepo}`);
if (data.fork && data.parent?.full_name === `${upstreamOwner}/${upstreamRepo}`) {
return {
owner: data.owner.login,
name: data.name,
fullName: data.full_name,
cloneUrl: data.clone_url,
webUrl: data.html_url,
parentFullName: data.parent.full_name,
};
}
return null;
} catch {
return null;
}
}
async waitForFork(
upstreamOwner: string,
upstreamRepo: string,
username: string,
timeout = 30000
): Promise<GitFork> {
const startTime = Date.now();
const pollInterval = 1000;
while (Date.now() - startTime < timeout) {
const fork = await this.getFork(upstreamOwner, upstreamRepo, username);
if (fork) {
return fork;
}
await new Promise(resolve => setTimeout(resolve, pollInterval));
}
throw new Error('Timeout waiting for fork to be created');
}
async createPullRequest(options: CreatePullRequestOptions): Promise<PullRequest> {
const [baseOwner, baseRepo] = options.baseRepo.split('/');
const [headOwner] = options.headRepo.split('/');
// Format head ref for cross-repo PR
const head = headOwner !== baseOwner
? `${headOwner}:${options.headBranch}`
: options.headBranch;
const data = await this.fetch<GiteaPRResponse>(`/repos/${baseOwner}/${baseRepo}/pulls`, {
method: 'POST',
body: JSON.stringify({
title: options.title,
body: options.body || '',
head,
base: options.baseBranch,
}),
});
return this.transformPullRequest(data);
}
async getPullRequest(owner: string, repo: string, number: number): Promise<PullRequest> {
const data = await this.fetch<GiteaPRResponse>(`/repos/${owner}/${repo}/pulls/${number}`);
return this.transformPullRequest(data);
}
async listPullRequests(
owner: string,
repo: string,
state: 'open' | 'closed' | 'all' = 'open'
): Promise<PullRequest[]> {
const data = await this.fetch<GiteaPRResponse[]>(`/repos/${owner}/${repo}/pulls?state=${state}`);
return data.map(pr => this.transformPullRequest(pr));
}
async updatePullRequest(
owner: string,
repo: string,
number: number,
options: { title?: string; body?: string }
): Promise<PullRequest> {
const data = await this.fetch<GiteaPRResponse>(`/repos/${owner}/${repo}/pulls/${number}`, {
method: 'PATCH',
body: JSON.stringify(options),
});
return this.transformPullRequest(data);
}
async closePullRequest(owner: string, repo: string, number: number): Promise<PullRequest> {
const data = await this.fetch<GiteaPRResponse>(`/repos/${owner}/${repo}/pulls/${number}`, {
method: 'PATCH',
body: JSON.stringify({ state: 'closed' }),
});
return this.transformPullRequest(data);
}
async getCurrentUser(): Promise<GitHostUser> {
interface GiteaUser {
login: string;
full_name: string;
email: string;
avatar_url: string;
}
const data = await this.fetch<GiteaUser>('/user');
return {
username: data.login,
name: data.full_name,
email: data.email,
avatarUrl: data.avatar_url,
};
}
getCompareUrl(baseRepo: string, baseBranch: string, headRepo: string, headBranch: string): string {
const baseUrl = this.apiBaseUrl.replace('/api/v1', '');
const [headOwner, headRepoName] = headRepo.split('/');
return `${baseUrl}/${baseRepo}/compare/${baseBranch}...${headOwner}:${headRepoName}:${headBranch}`;
}
private transformPullRequest(data: {
id: number;
number: number;
state: string;
title: string;
body: string;
html_url: string;
created_at: string;
updated_at: string;
user: { login: string };
head: { ref: string; repo: { full_name: string } };
base: { ref: string; repo: { full_name: string } };
mergeable?: boolean;
merged?: boolean;
}): PullRequest {
const state: 'open' | 'closed' | 'merged' = data.merged ? 'merged' : data.state as 'open' | 'closed';
return {
number: data.number,
title: data.title,
body: data.body,
state,
headBranch: data.head.ref,
baseBranch: data.base.ref,
headRepo: data.head.repo?.full_name || '',
baseRepo: data.base.repo.full_name,
url: data.html_url,
createdAt: new Date(data.created_at),
updatedAt: new Date(data.updated_at),
author: data.user.login,
mergeable: data.mergeable,
};
}
}
+257
View File
@@ -0,0 +1,257 @@
import { NRelay1, type NostrEvent } from '@nostrify/nostrify';
import { parseRepositoryAnnouncement } from '@/lib/announceRepository';
import type {
GitHostProvider,
GitHostConfig,
GitRepository,
GitFork,
PullRequest,
CreatePullRequestOptions,
GitHostUser,
} from './types';
interface NostrSigner {
signEvent: (event: { kind: number; content: string; tags: string[][]; created_at: number }) => Promise<NostrEvent>;
}
/**
* Nostr Git provider implementing NIP-34 (git stuff)
* Enables creating patches/PRs on Nostr git repositories
*/
export class NostrGitProvider implements GitHostProvider {
readonly name = 'Nostr Git';
readonly apiBaseUrl = ''; // Not applicable for Nostr
private relay: NRelay1;
private signer: NostrSigner;
private pubkey: string;
private relayUrls: string[];
constructor(config: GitHostConfig & { signer: NostrSigner; pubkey: string; relayUrls: string[] }) {
this.signer = config.signer;
this.pubkey = config.pubkey;
this.relayUrls = config.relayUrls;
// For Nostr git, we need to publish to the repository's designated relays
// The relay will be set dynamically when we know which repo we're working with
this.relay = new NRelay1('wss://relay.nostr.band'); // Default, will be changed
}
private async queryRepo(owner: string, repo: string): Promise<NostrEvent> {
// Query for repository announcement (kind 30617)
// d tag is the repo-id (usually kebab-case short name)
const events = await this.relay.query([
{
kinds: [30617],
authors: [owner], // owner is the pubkey
'#d': [repo], // repo is the d tag identifier
limit: 1,
}
]) as NostrEvent[];
if (events.length === 0) {
throw new Error(`Repository not found: ${owner}/${repo}`);
}
return events[0];
}
async getRepository(owner: string, repo: string): Promise<GitRepository> {
const event = await this.queryRepo(owner, repo);
// Parse the NIP-34 repository announcement
const repoAnn = parseRepositoryAnnouncement(event);
// Update relay to use repository's designated relays
if (repoAnn.relays.length > 0) {
this.relayUrls = repoAnn.relays;
this.relay = new NRelay1(repoAnn.relays[0]);
}
return {
owner,
name: repoAnn.name || repo,
fullName: `${owner}/${repo}`,
defaultBranch: 'main', // Nostr git doesn't specify, assume main
cloneUrl: repoAnn.httpsCloneUrls[0] || '',
webUrl: repoAnn.webUrls[0] || '',
description: repoAnn.description,
isPrivate: false, // All Nostr repos are public
};
}
async canUserPush(owner: string, repo: string): Promise<boolean> {
// In Nostr git, anyone can submit patches (kind 1617)
// But only maintainers can apply them
// Check if current user is listed as a maintainer
const event = await this.queryRepo(owner, repo);
// Parse the NIP-34 repository announcement
const parsed = parseRepositoryAnnouncement(event);
// Repo owner is always a maintainer
const isMaintainer = owner === this.pubkey || parsed.maintainers.includes(this.pubkey);
return isMaintainer;
}
async createFork(owner: string, repo: string): Promise<GitFork> {
// In Nostr git, there's no explicit "fork" concept
// Users submit patches to the original repo
// For compatibility with the PR flow, we return a "virtual fork"
const repoEvent = await this.queryRepo(owner, repo);
// Parse the NIP-34 repository announcement
const parsed = parseRepositoryAnnouncement(repoEvent);
// The "fork" is actually just the user's local copy
// We'll use this to track that patches come from the user
return {
owner: this.pubkey,
name: repo,
fullName: `${this.pubkey}/${repo}`,
cloneUrl: parsed.httpsCloneUrls[0] || '',
webUrl: parsed.webUrls[0] || '',
parentFullName: `${owner}/${repo}`,
};
}
async getFork(_upstreamOwner: string, _upstreamRepo: string, _username: string): Promise<GitFork | null> {
// Nostr git doesn't have forks - patches are submitted directly
// Return null to indicate no fork exists
return null;
}
async waitForFork(upstreamOwner: string, upstreamRepo: string, _username: string, _timeout = 10000): Promise<GitFork> {
// Create a virtual fork immediately
return this.createFork(upstreamOwner, upstreamRepo);
}
async createPullRequest(options: CreatePullRequestOptions): Promise<PullRequest> {
// In Nostr git, a "pull request" is a patch event (kind 1617)
// The patch content should be the output of `git format-patch`
const [owner, repo] = options.baseRepo.split('/');
const repoEvent = await this.queryRepo(owner, repo);
// Parse the NIP-34 repository announcement
const parsed = parseRepositoryAnnouncement(repoEvent);
// Get the earliest unique commit (euc) for the repository
const euc = parsed.earliestCommit;
// Create patch content from the provided body or generate a simple patch description
const patchContent = options.body ||
`Patch proposal: ${options.title}\n\nFrom: ${options.headBranch}\nTo: ${options.baseBranch}`;
// Create patch event (kind 1617)
const patchEvent = await this.signer.signEvent({
kind: 1617,
content: patchContent,
tags: [
['a', `30617:${owner}:${repo}`], // Reference to repository announcement
['p', owner], // Repository owner
['t', 'root'], // Root patch in series
['t', 'root-revision'], // First patch in a revision
['subject', options.title], // Use subject tag for title
// Optional: Add r tag for euc if available
...(euc ? [['r', euc]] : []),
],
created_at: Math.floor(Date.now() / 1000),
});
// Publish to repository's designated relays
await this.relay.event(patchEvent);
// Return a PullRequest-compatible object
return {
number: parseInt(patchEvent.id.slice(0, 8), 16), // Use first 8 chars of event ID as number
title: options.title,
body: options.body,
state: 'open',
headBranch: options.headBranch,
baseBranch: options.baseBranch,
headRepo: options.headRepo,
baseRepo: options.baseRepo,
url: `nostr:${patchEvent.id}`, // Nostr event reference
createdAt: new Date(patchEvent.created_at * 1000),
updatedAt: new Date(patchEvent.created_at * 1000),
author: this.pubkey,
};
}
async getPullRequest(_owner: string, _repo: string, _number: number): Promise<PullRequest> {
// Query for patch event by converting number back to event ID
// This is a limitation - we'd need to store the mapping or query differently
throw new Error('Getting specific patches by number is not yet implemented for Nostr git');
}
async listPullRequests(owner: string, repo: string, _state: 'open' | 'closed' | 'all' = 'open'): Promise<PullRequest[]> {
// Query for patch events (kind 1617) referencing this repository
const events = await this.relay.query([
{
kinds: [1617],
'#a': [`30617:${owner}:${repo}`],
'#t': ['root'], // Only root patches, not replies
limit: 50,
}
]);
// For state filtering, we'd need to check status events (kind 1630-1633)
// For now, return all as 'open'
return events.map(event => ({
number: parseInt(event.id.slice(0, 8), 16),
title: event.tags.find((t: string[]) => t[0] === 'subject')?.[1] || 'Untitled patch',
body: event.content,
state: 'open' as const,
headBranch: 'unknown', // Not stored in NIP-34
baseBranch: 'unknown', // Not stored in NIP-34
headRepo: `${event.pubkey}/${repo}`,
baseRepo: `${owner}/${repo}`,
url: `nostr:${event.id}`,
createdAt: new Date(event.created_at * 1000),
updatedAt: new Date(event.created_at * 1000),
author: event.pubkey,
}));
}
async updatePullRequest(_owner: string, _repo: string, _number: number, _options: { title?: string; body?: string }): Promise<PullRequest> {
// In Nostr git, you can't edit events - you'd create a new revision
throw new Error('Updating patches is not supported - create a new revision instead');
}
async closePullRequest(_owner: string, _repo: string, _number: number): Promise<PullRequest> {
// To close a patch, publish a status event (kind 1632 - Closed)
throw new Error('Closing patches via status events is not yet implemented');
}
async getCurrentUser(): Promise<GitHostUser> {
// In Nostr, we can query the user's profile (kind 0)
const profiles = await this.relay.query([
{
kinds: [0],
authors: [this.pubkey],
limit: 1,
}
]);
if (profiles.length > 0) {
const profile = JSON.parse(profiles[0].content);
return {
username: profile.name || this.pubkey.slice(0, 8),
name: profile.display_name || profile.name,
email: profile.nip05,
avatarUrl: profile.picture,
};
}
return {
username: this.pubkey.slice(0, 8),
};
}
getCompareUrl(_baseRepo: string, _baseBranch: string, _headRepo: string, _headBranch: string): string {
// Nostr git doesn't have a web compare view
// Could potentially link to a Nostr client that displays patches
return '';
}
}
+64
View File
@@ -0,0 +1,64 @@
export * from './types';
export { GitHubProvider } from './GitHubProvider';
export { GitLabProvider } from './GitLabProvider';
export { GiteaProvider } from './GiteaProvider';
export { NostrGitProvider } from './NostrGitProvider';
import { GitHubProvider } from './GitHubProvider';
import { GitLabProvider } from './GitLabProvider';
import { GiteaProvider } from './GiteaProvider';
import { NostrGitProvider } from './NostrGitProvider';
import { detectGitHost } from './types';
import type { GitHostProvider, GitHostConfig } from './types';
import type { NostrEvent } from '@nostrify/nostrify';
/**
* Create a Git host provider instance based on the repository URL
*/
interface NostrSigner {
signEvent: (event: { kind: number; content: string; tags: string[][]; created_at: number }) => Promise<NostrEvent>;
}
export function createGitHostProvider(
url: string,
config: GitHostConfig & { signer?: NostrSigner; pubkey?: string; relayUrls?: string[] },
corsProxy?: string
): GitHostProvider | null {
const hostType = detectGitHost(url);
switch (hostType) {
case 'github':
return new GitHubProvider(config, corsProxy);
case 'gitlab':
return new GitLabProvider(config, corsProxy);
case 'codeberg':
return new GiteaProvider(config, 'https://codeberg.org/api/v1', 'Codeberg', corsProxy);
case 'gitea':
// Extract API URL from repository URL
try {
const parsed = new URL(url.replace(/^git@/, 'https://').replace(/\.git$/, ''));
const apiUrl = `${parsed.protocol}//${parsed.hostname}/api/v1`;
return new GiteaProvider(config, apiUrl, 'Gitea', corsProxy);
} catch {
return null;
}
case 'nostr':
// Nostr git requires signer and pubkey
if (!config.signer || !config.pubkey) {
throw new Error('Nostr git requires signer and pubkey in config');
}
return new NostrGitProvider({
token: config.token,
signer: config.signer,
pubkey: config.pubkey,
relayUrls: config.relayUrls || ['wss://relay.nostr.band'],
});
default:
return null;
}
}
+186
View File
@@ -0,0 +1,186 @@
import { nip19 } from 'nostr-tools';
/**
* Git host provider abstraction for PR/MR operations
*/
export interface GitHostUser {
username: string;
name?: string;
email?: string;
avatarUrl?: string;
}
export interface GitRepository {
owner: string;
name: string;
fullName: string; // e.g. "owner/repo"
defaultBranch: string;
cloneUrl: string;
webUrl: string;
description?: string;
isPrivate: boolean;
}
export interface GitFork {
owner: string;
name: string;
fullName: string;
cloneUrl: string;
webUrl: string;
parentFullName: string; // The upstream repo
}
export interface PullRequest {
number: number;
title: string;
body?: string;
state: 'open' | 'closed' | 'merged';
headBranch: string;
baseBranch: string;
headRepo: string; // Full name of head repo (fork)
baseRepo: string; // Full name of base repo (upstream)
url: string;
createdAt: Date;
updatedAt: Date;
author: string;
mergeable?: boolean;
checks?: PullRequestCheck[];
}
export interface PullRequestCheck {
name: string;
status: 'pending' | 'success' | 'failure' | 'cancelled';
conclusion?: 'success' | 'failure' | 'neutral' | 'cancelled' | 'skipped' | 'timed_out' | 'action_required';
detailsUrl?: string;
}
export interface CreatePullRequestOptions {
title: string;
body?: string;
headBranch: string;
baseBranch: string;
headRepo: string; // For cross-repo PRs (from fork)
baseRepo: string; // The upstream repo
maintainerCanModify?: boolean;
}
export interface GitHostConfig {
token: string;
username?: string;
}
/**
* Abstract interface for Git hosting providers (GitHub, GitLab, Gitea, etc.)
*/
export interface GitHostProvider {
readonly name: string;
readonly apiBaseUrl: string;
// Repository operations
getRepository(owner: string, repo: string): Promise<GitRepository>;
canUserPush(owner: string, repo: string): Promise<boolean>;
// Fork operations
createFork(owner: string, repo: string): Promise<GitFork>;
getFork(upstreamOwner: string, upstreamRepo: string, username: string): Promise<GitFork | null>;
waitForFork(upstreamOwner: string, upstreamRepo: string, username: string, timeout?: number): Promise<GitFork>;
// Pull request operations
createPullRequest(options: CreatePullRequestOptions): Promise<PullRequest>;
getPullRequest(owner: string, repo: string, number: number): Promise<PullRequest>;
listPullRequests(owner: string, repo: string, state?: 'open' | 'closed' | 'all'): Promise<PullRequest[]>;
updatePullRequest(owner: string, repo: string, number: number, options: { title?: string; body?: string }): Promise<PullRequest>;
closePullRequest(owner: string, repo: string, number: number): Promise<PullRequest>;
// User operations
getCurrentUser(): Promise<GitHostUser>;
// Utility
getCompareUrl(baseRepo: string, baseBranch: string, headRepo: string, headBranch: string): string;
}
/**
* Detect Git host from repository URL
*/
export function detectGitHost(url: string): 'github' | 'gitlab' | 'gitea' | 'codeberg' | 'nostr' | 'unknown' {
try {
// Check for Nostr git URLs (format: nostr://<pubkey>/<repo-id>)
if (url.startsWith('nostr://')) {
return 'nostr';
}
const parsed = new URL(url.replace(/^git@/, 'https://').replace(/\.git$/, ''));
const hostname = parsed.hostname.toLowerCase();
if (hostname === 'github.com') return 'github';
if (hostname === 'gitlab.com') return 'gitlab';
if (hostname === 'codeberg.org') return 'codeberg';
if (hostname.includes('gitea')) return 'gitea';
return 'unknown';
} catch {
return 'unknown';
}
}
/**
* Parse repository owner and name from URL
*/
export function parseRepoUrl(url: string): { owner: string; repo: string } | null {
try {
// Handle Nostr git URLs (format: nostr://<pubkey>/<repo-id>)
if (url.startsWith('nostr://')) {
const match = url.match(/^nostr:\/\/([^/]+)\/(.+)$/);
if (match) {
let owner = match[1]; // pubkey in hex or npub
const repo = match[2]; // repo-id (d tag)
// Convert npub to hex if needed
if (owner.startsWith('npub1')) {
try {
const decoded = nip19.decode(owner);
if (decoded.type === 'npub') {
owner = decoded.data;
}
} catch (err) {
console.error('Failed to decode npub:', err);
return null;
}
}
return {
owner, // pubkey in hex
repo, // repo-id (d tag)
};
}
}
// Handle git@ URLs
const normalized = url.replace(/^git@([^:]+):/, 'https://$1/').replace(/\.git$/, '');
const parsed = new URL(normalized);
const parts = parsed.pathname.split('/').filter(Boolean);
if (parts.length >= 2) {
return {
owner: parts[0],
repo: parts[1],
};
}
} catch {
// Invalid URL
}
return null;
}
/**
* Format repository URL for display
*/
export function formatRepoUrl(url: string): string {
const parsed = parseRepoUrl(url);
if (parsed) {
return `${parsed.owner}/${parsed.repo}`;
}
return url;
}
+71 -17
View File
@@ -12,7 +12,6 @@ vi.mock('nostr-tools', () => ({
nip19: {
decode: vi.fn(),
naddrEncode: vi.fn(),
npubEncode: vi.fn((pubkey: string) => `npub1${pubkey.slice(0, 10)}`),
},
}));
vi.mock('@nostrify/nostrify', () => ({
@@ -306,8 +305,9 @@ describe('Git', () => {
it('uses shakespeare.diy as default author when no Git identity is configured', async () => {
const { readGitSettings } = await import('./configUtils');
vi.mocked(readGitSettings).mockResolvedValue({
credentials: [],
coAuthorEnabled: false,
credentials: {},
hostTokens: {},
coAuthorEnabled: true,
});
await gitInstance.commit({
@@ -323,13 +323,18 @@ describe('Git', () => {
name: 'shakespeare.diy',
email: '[email protected]',
},
committer: {
name: 'shakespeare.diy',
email: '[email protected]',
},
});
});
it('uses custom identity when both name and email are configured', async () => {
const { readGitSettings } = await import('./configUtils');
vi.mocked(readGitSettings).mockResolvedValue({
credentials: [],
credentials: {},
hostTokens: {},
name: 'John Doe',
email: '[email protected]',
coAuthorEnabled: true,
@@ -348,13 +353,18 @@ describe('Git', () => {
name: 'John Doe',
email: '[email protected]',
},
committer: {
name: 'John Doe',
email: '[email protected]',
},
});
});
it('does not add co-author when coAuthorEnabled is false', async () => {
const { readGitSettings } = await import('./configUtils');
vi.mocked(readGitSettings).mockResolvedValue({
credentials: [],
credentials: {},
hostTokens: {},
name: 'John Doe',
email: '[email protected]',
coAuthorEnabled: false,
@@ -373,6 +383,48 @@ describe('Git', () => {
name: 'John Doe',
email: '[email protected]',
},
committer: {
name: 'John Doe',
email: '[email protected]',
},
});
});
it('respects provided author when explicitly passed', async () => {
const { readGitSettings } = await import('./configUtils');
vi.mocked(readGitSettings).mockResolvedValue({
credentials: {},
hostTokens: {},
name: 'John Doe',
email: '[email protected]',
coAuthorEnabled: true,
});
await gitInstance.commit({
dir: '/test',
message: 'Test commit',
author: {
name: 'Custom Author',
email: '[email protected]',
},
committer: {
name: 'Custom Committer',
email: '[email protected]',
},
});
expect(mockGit.commit).toHaveBeenCalledWith({
fs,
dir: '/test',
message: 'Test commit',
author: {
name: 'Custom Author',
email: '[email protected]',
},
committer: {
name: 'Custom Committer',
email: '[email protected]',
},
});
});
});
@@ -391,15 +443,10 @@ describe('Git', () => {
getPublicKey: vi.fn().mockResolvedValue('abcd1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab'),
};
let gitInstanceWithSigner: Git;
beforeEach(() => {
// Mock timers to avoid waiting 5 seconds
vi.useFakeTimers();
// Create a Git instance with a signer
gitInstanceWithSigner = new Git({ fs, nostr, corsProxy, signer: mockSigner });
mockGit.push = vi.fn().mockResolvedValue(undefined);
mockGit.listRemotes = vi.fn().mockResolvedValue([
{ remote: 'origin', url: 'nostr://npub1abc123/my-repo' }
@@ -465,11 +512,12 @@ describe('Git', () => {
mockGit.isDescendent = vi.fn().mockResolvedValue(false);
await expect(
gitInstanceWithSigner.push({
gitInstance.push({
dir: '/test',
remote: 'origin',
ref: 'main',
force: false,
signer: mockSigner,
})
).rejects.toThrow('Updates were rejected');
});
@@ -479,11 +527,12 @@ describe('Git', () => {
mockGit.isDescendent = vi.fn().mockResolvedValue(false);
// Should not throw with force flag
const pushPromise = gitInstanceWithSigner.push({
const pushPromise = gitInstance.push({
dir: '/test',
remote: 'origin',
ref: 'main',
force: true,
signer: mockSigner,
});
// Advance timers to skip the 5 second wait
@@ -500,11 +549,12 @@ describe('Git', () => {
mockGit.isDescendent = vi.fn().mockResolvedValue(true);
// Should not throw
const pushPromise = gitInstanceWithSigner.push({
const pushPromise = gitInstance.push({
dir: '/test',
remote: 'origin',
ref: 'main',
force: false,
signer: mockSigner,
});
// Advance timers to skip the 5 second wait
@@ -520,11 +570,12 @@ describe('Git', () => {
// Mock resolveRef to return the same commit as remote
mockGit.resolveRef = vi.fn().mockResolvedValue('remotecommit456');
await gitInstanceWithSigner.push({
await gitInstance.push({
dir: '/test',
remote: 'origin',
ref: 'main',
force: false,
signer: mockSigner,
});
// Should not have attempted to push (already up-to-date)
@@ -554,11 +605,12 @@ describe('Git', () => {
nostr.relay = vi.fn().mockReturnValue(mockRelay);
// Should not throw even if not a fast-forward (no state to check against)
const pushPromise = gitInstanceWithSigner.push({
const pushPromise = gitInstance.push({
dir: '/test',
remote: 'origin',
ref: 'main',
force: false,
signer: mockSigner,
});
// Advance timers to skip the 5 second wait
@@ -606,11 +658,12 @@ describe('Git', () => {
nostr.relay = vi.fn().mockReturnValue(mockRelay);
// Should not throw (no matching ref in state)
const pushPromise = gitInstanceWithSigner.push({
const pushPromise = gitInstance.push({
dir: '/test',
remote: 'origin',
ref: 'main',
force: false,
signer: mockSigner,
});
// Advance timers to skip the 5 second wait
@@ -658,11 +711,12 @@ describe('Git', () => {
nostr.group = vi.fn().mockReturnValue(mockGroupRelay);
const pushPromise = gitInstanceWithSigner.push({
const pushPromise = gitInstance.push({
dir: '/test',
remote: 'origin',
ref: 'main',
force: false,
signer: mockSigner,
});
// Advance timers to skip the 5 second wait
+255 -140
View File
@@ -1,8 +1,9 @@
import git, { AuthCallback, FetchResult, GitHttpRequest, GitHttpResponse, HttpClient } from 'isomorphic-git';
import git, { FetchResult, GitHttpRequest, GitHttpResponse, HttpClient } from 'isomorphic-git';
import { NIP05 } from '@nostrify/nostrify';
import { nip19 } from 'nostr-tools';
import { proxyUrl } from './proxyUrl';
import { readGitSettings } from './configUtils';
import { parseRepositoryAnnouncement, RepositoryAnnouncement } from './announceRepository';
import { NostrURI } from './NostrURI';
import type { NostrEvent, NostrSigner, NPool } from '@nostrify/nostrify';
import type { JSRuntimeFS } from './JSRuntime';
@@ -11,9 +12,12 @@ export interface GitOptions {
nostr: NPool;
corsProxy?: string;
ngitServers?: string[];
systemAuthor?: { name: string; email: string };
onAuth?: AuthCallback;
signer?: NostrSigner;
}
interface NostrCloneURI {
pubkey: string;
d: string;
relay?: string;
}
/**
@@ -27,21 +31,12 @@ export class Git {
private http: HttpClient;
private nostr: NPool;
private ngitServers: string[];
private systemAuthor: { name: string; email: string };
private onAuth?: AuthCallback;
private signer?: NostrSigner;
constructor(options: GitOptions) {
this.fs = options.fs;
this.http = new GitHttp(options.corsProxy);
this.nostr = options.nostr;
this.ngitServers = options.ngitServers ?? ['git.shakespeare.diy', 'relay.ngit.dev'];
this.systemAuthor = options.systemAuthor ?? {
name: 'shakespeare.diy',
email: '[email protected]',
};
this.onAuth = options.onAuth;
this.signer = options.signer;
}
// Repository initialization and configuration
@@ -55,7 +50,10 @@ export class Git {
async clone(options: Omit<Parameters<typeof git.clone>[0], 'fs' | 'http' | 'corsProxy'>) {
// Check if the URL is a Nostr URI
if (options.url.startsWith('nostr://')) {
const nostrURI = await NostrURI.parse(options.url);
const nostrURI = await this.parseNostrCloneURI(options.url);
if (!nostrURI) {
throw new Error('Invalid Nostr clone URI format');
}
// Try cloning from Nostr
return this.nostrClone(nostrURI, options);
}
@@ -64,7 +62,6 @@ export class Git {
return git.clone({
fs: this.fs,
http: this.http,
onAuth: this.onAuth,
...options,
});
}
@@ -99,19 +96,50 @@ export class Git {
}
// Commits and history
async commit(options: Omit<Parameters<typeof git.commit>[0], 'fs' | 'author'>) {
const { author, coAuthorEnabled } = await this.getGitSettings();
// Add system co-author if enabled
async commit(options: Omit<Parameters<typeof git.commit>[0], 'fs'>) {
// If author is not provided, use Git identity settings
let author = options.author;
let committer = options.committer;
let message = options.message;
if (coAuthorEnabled) {
message = `${message}\n\nCo-authored-by: ${this.systemAuthor.name} <${this.systemAuthor.email}>`;
if (!author || !committer) {
// Read Git identity settings from config
const gitSettings = await readGitSettings(this.fs);
// Determine author based on Git identity settings
const defaultAuthor = {
name: 'shakespeare.diy',
email: '[email protected]',
};
const hasCustomIdentity = gitSettings.name && gitSettings.email;
if (hasCustomIdentity) {
const customAuthor = {
name: gitSettings.name!,
email: gitSettings.email!,
};
// Use custom identity
if (!author) author = customAuthor;
if (!committer) committer = customAuthor;
// Add Shakespeare as co-author if enabled
if (gitSettings.coAuthorEnabled ?? true) {
message = `${message}\n\nCo-authored-by: shakespeare.diy <[email protected]>`;
}
} else {
// Use Shakespeare as default author
if (!author) author = defaultAuthor;
if (!committer) committer = defaultAuthor;
}
}
return git.commit({
fs: this.fs,
...options,
author,
committer,
message,
});
}
@@ -191,13 +219,11 @@ export class Git {
async getRemoteInfo(options: Omit<Parameters<typeof git.getRemoteInfo>[0], 'http' | 'corsProxy'>) {
// Check if the URL is a Nostr URI
if (options.url.startsWith('nostr://')) {
const nostrURI = await NostrURI.parse(options.url);
return this.getNostrRemoteInfo(nostrURI);
return this.getNostrRemoteInfo(options.url);
}
return git.getRemoteInfo({
http: this.http,
onAuth: this.onAuth,
...options,
});
}
@@ -209,56 +235,51 @@ export class Git {
const remoteUrl = await this.getRemoteURL(dir, remote);
if (remoteUrl && remoteUrl.startsWith('nostr://')) {
const nostrURI = await NostrURI.parse(remoteUrl);
return this.nostrFetch(nostrURI, { ...options, remote, dir });
return this.nostrFetch(remoteUrl, { ...options, remote, dir });
}
// Regular Git fetch
return git.fetch({
fs: this.fs,
http: this.http,
onAuth: this.onAuth,
...options,
});
}
async pull(options: Omit<Parameters<typeof git.pull>[0], 'fs' | 'http' | 'author' | 'corsProxy'>) {
async pull(options: Omit<Parameters<typeof git.pull>[0], 'fs' | 'http' | 'corsProxy'>) {
// Check if this is a Nostr repository by looking at the remote URL
const remote = options.remote || 'origin';
const dir = options.dir || '.';
const remoteUrl = await this.getRemoteURL(dir, remote);
const { author } = await this.getGitSettings();
if (remoteUrl && remoteUrl.startsWith('nostr://')) {
const nostrURI = await NostrURI.parse(remoteUrl);
return this.nostrPull(nostrURI, { ...options, author, remote, dir });
return this.nostrPull(remoteUrl, { ...options, remote, dir });
}
// Regular Git pull
return git.pull({
fs: this.fs,
http: this.http,
onAuth: this.onAuth,
...options,
author,
});
}
async push(options: Omit<Parameters<typeof git.push>[0], 'fs' | 'http' | 'onAuth' | 'corsProxy'>) {
async push(options: Omit<Parameters<typeof git.push>[0], 'fs' | 'http' | 'corsProxy'> & { signer?: NostrSigner }) {
// Check if this is a Nostr repository by looking at the remote URL
const remote = options.remote || 'origin';
const dir = options.dir || '.';
const remoteUrl = await this.getRemoteURL(dir, remote);
if (remoteUrl && remoteUrl.startsWith('nostr://')) {
const nostrURI = await NostrURI.parse(remoteUrl);
return this.nostrPush(nostrURI, { ...options, remote, dir: dir });
if (!options.signer) {
throw new Error('Nostr signer is required for pushing to Nostr repositories');
}
return this.nostrPush(remoteUrl, { ...options, remote, dir: dir, signer: options.signer });
}
return git.push({
fs: this.fs,
http: this.http,
onAuth: this.onAuth,
...options,
});
}
@@ -376,13 +397,10 @@ export class Git {
}
// Merge operations
async merge(options: Omit<Parameters<typeof git.merge>[0], 'fs' | 'author'>) {
const { author } = await this.getGitSettings();
async merge(options: Omit<Parameters<typeof git.merge>[0], 'fs'>) {
return git.merge({
fs: this.fs,
...options,
author,
});
}
@@ -411,7 +429,6 @@ export class Git {
async getRemoteInfo2(options: Omit<Parameters<typeof git.getRemoteInfo2>[0], 'http' | 'corsProxy'>) {
return git.getRemoteInfo2({
http: this.http,
onAuth: this.onAuth,
...options,
});
}
@@ -537,7 +554,6 @@ export class Git {
async listServerRefs(options: Omit<Parameters<typeof git.listServerRefs>[0], 'http' | 'corsProxy'>) {
return git.listServerRefs({
http: this.http,
onAuth: this.onAuth,
...options,
});
}
@@ -582,37 +598,23 @@ export class Git {
return git.version();
}
private async getGitSettings(): Promise<{ author: { name: string; email: string }; coAuthorEnabled: boolean }> {
const {
name,
email,
coAuthorEnabled = true,
} = await readGitSettings(this.fs);
if (name && email) {
return {
author: { name, email },
coAuthorEnabled,
};
} else {
return {
author: this.systemAuthor,
coAuthorEnabled,
}
}
}
// Nostr-specific helper methods
/**
* Get remote info for a Nostr repository URI
*/
private async getNostrRemoteInfo(nostrURI: NostrURI): Promise<{
private async getNostrRemoteInfo(nostrUrl: string): Promise<{
capabilities: string[];
refs: Record<string, string>;
HEAD?: string;
}> {
console.log(`Getting remote info for Nostr repository: ${nostrURI.toString()}`);
// Parse the Nostr URI
const nostrURI = await this.parseNostrCloneURI(nostrUrl);
if (!nostrURI) {
throw new Error('Invalid Nostr URI format');
}
console.log(`Getting remote info for Nostr repository: ${nostrUrl}`);
// Fetch the repository announcement and state from Nostr
const { repo, state } = await this.fetchNostrRepoEvents(nostrURI);
@@ -641,7 +643,6 @@ export class Git {
try {
const gitRemoteInfo = await git.getRemoteInfo({
http: this.http,
onAuth: this.onAuth,
url: repo.httpsCloneUrls[0],
});
@@ -898,7 +899,63 @@ export class Git {
return { valid, warnings };
}
private async parseNostrCloneURI(uri: string): Promise<NostrCloneURI | null> {
try {
if (!uri.startsWith('nostr://')) {
return null;
}
const path = uri.slice(8); // Remove 'nostr://' prefix
const parts = path.split('/');
if (parts.length < 2) {
return null;
}
const identifier = parts[0];
let pubkey: string;
// Try to decode as npub first, otherwise assume it's already a hex pubkey
try {
const decoded = nip19.decode(identifier);
if (decoded.type === 'npub') {
pubkey = decoded.data;
} else {
return null;
}
} catch {
// If decoding fails, check if it's a NIP-05 identifier
if (identifier.split('@').length === 2) {
const pointer = await NIP05.lookup(identifier, {
signal: AbortSignal.timeout(3000),
});
pubkey = pointer.pubkey;
} else {
return null;
}
}
// Check if we have relay and d-tag or just d-tag
if (parts.length === 3) {
// Format: nostr://npub/relay/d
return {
pubkey,
relay: `wss://${parts[1]}/`,
d: parts[2],
};
} else if (parts.length === 2) {
// Format: nostr://npub/d
return {
pubkey,
d: parts[1],
};
}
return null;
} catch {
return null;
}
}
/**
* Process GRASP server mismatch between configured servers and announcement servers.
@@ -926,7 +983,7 @@ export class Git {
}
}
private async fetchNostrRepoEvents(nostrURI: NostrURI): Promise<{
private async fetchNostrRepoEvents(nostrURI: NostrCloneURI): Promise<{
repo: RepositoryAnnouncement;
state?: RespositoryState;
serversWithoutAnnouncement?: string[];
@@ -939,7 +996,7 @@ export class Git {
const filter = {
kinds: [30617, 30618],
authors: [nostrURI.pubkey],
'#d': [nostrURI.identifier],
'#d': [nostrURI.d],
};
// Track all servers we've queried to avoid duplicates
@@ -1104,7 +1161,7 @@ export class Git {
};
}
private async nostrClone(nostrURI: NostrURI, options: Omit<Parameters<typeof git.clone>[0], 'fs' | 'http' | 'corsProxy'>): Promise<void> {
private async nostrClone(nostrURI: NostrCloneURI, options: Omit<Parameters<typeof git.clone>[0], 'fs' | 'http' | 'corsProxy'>): Promise<void> {
// Fetch events from Nostr
const { repo, state } = await this.fetchNostrRepoEvents(nostrURI);
@@ -1151,7 +1208,6 @@ export class Git {
const remoteInfo = await Promise.race([
git.getRemoteInfo({
http: this.http,
onAuth: this.onAuth,
url: cloneUrl,
}),
new Promise<never>((_, reject) =>
@@ -1179,7 +1235,6 @@ export class Git {
git.clone({
fs: this.fs,
http: this.http,
onAuth: this.onAuth,
...options,
url: cloneUrl,
}),
@@ -1237,7 +1292,6 @@ export class Git {
git.clone({
fs: this.fs,
http: this.http,
onAuth: this.onAuth,
...options,
url: bestCloneUrl,
}),
@@ -1265,7 +1319,6 @@ export class Git {
git.clone({
fs: this.fs,
http: this.http,
onAuth: this.onAuth,
...options,
url: cloneUrl,
}),
@@ -1288,9 +1341,9 @@ export class Git {
throw lastError || new Error('All clone attempts failed');
}
// After successful clone, update the remote to point to the Nostr URI
// After successful clone, update the origin remote to point to the Nostr URI
await this.setRemoteURL({
remote: options.remote || 'origin',
remote: 'origin',
dir: options.dir,
url: options.url,
});
@@ -1299,7 +1352,11 @@ export class Git {
await this.setConfig({
dir: options.dir,
path: 'nostr.repo',
value: nostrURI.toNaddr(),
value: nip19.naddrEncode({
kind: 30617,
pubkey: nostrURI.pubkey,
identifier: nostrURI.d,
})
});
// Validate the cloned repository against the expected state
@@ -1498,7 +1555,6 @@ export class Git {
try {
const result = await git.getRemoteInfo({
http: this.http,
onAuth: this.onAuth,
url: cloneUrl,
});
return { cloneUrl, result };
@@ -1599,8 +1655,14 @@ export class Git {
return differences;
}
private async nostrFetch(nostrURI: NostrURI, options: Omit<Parameters<typeof git.fetch>[0], 'fs' | 'http' | 'corsProxy'> & { remote: string; dir: string }): Promise<FetchResult> {
console.log(`Fetching updates from Nostr repository: ${nostrURI.toString()}`);
private async nostrFetch(nostrUrl: string, options: Omit<Parameters<typeof git.fetch>[0], 'fs' | 'http' | 'corsProxy'> & { remote: string; dir: string }): Promise<FetchResult> {
// Parse the Nostr URI
const nostrURI = await this.parseNostrCloneURI(nostrUrl);
if (!nostrURI) {
throw new Error('Invalid Nostr URI format');
}
console.log(`Fetching updates from Nostr repository: ${nostrUrl}`);
// Fetch the latest repository state from Nostr
const { repo, state, serversWithoutLatestAnnouncement, serversWithoutLatestState } = await this.fetchNostrRepoEvents(nostrURI);
@@ -1687,9 +1749,9 @@ export class Git {
}
}
private async nostrPull(nostrURI: NostrURI, options: Omit<Parameters<typeof git.pull>[0], 'fs' | 'http' | 'corsProxy'> & { remote: string; dir: string }): Promise<void> {
private async nostrPull(nostrUrl: string, options: Omit<Parameters<typeof git.pull>[0], 'fs' | 'http' | 'corsProxy'> & { remote: string; dir: string }): Promise<void> {
// First, fetch the latest state
const fetchResult = await this.nostrFetch(nostrURI, options);
const fetchResult = await this.nostrFetch(nostrUrl, options);
// Get the current branch
const currentBranch = await git.currentBranch({ fs: this.fs, dir: options.dir });
@@ -1764,7 +1826,6 @@ export class Git {
ours: currentCommit,
theirs: upstreamCommit,
message: `Merge remote-tracking branch '${options.remote}/${currentBranch}' from Nostr`,
author: options.author,
});
if (mergeResult.alreadyMerged) {
@@ -1775,17 +1836,20 @@ export class Git {
}
}
private async nostrPush(nostrURI: NostrURI, options: Omit<Parameters<typeof git.push>[0], 'fs' | 'http' | 'onAuth' | 'corsProxy'>) {
if (!this.signer) {
throw new Error('Nostr signer is required for pushing to Nostr repositories');
}
private async nostrPush(nostrUrl: string, options: Omit<Parameters<typeof git.push>[0], 'fs' | 'http' | 'corsProxy'> & { signer: NostrSigner }) {
const { signer, ...gitPushOptions } = options;
const dir = options.dir || '.';
const ref = options.ref || 'HEAD';
const remoteRef = options.remoteRef || ref;
const force = options.force || false;
console.log(`Pushing to Nostr repository: ${nostrURI.toString()}`);
// Parse the Nostr URI
const nostrURI = await this.parseNostrCloneURI(nostrUrl);
if (!nostrURI) {
throw new Error('Invalid Nostr URI format');
}
console.log(`Pushing to Nostr repository: ${nostrUrl}`);
// Fetch the repository announcement and state to get relay information and current remote state
// Also check which servers don't have the latest announcement
@@ -1918,10 +1982,10 @@ export class Git {
}
// Apply push changes and create updated event
stateEvent = await this.applyPushAndUpdateStateEvent(state, remoteRef, localCommit, this.signer);
stateEvent = await this.applyPushAndUpdateStateEvent(state, remoteRef, localCommit, signer);
} else {
// No existing state event - create initial state from repository
stateEvent = await this.createInitialRepositoryState(dir, nostrURI.identifier, this.signer);
stateEvent = await this.createInitialRepositoryState(dir, nostrURI.d, signer);
}
// Publish the state event to Nostr relays
@@ -1954,13 +2018,13 @@ export class Git {
console.log(`Pushing to Git remote: ${cloneUrl}`);
try {
// Push to the temporary remote
await git.push({
fs: this.fs,
http: this.http,
onAuth: this.onAuth,
dir,
url: cloneUrl,
...options,
...gitPushOptions,
});
pushSuccessful = true;
@@ -1983,21 +2047,50 @@ export class Git {
try {
console.log(`Fetching from Git remote: ${httpsCloneUrl}`);
// Fetch from the temporary remote
const fetchResult = await git.fetch({
// Add a temporary remote
const tempRemoteName = `temp-${Date.now()}`;
await git.addRemote({
fs: this.fs,
http: this.http,
onAuth: this.onAuth,
dir,
tags: true,
remote: tempRemoteName,
url: httpsCloneUrl,
});
return {
fetchHead: fetchResult.fetchHead || null,
fetchHeadDescription: `Fetched from Git remote: ${httpsCloneUrl}`,
defaultBranch: fetchResult.defaultBranch || null,
};
try {
// Fetch from the temporary remote
const fetchResult = await git.fetch({
fs: this.fs,
http: this.http,
dir,
tags: true,
remote: tempRemoteName,
});
// Remove the temporary remote
await git.deleteRemote({
fs: this.fs,
dir,
remote: tempRemoteName,
});
return {
fetchHead: fetchResult.fetchHead || null,
fetchHeadDescription: `Fetched from Git remote: ${httpsCloneUrl}`,
defaultBranch: fetchResult.defaultBranch || null,
};
} catch (fetchError) {
// Clean up the temporary remote
try {
await git.deleteRemote({
fs: this.fs,
dir,
remote: tempRemoteName,
});
} catch {
// Ignore cleanup errors
}
throw fetchError;
}
} catch (error) {
console.warn(`Failed to fetch from ${httpsCloneUrl}:`, error);
throw error instanceof Error ? error : new Error('Unknown error');
@@ -2167,49 +2260,69 @@ export class Git {
toCreate: changes.refsToCreate.length,
});
// Push all refs that need to be created or updated
const refsToPush = [...changes.refsToCreate, ...changes.refsToUpdate];
// Add a temporary remote
const tempRemoteName = `sync-${Date.now()}`;
await git.addRemote({
fs: this.fs,
dir,
remote: tempRemoteName,
url: cloneUrl,
});
if (refsToPush.length > 0) {
for (const ref of refsToPush) {
try {
await git.push({
fs: this.fs,
http: this.http,
onAuth: this.onAuth,
dir,
url: cloneUrl,
ref,
force: true, // Force push to ensure refs are updated
});
console.log(` ✓ Pushed ${ref}`);
} catch (pushError) {
console.warn(` ✗ Failed to push ${ref}:`, pushError);
try {
// Push all refs that need to be created or updated
const refsToPush = [...changes.refsToCreate, ...changes.refsToUpdate];
if (refsToPush.length > 0) {
for (const ref of refsToPush) {
try {
await git.push({
fs: this.fs,
http: this.http,
dir,
remote: tempRemoteName,
ref,
force: true, // Force push to ensure refs are updated
});
console.log(` ✓ Pushed ${ref}`);
} catch (pushError) {
console.warn(` ✗ Failed to push ${ref}:`, pushError);
}
}
}
}
// Delete refs that should not exist on the remote
// Note: Git push with :ref syntax deletes remote refs
if (changes.refsToDelete.length > 0) {
for (const ref of changes.refsToDelete) {
try {
await git.push({
fs: this.fs,
http: this.http,
onAuth: this.onAuth,
dir,
url: cloneUrl,
ref: `:${ref}`, // :ref syntax deletes the remote ref
});
console.log(` ✓ Deleted ${ref}`);
} catch (deleteError) {
console.warn(` ✗ Failed to delete ${ref}:`, deleteError);
// Delete refs that should not exist on the remote
// Note: Git push with :ref syntax deletes remote refs
if (changes.refsToDelete.length > 0) {
for (const ref of changes.refsToDelete) {
try {
await git.push({
fs: this.fs,
http: this.http,
dir,
remote: tempRemoteName,
ref: `:${ref}`, // :ref syntax deletes the remote ref
});
console.log(` ✓ Deleted ${ref}`);
} catch (deleteError) {
console.warn(` ✗ Failed to delete ${ref}:`, deleteError);
}
}
}
}
console.log(`✓ Synced ${cloneUrl}`);
console.log(`✓ Synced ${cloneUrl}`);
} finally {
// Clean up the temporary remote
try {
await git.deleteRemote({
fs: this.fs,
dir,
remote: tempRemoteName,
});
} catch {
// Ignore cleanup errors
}
}
} catch (error) {
console.warn(`Failed to sync ${cloneUrl}:`, error);
}
@@ -2258,6 +2371,9 @@ class GitHttp implements HttpClient {
}
}
// Drain an async iterable of Uint8Array into one Uint8Array
async function collectToUint8Array(
src: AsyncIterable<Uint8Array> | AsyncIterableIterator<Uint8Array>
@@ -2309,7 +2425,6 @@ interface RespositoryState {
headBranch?: string;
refs: Record<string, string>;
}
/**
* Parse repository state information from a NIP-34 repository state event
*/
Loaded 100 of 126 files, more files were not shown because too many files have changed in this diff. Show more