mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 16:03:34 +00:00
Compare commits
148
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
764319223a | ||
|
|
7f5265cc92 | ||
|
|
7f4b7f2a03 | ||
|
|
34ede4b799 | ||
|
|
d5c28c3097 | ||
|
|
31de1b934d | ||
|
|
45f1202b9d | ||
|
|
b4f0ede7b7 | ||
|
|
df39f78d20 | ||
|
|
b7e94ff67c | ||
|
|
8b981dcf36 | ||
|
|
f702d2300b | ||
|
|
4edbb8a73a | ||
|
|
98f584a851 | ||
|
|
8b438c8c1b | ||
|
|
d18cfb4849 | ||
|
|
b04c1440b5 | ||
|
|
5fa16115fd | ||
|
|
795eaa50c2 | ||
|
|
3da2075539 | ||
|
|
a87063f6e9 | ||
|
|
75cab68281 | ||
|
|
1abc37f388 | ||
|
|
24c8525360 | ||
|
|
2f4fb16e94 | ||
|
|
3e8d5fb87c | ||
|
|
7b438bae34 | ||
|
|
cb4cc16760 | ||
|
|
aca620e460 | ||
|
|
89db9c354a | ||
|
|
fc0134a3a8 | ||
|
|
2477b5417c | ||
|
|
92483728d0 | ||
|
|
ba0ec1f420 | ||
|
|
bdcaa2ef76 | ||
|
|
d1d8f1dd15 | ||
|
|
66d08d05de | ||
|
|
bb8912dd57 | ||
|
|
804cdbd789 | ||
|
|
f022332595 | ||
|
|
ba509584b7 | ||
|
|
787877d2c7 | ||
|
|
0b269f78a4 | ||
|
|
7a11137aed | ||
|
|
1d0231bc03 | ||
|
|
8b62ba8e7e | ||
|
|
4e0625721e | ||
|
|
3529d43b91 | ||
|
|
93a636589d | ||
|
|
eba609ae73 | ||
|
|
8c60a3a8bc | ||
|
|
939deabb5b | ||
|
|
2ec32f5537 | ||
|
|
124e9d5937 | ||
|
|
b064c9ff86 | ||
|
|
a9a5cafcac | ||
|
|
2db9d5e513 | ||
|
|
e8156243d0 | ||
|
|
e9c73693ce | ||
|
|
1a9a553523 | ||
|
|
fc6a70793f | ||
|
|
fba1328e5f | ||
|
|
a45e29578c | ||
|
|
c1cbbed05c | ||
|
|
d95abf2499 | ||
|
|
4316b766e2 | ||
|
|
8800a55eed | ||
|
|
48dfd2d99e | ||
|
|
cb971955ae | ||
|
|
deb593c1b6 | ||
|
|
3b3637009d | ||
|
|
dc50d41928 | ||
|
|
ca334d7585 | ||
|
|
57a80ad33d | ||
|
|
a05ad13e67 | ||
|
|
247919a24b | ||
|
|
9b43f07372 | ||
|
|
af8fb22438 | ||
|
|
fc4e82c26d | ||
|
|
3b305b5b86 | ||
|
|
456ea946e7 | ||
|
|
6c770630d8 | ||
|
|
8f4598b9b8 | ||
|
|
64c06ec430 | ||
|
|
29aae4f55b | ||
|
|
fb12bda5fa | ||
|
|
7348aaf9ce | ||
|
|
8948507b6f | ||
|
|
2dbb9a23e3 | ||
|
|
11867b3bb2 | ||
|
|
0f82ab15ec | ||
|
|
80ae098323 | ||
|
|
fa64a5ce52 | ||
|
|
870e2f6b9b | ||
|
|
26c09733f8 | ||
|
|
2a80e586ba | ||
|
|
9f20fd6196 | ||
|
|
94bcc7eccb | ||
|
|
f62b2f807c | ||
|
|
374d2804ad | ||
|
|
c0f906ae7e | ||
|
|
92e2ac1ce5 | ||
|
|
e81fb33ffe | ||
|
|
9a65d5d086 | ||
|
|
61d5a5fefc | ||
|
|
75e961d281 | ||
|
|
93e992f128 | ||
|
|
7ab30af944 | ||
|
|
6296fc4366 | ||
|
|
147c7cdf3a | ||
|
|
18a276a44e | ||
|
|
a20bbfdf29 | ||
|
|
980cb60f1b | ||
|
|
2956c86f88 | ||
|
|
c46077af67 | ||
|
|
e5ca49962e | ||
|
|
f5c5684ac8 | ||
|
|
6a72711aa0 | ||
|
|
1ed4a5abd4 | ||
|
|
db57619bca | ||
|
|
0f4075ce38 | ||
|
|
37147a69d4 | ||
|
|
ec5d84d3f7 | ||
|
|
0b949d55b9 | ||
|
|
25f14ee2b3 | ||
|
|
7057c34f01 | ||
|
|
d932f05d04 | ||
|
|
e9f8e99ac5 | ||
|
|
4f9d3ae1d1 | ||
|
|
fdfdcb4b16 | ||
|
|
50e16e1b57 | ||
|
|
662f95d35d | ||
|
|
458eec0e27 | ||
|
|
74e472338d | ||
|
|
2b5e3013ff | ||
|
|
951eefb7b8 | ||
|
|
a68d37452b | ||
|
|
c8653e67dc | ||
|
|
660f25656c | ||
|
|
804efb4d23 | ||
|
|
8108407478 | ||
|
|
41d7d7834d | ||
|
|
785f75a39a | ||
|
|
8e3cc67ce2 | ||
|
|
fae90cc85e | ||
|
|
2ed44e43f7 | ||
|
|
53cf844fd6 | ||
|
|
6aa36b6738 |
No files matched your search
@@ -51,6 +51,7 @@ Shakespeare provides AI agents with specialized tools for project development (n
|
||||
- **NostrReadNipsIndexTool**: Read the full list of NIPs, kinds, and tags
|
||||
- **NostrFetchEventTool**: Fetch Nostr events using NIP-19 identifiers
|
||||
- **NostrGenerateKindTool**: Generate unused Nostr event kind numbers
|
||||
- **ReadConsoleMessagesTool**: Read console messages from project preview with filtering capabilities
|
||||
|
||||
#### Shell Commands
|
||||
|
||||
|
||||
@@ -148,6 +148,36 @@ consistent handling of both text and binary data across the messaging protocol.
|
||||
|
||||
**Result:** None (notification only, no response expected)
|
||||
|
||||
### Navigation Methods
|
||||
|
||||
#### `navigate`
|
||||
**Purpose:** Navigate iframe to a new URL within the same origin
|
||||
**Parameters:** `url` (string) - Target URL (must be same origin)
|
||||
**Result:** None (notification only)
|
||||
|
||||
#### `refresh`
|
||||
**Purpose:** Refresh/reload the current page in the iframe
|
||||
**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:**
|
||||
- `currentUrl` (string) - Current URL of the iframe
|
||||
- `canGoBack` (boolean) - Whether iframe can go back in history
|
||||
- `canGoForward` (boolean) - Whether iframe can go forward in history
|
||||
**Result:** None (notification only)
|
||||
|
||||
## Implementation
|
||||
|
||||
### Parent Page
|
||||
|
||||
@@ -136,7 +136,27 @@ The system now uses a simplified JSON-RPC 2.0 protocol with two methods:
|
||||
- Parent responds with serialized HTTP responses
|
||||
- ServiceWorker creates Response objects and returns them to the client app
|
||||
|
||||
3. **Content Replacement:**
|
||||
3. **SPA Routing Support:**
|
||||
- ServiceWorker detects navigation requests (HTML page requests with `mode: "navigate"`)
|
||||
- For SPA routes like `/about`, `/contact`, etc., the ServiceWorker serves the site's `index.html`
|
||||
- This allows the SPA's client-side router to handle the route properly
|
||||
- All other requests (assets, API calls, etc.) are handled normally via JSON-RPC
|
||||
|
||||
4. **Semantic Path Navigation:**
|
||||
- **Key Concept**: iframe stays on base URL (`/`) while communicating semantic paths to parent
|
||||
- When user navigates to `/about` in address bar, iframe doesn't actually change URL
|
||||
- Instead, NavigationHandler tracks semantic path (`/about`) and communicates it to parent
|
||||
- Parent displays semantic path while iframe remains on base URL
|
||||
- SPA's client-side router handles navigation internally without page reloads
|
||||
- This prevents 404 errors from literal path navigation
|
||||
|
||||
5. **SPA Navigation Tracking:**
|
||||
- NavigationHandler overrides `history.pushState()` and `history.replaceState()` to detect SPA navigation
|
||||
- When SPAs change URLs via history methods, NavigationHandler detects the change and sends navigation state to parent
|
||||
- Navigation state includes semantic path, back/forward capability, and history tracking
|
||||
- Parent can display current semantic path and enable proper back/forward navigation controls
|
||||
|
||||
6. **Content Replacement:**
|
||||
- Main thread requests `/` from parent via JSON-RPC fetch
|
||||
- Replaces its own content with the site index
|
||||
- Site runs normally, with all requests handled by SW via JSON-RPC
|
||||
@@ -322,6 +342,14 @@ function handleRequest(fetchRequest) {
|
||||
- Check that JSON-RPC messages are properly formatted
|
||||
- Ensure iframe has appropriate sandbox permissions
|
||||
|
||||
### SPA routes don't work
|
||||
|
||||
- Ensure the parent page serves the correct `index.html` for the root path `/`
|
||||
- Check that the SPA's client-side router is properly configured
|
||||
- Verify that navigation requests are being detected correctly by the ServiceWorker
|
||||
- Make sure the parent page returns the same `index.html` content for SPA routes as it does for the root path
|
||||
- **Important**: iframe should stay on base URL (`/`) while semantic paths are communicated to parent. If you see literal path navigation (iframe URL changing to `/about`), this indicates a configuration issue.
|
||||
|
||||
## Development
|
||||
|
||||
To modify the system:
|
||||
|
||||
@@ -13,6 +13,11 @@ class JSONRPCClient {
|
||||
|
||||
setupMessageListener() {
|
||||
window.addEventListener("message", (event) => {
|
||||
// Only accept messages from parent window for security
|
||||
if (event.source !== window.parent) {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = event.data;
|
||||
// Check if this is a response to our own request or a ServiceWorker request
|
||||
if (message.jsonrpc === "2.0" && message.id !== undefined) {
|
||||
@@ -148,19 +153,202 @@ class ConsoleInterceptor {
|
||||
}
|
||||
}
|
||||
|
||||
// Navigation Handler - manages iframe navigation and history
|
||||
class NavigationHandler {
|
||||
constructor() {
|
||||
// Get initial path from window property or default to root
|
||||
this.currentSemanticPath = window.__IFRAME_INITIAL_PATH__ || '/';
|
||||
|
||||
this.setupMessageListener();
|
||||
this.setupHistoryListeners();
|
||||
this.overrideHistoryMethods();
|
||||
this.updateNavigationState();
|
||||
}
|
||||
|
||||
// Extract semantic path from URL or string
|
||||
extractSemanticPath(urlOrString) {
|
||||
try {
|
||||
const url = typeof urlOrString === 'string'
|
||||
? new URL(urlOrString, window.location.origin)
|
||||
: urlOrString;
|
||||
return url.pathname + url.search + url.hash;
|
||||
} catch {
|
||||
return window.location.pathname + window.location.search + window.location.hash;
|
||||
}
|
||||
}
|
||||
|
||||
setupMessageListener() {
|
||||
window.addEventListener("message", (event) => {
|
||||
// Only accept messages from parent window for security
|
||||
if (event.source !== window.parent) {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = event.data;
|
||||
if (message.jsonrpc === "2.0") {
|
||||
switch (message.method) {
|
||||
case "navigate":
|
||||
this.handleNavigate(message.params.url);
|
||||
break;
|
||||
case "refresh":
|
||||
this.handleRefresh();
|
||||
break;
|
||||
case "goBack":
|
||||
this.handleGoBack();
|
||||
break;
|
||||
case "goForward":
|
||||
this.handleGoForward();
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
setupHistoryListeners() {
|
||||
// Listen for popstate events (back/forward navigation)
|
||||
window.addEventListener('popstate', () => {
|
||||
this.currentSemanticPath = this.extractSemanticPath(window.location);
|
||||
this.updateNavigationState();
|
||||
});
|
||||
|
||||
// Listen for hash changes
|
||||
window.addEventListener('hashchange', () => {
|
||||
this.currentSemanticPath = this.extractSemanticPath(window.location);
|
||||
this.updateNavigationState();
|
||||
});
|
||||
}
|
||||
|
||||
overrideHistoryMethods() {
|
||||
// Override history.pushState and history.replaceState to detect SPA navigation
|
||||
this.originalPushState = window.history.pushState;
|
||||
this.originalReplaceState = window.history.replaceState;
|
||||
|
||||
window.history.pushState = (...args) => {
|
||||
const result = this.originalPushState.apply(window.history, args);
|
||||
|
||||
// Extract semantic path from URL argument or use current location
|
||||
const semanticPath = args[2]
|
||||
? this.extractSemanticPath(args[2])
|
||||
: this.extractSemanticPath(window.location);
|
||||
|
||||
this.currentSemanticPath = semanticPath;
|
||||
this.updateNavigationState();
|
||||
return result;
|
||||
};
|
||||
|
||||
window.history.replaceState = (...args) => {
|
||||
const result = this.originalReplaceState.apply(window.history, args);
|
||||
|
||||
const semanticPath = args[2]
|
||||
? this.extractSemanticPath(args[2])
|
||||
: this.extractSemanticPath(window.location);
|
||||
|
||||
this.currentSemanticPath = semanticPath;
|
||||
this.updateNavigationState();
|
||||
return result;
|
||||
};
|
||||
}
|
||||
|
||||
handleNavigate(url) {
|
||||
try {
|
||||
// Validate URL - must be same origin
|
||||
const targetUrl = new URL(url, window.location.origin);
|
||||
if (targetUrl.origin !== window.location.origin) {
|
||||
console.error('Navigation to different origin not allowed:', url);
|
||||
return;
|
||||
}
|
||||
|
||||
const semanticPath = this.extractSemanticPath(targetUrl);
|
||||
this.currentSemanticPath = semanticPath;
|
||||
this.updateNavigationState();
|
||||
|
||||
// Trigger SPA navigation
|
||||
window.history.pushState({}, '', semanticPath);
|
||||
window.dispatchEvent(new PopStateEvent('popstate', { state: {} }));
|
||||
|
||||
} catch (error) {
|
||||
console.error('Invalid navigation URL:', url, error);
|
||||
}
|
||||
}
|
||||
|
||||
handleRefresh() {
|
||||
// Store current semantic path for reload
|
||||
const currentPath = this.currentSemanticPath || '/';
|
||||
|
||||
// Save the current path to sessionStorage so it persists across reload
|
||||
try {
|
||||
sessionStorage.setItem('iframe_initial_path', currentPath);
|
||||
} catch (error) {
|
||||
console.warn('Failed to store initial path in sessionStorage:', error);
|
||||
}
|
||||
|
||||
// Actually reload the iframe to get a fresh SPA instance
|
||||
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);
|
||||
|
||||
const state = {
|
||||
currentUrl: semanticPath,
|
||||
canGoBack: false, // Let parent handle history tracking
|
||||
canGoForward: false // Let parent handle history tracking
|
||||
};
|
||||
|
||||
// Send navigation state to parent
|
||||
try {
|
||||
window.parent.postMessage({
|
||||
jsonrpc: "2.0",
|
||||
method: "updateNavigationState",
|
||||
params: state
|
||||
}, "*");
|
||||
} catch (error) {
|
||||
console.error('Failed to send navigation state:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Main Fetch Client
|
||||
class FetchClient {
|
||||
constructor() {
|
||||
this.rpcClient = new JSONRPCClient();
|
||||
this.consoleInterceptor = new ConsoleInterceptor();
|
||||
this.navigationHandler = new NavigationHandler();
|
||||
this.init();
|
||||
}
|
||||
|
||||
// Ensure SPA navigates to initial path after document is loaded
|
||||
ensureInitialNavigation() {
|
||||
// Wait for the SPA to initialize, then navigate to the initial path
|
||||
setTimeout(() => {
|
||||
const initialPath = window.__IFRAME_INITIAL_PATH__;
|
||||
|
||||
if (initialPath && initialPath !== '/') {
|
||||
const currentPath = window.location.pathname + window.location.search + window.location.hash;
|
||||
|
||||
// If we're not already at the initial path, navigate there
|
||||
if (currentPath !== initialPath) {
|
||||
this.navigationHandler.handleNavigate(initialPath);
|
||||
}
|
||||
}
|
||||
}, 150); // Give SPA more time to initialize
|
||||
}
|
||||
|
||||
async init() {
|
||||
try {
|
||||
await this.setupServiceWorker();
|
||||
await this.loadSiteIndex();
|
||||
} catch (error) {
|
||||
console.error("FetchClient: Initialization failed:", error);
|
||||
this.showError("Failed to initialize fetch client", error);
|
||||
}
|
||||
}
|
||||
@@ -212,6 +400,20 @@ class FetchClient {
|
||||
}
|
||||
|
||||
async loadSiteIndex() {
|
||||
// Check if we have a stored initial path from a refresh
|
||||
let initialPath = '/';
|
||||
try {
|
||||
const storedPath = sessionStorage.getItem('iframe_initial_path');
|
||||
if (storedPath) {
|
||||
initialPath = storedPath;
|
||||
// Clear the stored path after using it
|
||||
sessionStorage.removeItem('iframe_initial_path');
|
||||
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('loadSiteIndex: Failed to read initial path from sessionStorage:', error);
|
||||
}
|
||||
|
||||
const serializedRequest = {
|
||||
url: `${location.origin}/`,
|
||||
method: "GET",
|
||||
@@ -232,10 +434,33 @@ class FetchClient {
|
||||
const bytes = new Uint8Array(atob(response.body).split('').map(c => c.charCodeAt(0)));
|
||||
const text = new TextDecoder().decode(bytes);
|
||||
|
||||
// Set the initial path on window before replacing the document
|
||||
// This will be available to the NavigationHandler when it initializes
|
||||
if (initialPath && initialPath !== '/') {
|
||||
window.__IFRAME_INITIAL_PATH__ = initialPath;
|
||||
}
|
||||
|
||||
this.replaceDocument(text);
|
||||
}
|
||||
|
||||
replaceDocument(htmlContent) {
|
||||
console.log("replaceDocument: Starting...");
|
||||
|
||||
// Restore the initial path from sessionStorage before replacing document
|
||||
let initialPath = '/';
|
||||
try {
|
||||
const storedPath = sessionStorage.getItem('spa_initial_path');
|
||||
if (storedPath) {
|
||||
initialPath = storedPath;
|
||||
sessionStorage.removeItem('spa_initial_path');
|
||||
console.log('replaceDocument: Restored initial path:', initialPath);
|
||||
// Set it on window for the new document
|
||||
window.__IFRAME_INITIAL_PATH__ = initialPath;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('replaceDocument: Failed to restore initial path:', error);
|
||||
}
|
||||
|
||||
// Create a new document from the HTML content
|
||||
const parser = new DOMParser();
|
||||
const newDoc = parser.parseFromString(htmlContent, "text/html");
|
||||
@@ -266,7 +491,8 @@ class FetchClient {
|
||||
document.body.appendChild(newScript);
|
||||
});
|
||||
|
||||
console.log("Document replaced with site content");
|
||||
// Ensure initial navigation after document is loaded
|
||||
this.ensureInitialNavigation();
|
||||
}
|
||||
|
||||
showError(message, error) {
|
||||
|
||||
+60
-14
@@ -68,23 +68,37 @@ async function requestViaJSONRPC(request) {
|
||||
return new Promise(async (resolve, reject) => {
|
||||
const id = ++requestIdCounter;
|
||||
|
||||
// Serialize the fetch request
|
||||
let body = null;
|
||||
if (request.body) {
|
||||
try {
|
||||
// Convert body to Uint8Array then base64 encode
|
||||
const bytes = await request.bytes();
|
||||
body = btoa(String.fromCharCode(...bytes));
|
||||
} catch (error) {
|
||||
reject(new Error(`Failed to serialize request body: ${error.message}`));
|
||||
return;
|
||||
// Check if request is a plain object or Request object
|
||||
let url, method, headers, body;
|
||||
|
||||
if (request instanceof Request) {
|
||||
// Handle Request object
|
||||
url = request.url;
|
||||
method = request.method;
|
||||
headers = Object.fromEntries(request.headers.entries());
|
||||
|
||||
if (request.body) {
|
||||
try {
|
||||
// Convert body to Uint8Array then base64 encode
|
||||
const bytes = await request.bytes();
|
||||
body = btoa(String.fromCharCode(...bytes));
|
||||
} catch (error) {
|
||||
reject(new Error(`Failed to serialize request body: ${error.message}`));
|
||||
return;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Handle plain request object
|
||||
url = request.url;
|
||||
method = request.method || 'GET';
|
||||
headers = request.headers || {};
|
||||
body = request.body || null;
|
||||
}
|
||||
|
||||
const serializedRequest = {
|
||||
url: request.url,
|
||||
method: request.method,
|
||||
headers: Object.fromEntries(request.headers.entries()),
|
||||
url: url,
|
||||
method: method,
|
||||
headers: headers,
|
||||
body: body,
|
||||
};
|
||||
|
||||
@@ -109,7 +123,7 @@ async function requestViaJSONRPC(request) {
|
||||
setTimeout(() => {
|
||||
if (pendingRequests.has(id)) {
|
||||
pendingRequests.delete(id);
|
||||
reject(new Error(`Timeout requesting: ${request.url}`));
|
||||
reject(new Error(`Timeout requesting: ${url}`));
|
||||
}
|
||||
}, 10000);
|
||||
});
|
||||
@@ -134,6 +148,38 @@ self.addEventListener("fetch", (event) => {
|
||||
return;
|
||||
}
|
||||
|
||||
// Let iframe client assets be handled normally (anything in _iframe-client directory and common assets)
|
||||
if (url.pathname.startsWith("/_iframe-client/") ||
|
||||
url.pathname === "/favicon.ico" ||
|
||||
url.pathname === "/manifest.webmanifest") {
|
||||
return;
|
||||
}
|
||||
|
||||
// For SPA routes, check if this is a navigation request (HTML page request)
|
||||
// But first check if we need to load the iframe client (this happens during refresh)
|
||||
if (event.request.mode === "navigate" &&
|
||||
(event.request.headers.get("accept") || "").includes("text/html")) {
|
||||
|
||||
// Check if this is a request for the iframe client itself
|
||||
// We need to serve the iframe client HTML first, which will then load the SPA
|
||||
if (url.pathname !== "/") {
|
||||
// Redirect to root to load the iframe client, which will then navigate to the target path
|
||||
const response = Response.redirect(new URL("/", event.request.url).href, 302);
|
||||
event.respondWith(response);
|
||||
return;
|
||||
}
|
||||
|
||||
// This is a request for the root path, serve the site's index.html via JSON-RPC
|
||||
const rootRequest = {
|
||||
url: new URL("/", event.request.url).href,
|
||||
method: event.request.method,
|
||||
headers: Object.fromEntries(event.request.headers.entries()),
|
||||
body: event.request.body
|
||||
};
|
||||
event.respondWith(handleRequest(rootRequest));
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle all other requests through JSON-RPC communication
|
||||
event.respondWith(handleRequest(event.request));
|
||||
});
|
||||
|
||||
+3
-3
@@ -2,14 +2,14 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" />
|
||||
<title>Shakespeare - AI-Powered Nostr Development</title>
|
||||
<meta name="description" content="Build custom Nostr websites with AI assistance using Shakespeare, an AI-powered development environment">
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:title" content="Shakespeare - AI-Powered Nostr Development">
|
||||
<meta property="og:description" content="Build custom Nostr websites with AI assistance using Shakespeare, an AI-powered development environment">
|
||||
<!-- <meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: wss:; img-src 'self' data: blob: https:; media-src 'self' https:"> -->
|
||||
<link rel="icon" type="image/png" href="/favicon.png">
|
||||
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: http: wss: ws:; img-src 'self' data: blob: https:; media-src 'self' https:">
|
||||
<link rel="icon" type="image/png" href="/shakespeare.png">
|
||||
<link rel="manifest" href="/manifest.webmanifest">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -1,35 +1,45 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
|
||||
<!-- saved from url=(0053)https://www.gnu.org/licenses/agpl-3.0-standalone.html -->
|
||||
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||
|
||||
<title>GNU Affero General Public License - GNU Project - Free Software Foundation (FSF)</title>
|
||||
<link rel="alternate" type="application/rdf+xml" href="http://www.gnu.org/licenses/agpl-3.0.rdf">
|
||||
</head>
|
||||
<body>
|
||||
<h3 style="text-align: center;">GNU AFFERO GENERAL PUBLIC LICENSE</h3>
|
||||
<p style="text-align: center;">Version 3, 19 November 2007</p>
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
<p>Copyright © 2007 Free Software Foundation,
|
||||
Inc. <<a href="https://fsf.org/">https://fsf.org/</a>>
|
||||
<br>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
of this license document, but changing it is not allowed.</p>
|
||||
|
||||
Preamble
|
||||
<h4 id="preamble">Preamble</h4>
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
<p>The GNU Affero General Public License is a free, copyleft license
|
||||
for software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.</p>
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
<p>The licenses for most software and other practical works are
|
||||
designed to take away your freedom to share and change the works. By
|
||||
contrast, our General Public Licenses are intended to guarantee your
|
||||
freedom to share and change all versions of a program--to make sure it
|
||||
remains free software for all its users.</p>
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
<p>When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
free programs, and that you know you can do these things.</p>
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
<p>Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
and/or modify the software.</p>
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
<p>A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
@@ -37,78 +47,79 @@ encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
source code to the public.</p>
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
<p>The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
code of the modified version.</p>
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
<p>An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
this license.</p>
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
<p>The precise terms and conditions for copying, distribution and
|
||||
modification follow.</p>
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
<h4 id="terms">TERMS AND CONDITIONS</h4>
|
||||
|
||||
0. Definitions.
|
||||
<h4 id="section0">0. Definitions.</h4>
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
<p>"This License" refers to version 3 of the GNU Affero General Public
|
||||
License.</p>
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
<p>"Copyright" also means copyright-like laws that apply to other kinds
|
||||
of works, such as semiconductor masks.</p>
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
<p>"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
"recipients" may be individuals or organizations.</p>
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
<p>To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
earlier work or a work "based on" the earlier work.</p>
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
<p>A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.</p>
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
<p>To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
public, and in some countries other activities as well.</p>
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
<p>To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
a computer network, with no transfer of a copy, is not conveying.</p>
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
<p>An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
menu, a prominent item in the list meets this criterion.</p>
|
||||
|
||||
1. Source Code.
|
||||
<h4 id="section1">1. Source Code.</h4>
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
<p>The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
form of a work.</p>
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
<p>A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
is widely used among developers working in that language.</p>
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
<p>The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
@@ -117,9 +128,9 @@ implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
produce the work, or an object code interpreter used to run it.</p>
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
<p>The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
@@ -130,26 +141,26 @@ includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
subprograms and other parts of the work.</p>
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
<p>The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
Source.</p>
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
<p>The Corresponding Source for a work in source code form is that
|
||||
same work.</p>
|
||||
|
||||
2. Basic Permissions.
|
||||
<h4 id="section2">2. Basic Permissions.</h4>
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
<p>All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
rights of fair use or other equivalent, as provided by copyright law.</p>
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
<p>You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
@@ -158,69 +169,73 @@ the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
your copyrighted material outside their relationship with you.</p>
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
<p>Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
makes it unnecessary.</p>
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
<h4 id="section3">3. Protecting Users' Legal Rights From Anti-Circumvention Law.</h4>
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
<p>No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
measures.</p>
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
<p>When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
technological measures.</p>
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
<h4 id="section4">4. Conveying Verbatim Copies.</h4>
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
<p>You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
recipients a copy of this License along with the Program.</p>
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
<p>You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.</p>
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
<h4 id="section5">5. Conveying Modified Source Versions.</h4>
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
<p>You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
terms of section 4, provided that you also meet all of these conditions:</p>
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
<ul>
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
<li>a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.</li>
|
||||
|
||||
<li>b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
"keep intact all notices".</li>
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
<li>c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
invalidate such permission if you have separately received it.</li>
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
<li>d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
work need not make them do so.</li>
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
</ul>
|
||||
|
||||
<p>A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
@@ -228,21 +243,23 @@ in or on a volume of a storage or distribution medium, is called an
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
parts of the aggregate.</p>
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
<h4 id="section6">6. Conveying Non-Source Forms.</h4>
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
<p>You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
in one of these ways:</p>
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
<ul>
|
||||
|
||||
<li>a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
customarily used for software interchange.</li>
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
<li>b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
@@ -252,15 +269,15 @@ in one of these ways:
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
Corresponding Source from a network server at no charge.</li>
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
<li>c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
with subsection 6b.</li>
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
<li>d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
@@ -271,18 +288,20 @@ in one of these ways:
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
available for as long as needed to satisfy these requirements.</li>
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
<li>e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
charge under subsection 6d.</li>
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
</ul>
|
||||
|
||||
<p>A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
included in conveying the object code work.</p>
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
<p>A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
@@ -293,17 +312,17 @@ of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
the only significant mode of use of the product.</p>
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
<p>"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
modification has been made.</p>
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
<p>If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
@@ -312,133 +331,137 @@ Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
been installed in ROM).</p>
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
<p>The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
protocols for communication across the network.</p>
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
<p>Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
unpacking, reading or copying.</p>
|
||||
|
||||
7. Additional Terms.
|
||||
<h4 id="section7">7. Additional Terms.</h4>
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
<p>"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
this License without regard to the additional permissions.</p>
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
<p>When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
for which you have or can give appropriate copyright permission.</p>
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
<p>Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
that material) supplement the terms of this License with terms:</p>
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
<ul>
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
<li>a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or</li>
|
||||
|
||||
<li>b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
Notices displayed by works containing it; or</li>
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
<li>c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
reasonable ways as different from the original version; or</li>
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
<li>d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or</li>
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
<li>e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or</li>
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
<li>f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
those licensors and authors.</li>
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
</ul>
|
||||
|
||||
<p>All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
governed by this License along with a term that is a further restriction,
|
||||
you may remove that term. If a license document contains a further
|
||||
restriction but permits relicensing or conveying under this License, you
|
||||
may add to a covered work material governed by the terms of that license
|
||||
document, provided that the further restriction does not survive such
|
||||
relicensing or conveying.</p>
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
<p>If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
where to find the applicable terms.</p>
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
<p>Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
the above requirements apply either way.</p>
|
||||
|
||||
8. Termination.
|
||||
<h4 id="section8">8. Termination.</h4>
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
<p>You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
paragraph of section 11).</p>
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
<p>However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
prior to 60 days after the cessation.</p>
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
<p>Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
your receipt of the notice.</p>
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
<p>Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
material under section 10.</p>
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
<h4 id="section9">9. Acceptance Not Required for Having Copies.</h4>
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
<p>You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
covered work, you indicate your acceptance of this License to do so.</p>
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
<h4 id="section10">10. Automatic Licensing of Downstream Recipients.</h4>
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
<p>Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
for enforcing compliance by third parties with this License.</p>
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
<p>An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
@@ -446,23 +469,23 @@ transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
the predecessor has it or can get it with reasonable efforts.</p>
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
<p>You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
sale, or importing the Program or any portion of it.</p>
|
||||
|
||||
11. Patents.
|
||||
<h4 id="section11">11. Patents.</h4>
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
<p>A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
work thus licensed is called the contributor's "contributor version".</p>
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
<p>A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
@@ -470,21 +493,21 @@ but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
this License.</p>
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
<p>Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
propagate the contents of its contributor version.</p>
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
<p>In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
patent against the party.</p>
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
<p>If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
@@ -496,17 +519,17 @@ license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
country that you have reason to believe are valid.</p>
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
<p>If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
work and works based on it.</p>
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
<p>A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
@@ -519,15 +542,15 @@ patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
or that patent license was granted, prior to 28 March 2007.</p>
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
<p>Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
otherwise be available to you under applicable patent law.</p>
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
<h4 id="section12">12. No Surrender of Others' Freedom.</h4>
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
<p>If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
@@ -535,11 +558,11 @@ License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
License would be to refrain entirely from conveying the Program.</p>
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
<h4 id="section13">13. Remote Network Interaction; Use with the GNU General Public License.</h4>
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
<p>Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
@@ -548,56 +571,56 @@ from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
following paragraph.</p>
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
<p>Notwithstanding any other provision of this License, you have permission
|
||||
to link or combine any covered work with a work licensed under version 3
|
||||
of the GNU General Public License into a single combined work, and to
|
||||
convey the resulting work. The terms of this License will continue to
|
||||
apply to the part which is the covered work, but the work with which it is
|
||||
combined will remain governed by version 3 of the GNU General Public
|
||||
License.</p>
|
||||
|
||||
14. Revised Versions of this License.
|
||||
<h4 id="section14">14. Revised Versions of this License.</h4>
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
<p>The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new
|
||||
versions will be similar in spirit to the present version, but may differ
|
||||
in detail to address new problems or concerns.</p>
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
<p>Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero
|
||||
General Public License "or any later version" applies to it, you have
|
||||
the option of following the terms and conditions either of that
|
||||
numbered version or of any later version published by the Free
|
||||
Software Foundation. If the Program does not specify a version number
|
||||
of the GNU Affero General Public License, you may choose any version
|
||||
ever published by the Free Software Foundation.</p>
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
<p>If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that
|
||||
proxy's public statement of acceptance of a version permanently
|
||||
authorizes you to choose that version for the Program.</p>
|
||||
|
||||
Later license versions may give you additional or different
|
||||
<p>Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
later version.</p>
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
<h4 id="section15">15. Disclaimer of Warranty.</h4>
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
<p>THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.</p>
|
||||
|
||||
16. Limitation of Liability.
|
||||
<h4 id="section16">16. Limitation of Liability.</h4>
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
<p>IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
@@ -605,37 +628,37 @@ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
SUCH DAMAGES.</p>
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
<h4 id="section17">17. Interpretation of Sections 15 and 16.</h4>
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
<p>If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
copy of the Program in return for a fee.</p>
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
<p>END OF TERMS AND CONDITIONS</p>
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
<h4 id="howto">How to Apply These Terms to Your New Programs</h4>
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
<p>If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
free software which everyone can redistribute and change under these terms.</p>
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
<p>To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
the "copyright" line and a pointer to where the full notice is found.</p>
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
<pre> <one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
@@ -643,19 +666,23 @@ the "copyright" line and a pointer to where the full notice is found.
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
</pre>
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
<p>Also add information on how to contact you by electronic and paper mail.</p>
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
<p>If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
specific requirements.</p>
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
<p>You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
<<a href="https://www.gnu.org/licenses/">https://www.gnu.org/licenses/</a>>.</p>
|
||||
|
||||
|
||||
</body></html>
|
||||
@@ -8,12 +8,12 @@
|
||||
"theme_color": "#000000",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/favicon.png",
|
||||
"src": "/shakespeare.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png"
|
||||
},
|
||||
{
|
||||
"src": "/favicon.png",
|
||||
"src": "/shakespeare.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png"
|
||||
}
|
||||
|
||||
File renamed without changes.
|
Before Width: | Height: | Size: 18 KiB After Width: | Height: | Size: 18 KiB |
@@ -0,0 +1,63 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generator: Adobe Illustrator 25.2.3, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
|
||||
<svg version="1.1" id="レイヤー_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px"
|
||||
y="0px" viewBox="0 0 128 128" style="enable-background:new 0 0 128 128;" xml:space="preserve">
|
||||
<g>
|
||||
<g>
|
||||
<path style="fill:#F45125;" d="M110.28,61.32l2.63,8.84c0,0,7.24-1.6,7.62,3.2c0.38,4.8-6.77,8-6.77,8l2.26,10.63
|
||||
c0,0,7.9-6.4,8-15.61c0,0,0.66-11.29-6.11-13.92C113.67,60.85,110.28,61.32,110.28,61.32z"/>
|
||||
<path style="fill:#F45125;" d="M68.71,94.99c0,0-11.1-4.7-16.46,1.98c-0.75,0.94-1.41,1.88-2.16,2.82
|
||||
c-0.56,0.75-1.13,1.5-1.69,2.16c-0.47,0.56-1.03,1.13-1.69,1.5c-0.66,0.38-1.32,0.66-2.07,0.85c-0.94,0.19-1.88,0.19-2.82,0.09
|
||||
c-1.32-0.09-2.63-0.38-3.95-0.66c-0.47-0.09-0.85-0.19-1.22-0.28c-0.09,0-0.19-0.09-0.28-0.09s-0.19-0.09-0.28-0.09
|
||||
c-0.38,0.09,0.19,0.75,0.38,0.94c0.28,0.28,0.56,0.66,0.85,0.94c0.85,0.75,1.69,1.5,2.73,1.98c1.32,0.66,2.73,1.03,4.14,1.13
|
||||
c0.09,0,0.38,0,0.47,0.09c0.19,0.19-0.28,0.47-0.47,0.56c-0.28,0.19-0.47,0.28-0.75,0.38c-0.85,0.38-1.79,0.56-2.63,0.75
|
||||
c-0.85,0.19-1.69,0.28-2.45,0.28c-0.47,0-0.85,0.09-1.22,0.09c-0.28,0-0.56-0.09-0.85,0s0.09,0.47,0.28,0.56
|
||||
c0.38,0.19,0.75,0.47,1.13,0.66c1.13,0.56,2.26,1.03,3.39,1.32c1.5,0.38,3.1,0.56,4.61,0.38c1.32-0.19,2.63-0.56,3.86-1.03
|
||||
c6.77-3.1,6.21-9.59,12.42-10.16c4.61-0.38,11.1,2.07,11.1,2.07L68.71,94.99z"/>
|
||||
<path style="fill:#F45125;" d="M19.79,38.28c0,0-12.13,1.98-15.24,12.79C0.61,64.9,20.26,69.5,20.26,69.5l1.22-9.41
|
||||
c0,0-13.07-1.32-12.32-6.3c0.94-6.21,11.85-5.64,11.85-5.64L19.79,38.28z"/>
|
||||
<path style="fill:#F45125;" d="M20.73,70.92c0,0-1.88,0.56-4.61,2.54c-1.88,1.32-4.42,3.01-6.87,5.93
|
||||
c-1.22,1.41-2.16,3.1-2.82,4.89c-0.47,1.22-0.66,2.45-0.66,3.76c0,0.28,0,0.56,0,0.85c0,0.09,0,0.85,0.28,0.66
|
||||
c0.09-0.09,0.19-0.38,0.28-0.47c0.19-0.47,0.47-0.85,0.75-1.22c0.85-1.13,1.88-2.16,3.01-3.01c0.38-0.28,0.75-0.47,1.13-0.66
|
||||
c0.28-0.28,0.75-0.66,0.94-0.28c0.09,0.19-0.09,0.47-0.19,0.66c-0.09,0.28-0.19,0.66-0.19,0.94c-0.38,1.5-0.56,3.01-0.75,4.51
|
||||
c-0.09,0.85-0.09,1.69,0,2.45c0,0.38,0.09,0.85,0.09,1.22c0,0.19,0.09,0.38,0.09,0.56c0,0.19,0.19,0.47,0.38,0.19
|
||||
c0.09-0.09,0.09-0.19,0.19-0.38c0.19-0.28,0.28-0.66,0.47-0.94c0.47-0.85,0.94-1.69,1.5-2.63c0.66-1.13,1.41-2.16,2.16-3.1
|
||||
c0.85-1.13,1.88-2.26,2.92-3.2c1.13-1.03,2.35-2.07,3.67-2.92c0.75-0.47,1.6-0.94,2.45-1.32L20.73,70.92z"/>
|
||||
<g>
|
||||
<path style="fill:#FCC21B;" d="M116.4,79.29c-1.13-5.55-2.73-11.01-4.51-16.46c-1.5-4.61-3.1-9.31-5.83-13.36
|
||||
c-1.22-1.79-3.01-3.01-5.27-3.86c-4.33-1.69-9.97-1.98-13.73-1.98c-5.64,0-11.48,1.22-16.74,3.67
|
||||
c-1.88,5.64-7.05,19.94-14.86,26.34c0.47,2.63,1.03,5.36,1.79,8c1.32,4.61,3.01,9.22,4.61,13.83c1.5,4.42,3.29,8.84,6.58,12.23
|
||||
c0.85,0.94,1.88,1.69,2.82,2.45c2.26,1.88,4.99,3.01,7.71,3.95c2.54,0.85,5.17,1.5,7.81,2.07c4.7,1.03,11.48,2.82,16.08,0.66
|
||||
c2.54-1.13,4.61-2.92,6.3-5.08c1.79-2.26,3.2-4.8,4.42-7.43c1.88-3.95,3.86-8.37,4.14-12.89
|
||||
C117.99,87.38,117.24,83.24,116.4,79.29z"/>
|
||||
<path style="fill:#429ADF;" d="M77.64,33.57c-0.28-1.03-1.03-2.07-1.6-3.01c-6.3-11.01-20.04-16.27-32.26-15.52
|
||||
c-3.76,0.28-9.31,0.85-13.54,2.73c-2.07,0.94-3.86,2.35-4.99,4.14c-2.54,4.23-3.76,8.94-5.08,13.64
|
||||
C18.67,41,17.35,46.55,16.5,52.2c-0.75,4.89-1.41,10.25-0.09,15.14c1.03,3.86,3.29,9.22,5.74,12.32
|
||||
c2.73,3.39,6.58,7.34,10.72,8.84c0.75,0.28,1.6,0.47,2.45,0.66c1.6,0.28,3.29,0.47,4.89,0.19c0.94-0.19,1.98-0.28,2.92-0.56
|
||||
c1.88-0.47,3.67-1.13,5.46-1.79c7.52-3.01,13.64-7.43,17.68-14.58c1.69-3.1,3.1-6.4,4.42-9.69c0.09-0.19,0.19-0.38,0.19-0.56
|
||||
c1.98-5.46,3.29-11.19,4.61-16.84c0.66-2.73,1.41-5.55,1.79-8.37C77.55,35.92,77.92,34.7,77.64,33.57z"/>
|
||||
</g>
|
||||
</g>
|
||||
<path style="fill:#193D51;" d="M23.09,40.53c1.69-3.1,5.74-5.55,9.31-5.08c0.56,0.09,1.22,0.19,1.79,0.47
|
||||
c3.57,1.5,5.74,4.99,4.89,8.56c-0.19,0.75-0.66,0.85-1.22,0.38c-1.98-1.69-3.57-3.01-6.21-3.67c-2.16-0.56-4.61-0.28-6.68,0.28
|
||||
c-0.47,0.09-1.22,0.56-1.69,0.38C22.61,41.57,22.9,40.91,23.09,40.53z"/>
|
||||
<path style="fill:#193D51;" d="M62.21,64.9c-1.03,1.6-2.45,3.01-3.86,4.33c-0.38,0.28-0.66,0.66-1.03,0.94
|
||||
c-5.64,4.7-13.26,7.05-20.51,5.27c-1.98-0.47-4.14-1.5-5.74-2.73c-1.22-0.94-2.45-2.16-3.48-3.39c-1.88-2.26-3.29-4.89-4.23-7.62
|
||||
c-0.47-1.41-0.75-2.73-0.94-4.23c0-0.47-0.66-5.46,0.85-4.8c0.38,0.19,0.66,0.47,0.94,0.75c0.28,0.38,0.47,0.75,0.75,1.03
|
||||
c0.66,0.85,1.32,1.69,2.07,2.45c2.35,2.73,5.27,4.89,8.56,6.4c2.26,1.03,4.7,1.6,7.15,1.79c1.41,0.09,2.73,0.19,4.14,0.09
|
||||
c5.08-0.28,10.25-1.79,14.86-3.76c0.38-0.19,0.85-0.47,1.32-0.47C64.66,61.04,62.5,64.52,62.21,64.9z"/>
|
||||
<path style="fill:#193D51;" d="M67.58,51.16c0,0.47-0.19,1.13-0.75,1.03c-0.47-0.09-0.85-0.94-1.13-1.22
|
||||
c-1.32-1.69-3.86-3.57-6.4-4.14c-3.01-0.75-5.27,0.56-8.28,0.85c-0.85,0.09-1.32-0.28-0.94-1.03c1.6-3.48,5.83-6.21,10.25-5.46
|
||||
c0.75,0.09,1.41,0.28,2.07,0.56C66.26,43.36,67.86,47.59,67.58,51.16z"/>
|
||||
<path style="fill:#9B7515;" d="M91.84,63.86c4.23,2.73,9.69,3.48,14.58,3.2c1.41-0.09,2.26,0.09,1.88,1.69
|
||||
c-0.75,3.29-3.86,5.17-6.87,5.83c-0.75,0.19-1.5,0.19-2.26,0.19c-1.41-0.09-2.82-0.66-4.04-1.5c-2.63-1.79-4.61-4.89-5.17-8
|
||||
C89.68,63.67,90.25,62.83,91.84,63.86z"/>
|
||||
<path style="fill:#9B7515;" d="M65.22,80.79C64,79.57,64.66,79,65.98,78.25c4.51-2.35,9.03-5.93,11.38-10.63
|
||||
c0.85-1.79,1.79-1.41,2.45,0.28c1.13,3.1,1.03,6.87-0.38,9.88c-0.66,1.41-1.6,2.63-2.82,3.57c-0.66,0.47-1.32,0.75-2.07,1.03
|
||||
C71.43,83.33,67.58,83.24,65.22,80.79z"/>
|
||||
<path style="fill:#9B7515;" d="M110,96.41c-0.38,0-0.94-0.38-1.41-0.66c-0.47-0.28-0.94-0.66-1.22-0.85
|
||||
c-1.13-0.56-2.45-1.13-3.67-1.5c-3.76-1.22-7.9-1.22-11.57,0c-2.63,0.85-5.17,2.45-7.24,4.33c-2.26,2.16-3.95,4.8-6.11,7.05
|
||||
c-0.28,0.28-0.56,0.56-0.85,0.75c-0.56,0.28-1.13-0.09-1.32-0.66c-0.94-3.95,1.69-9.5,3.67-12.89c2.26-3.76,5.55-6.77,9.78-8
|
||||
c2.07-0.66,4.33-0.66,6.49-0.38c6.3,0.94,12.79,5.93,14.02,11.66C110.56,95.75,110.47,96.5,110,96.41z"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 5.8 KiB |
+1
-1
@@ -38,7 +38,7 @@ const queryClient = new QueryClient({
|
||||
});
|
||||
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "light",
|
||||
theme: "system",
|
||||
relayUrl: "wss://relay.primal.net",
|
||||
deployServer: "shakespeare.wtf",
|
||||
};
|
||||
|
||||
+1
-2
@@ -11,7 +11,7 @@ import AISettings from "./pages/AISettings";
|
||||
import GitSettings from "./pages/GitSettings";
|
||||
import DataSettings from "./pages/DataSettings";
|
||||
import AboutSettings from "./pages/AboutSettings";
|
||||
import EmailSettings from "./pages/EmailSettings";
|
||||
|
||||
import GitHubOAuth from "./pages/GitHubOAuth";
|
||||
import { NIP19Page } from "./pages/NIP19Page";
|
||||
import NotFound from "./pages/NotFound";
|
||||
@@ -34,7 +34,6 @@ export function AppRouter() {
|
||||
<Route path="ai" element={<AISettings />} />
|
||||
<Route path="git" element={<GitSettings />} />
|
||||
<Route path="data" element={<DataSettings />} />
|
||||
<Route path="email" element={<EmailSettings />} />
|
||||
<Route path="about" element={<AboutSettings />} />
|
||||
</Route>
|
||||
<Route path="/project/:projectId" element={<ProjectView />} />
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { memo, useState } from 'react';
|
||||
import { Streamdown } from 'streamdown';
|
||||
import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus, Terminal, Globe, CheckCircle, Lightbulb, Loader2 } from 'lucide-react';
|
||||
import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus, Terminal, Globe, CheckCircle, Lightbulb, Loader2, Logs } from 'lucide-react';
|
||||
import type { AIMessage } from '@/lib/SessionManager';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { UserMessage } from '@/components/UserMessage';
|
||||
@@ -150,6 +150,11 @@ export const AIMessageItem = memo(({
|
||||
icon: CheckCircle,
|
||||
title: 'TypeScript'
|
||||
};
|
||||
case 'read_console_messages':
|
||||
return {
|
||||
icon: Logs,
|
||||
title: 'Read Console'
|
||||
};
|
||||
default:
|
||||
return {
|
||||
icon: Wrench,
|
||||
|
||||
@@ -57,6 +57,7 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
// If providers are being updated, invalidate the provider-models query
|
||||
if ('providers' in newSettings) {
|
||||
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -80,6 +81,7 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
}
|
||||
});
|
||||
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
|
||||
};
|
||||
|
||||
const removeProvider = (id: string) => {
|
||||
@@ -88,6 +90,7 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
providers: prev.providers.filter(provider => provider.id !== id),
|
||||
}));
|
||||
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
|
||||
};
|
||||
|
||||
const setProviders = (providers: AIProvider[]) => {
|
||||
@@ -96,6 +99,7 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
providers,
|
||||
}));
|
||||
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
|
||||
};
|
||||
|
||||
const addRecentlyUsedModel = (modelId: string) => {
|
||||
|
||||
@@ -0,0 +1,350 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { ArrowRight, ArrowLeft, Download, Upload, ExternalLink, Sparkles } from 'lucide-react';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
|
||||
// import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useAICredits } from '@/hooks/useAICredits';
|
||||
// import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
|
||||
interface Act1DialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
type DialogStep = 'welcome' | 'migration' | 'credits' | 'conclusion';
|
||||
|
||||
const SHAKESPEARE_PROVIDER = {
|
||||
id: "shakespeare",
|
||||
baseURL: "https://ai.shakespeare.diy/v1",
|
||||
nostr: true,
|
||||
};
|
||||
|
||||
// const MKSTACK_NSP_ADDR = '31999:4bcaa7b5606e3c14df05cd497e588f5d3fe559b4e9a425e8b418a43af1ffb015:mkstack';
|
||||
|
||||
export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) {
|
||||
const [step, setStep] = useState<DialogStep>('welcome');
|
||||
// const { setProvider, updateSettings } = useAISettings();
|
||||
|
||||
// // Get the selectedNSPAddr from localStorage
|
||||
// const [selectedNSPAddr] = useLocalStorage<string | null>('selectedNSPAddr', null);
|
||||
|
||||
// Get user's credits
|
||||
const { data: creditsData } = useAICredits(SHAKESPEARE_PROVIDER);
|
||||
|
||||
const handleGetStarted = async () => {
|
||||
try {
|
||||
// // Add Shakespeare provider to their config
|
||||
// setProvider(SHAKESPEARE_PROVIDER);
|
||||
|
||||
// // Configure recently used models based on credits or NSP
|
||||
// const hasCredits = creditsData?.amount && creditsData.amount > 0;
|
||||
// const hasMKStackNSP = selectedNSPAddr === MKSTACK_NSP_ADDR;
|
||||
|
||||
// if (hasCredits || hasMKStackNSP) {
|
||||
// // User has credits or MKStack NSP - set to shakespeare model
|
||||
// updateSettings({ recentlyUsedModels: ['shakespeare/shakespeare'] });
|
||||
// } else {
|
||||
// // No credits - set to tybalt model (free)
|
||||
// updateSettings({ recentlyUsedModels: ['shakespeare/tybalt'] });
|
||||
// }
|
||||
|
||||
// Move to migration step
|
||||
setStep('migration');
|
||||
} catch (error) {
|
||||
console.error('Failed to configure Shakespeare provider:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleContinue = () => {
|
||||
setStep('credits');
|
||||
};
|
||||
|
||||
const handleCreditsNext = () => {
|
||||
setStep('conclusion');
|
||||
};
|
||||
|
||||
const handleFinish = () => {
|
||||
// Mark that the user is a previous Act 1 user
|
||||
localStorage.setItem('act1', 'true');
|
||||
// Remove the selectedNSPAddr from localStorage
|
||||
localStorage.removeItem('selectedNSPAddr');
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
const handleVisitAct1 = () => {
|
||||
window.open('https://act1.shakespeare.diy', '_blank');
|
||||
};
|
||||
|
||||
// Reset state when dialog opens/closes
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setStep('welcome');
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] overflow-hidden">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
{step === 'migration' && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setStep('welcome')}
|
||||
className="mr-2 p-1 h-auto"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
{step === 'credits' && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setStep('migration')}
|
||||
className="mr-2 p-1 h-auto"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
{step === 'conclusion' && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setStep('credits')}
|
||||
className="mr-2 p-1 h-auto"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="overflow-y-auto max-h-[calc(90vh-120px)] pr-2">
|
||||
<div className="space-y-6 py-4">
|
||||
{step === 'welcome' && (
|
||||
<div className="text-center space-y-6">
|
||||
<div className="text-6xl mb-4">🎭✨</div>
|
||||
<div className="space-y-3">
|
||||
<h2 className="text-2xl font-bold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||
Welcome to Act 2!
|
||||
</h2>
|
||||
<p className="text-lg text-muted-foreground max-w-lg mx-auto">
|
||||
We're excited to see you again! Shakespeare has been completely rebuilt
|
||||
with new features, improved performance, and a better development experience.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Card className="max-w-lg mx-auto text-left">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<span className="text-2xl">🔄</span>
|
||||
What's Changed
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="flex items-start gap-3">
|
||||
<Badge variant="secondary" className="mt-0.5">New</Badge>
|
||||
<div>
|
||||
<p className="font-medium">Use any AI Provider</p>
|
||||
<p className="text-sm text-muted-foreground">Your browser connects to AI providers directly</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<Badge variant="secondary" className="mt-0.5">New</Badge>
|
||||
<div>
|
||||
<p className="font-medium">Git Integration</p>
|
||||
<p className="text-sm text-muted-foreground">Push to GitHub, Nostr relays, and more</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<Badge variant="secondary" className="mt-0.5">New</Badge>
|
||||
<div>
|
||||
<p className="font-medium">Your Files</p>
|
||||
<p className="text-sm text-muted-foreground">Files are stored on your device directly in your browser</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="bg-amber-50 dark:bg-amber-950/20 border border-amber-200 dark:border-amber-800 rounded-lg p-4 max-w-lg mx-auto">
|
||||
<div className="flex items-start gap-3">
|
||||
<span className="text-amber-600 dark:text-amber-400 text-lg">⚠️</span>
|
||||
<div className="text-left">
|
||||
<p className="font-medium text-amber-800 dark:text-amber-200">Act 2 is in Development</p>
|
||||
<p className="text-sm text-amber-700 dark:text-amber-300">
|
||||
While we're working hard to make Act 2 stable, you may encounter bugs.
|
||||
Your Act 1 projects remain safe and accessible.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handleGetStarted}
|
||||
size="lg"
|
||||
className="gap-2"
|
||||
>
|
||||
Next
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'migration' && (
|
||||
<div className="space-y-6">
|
||||
<div className="text-center space-y-3">
|
||||
<h2 className="text-xl font-bold">Your Act 1 Projects & Credits</h2>
|
||||
<p className="text-muted-foreground max-w-lg mx-auto">
|
||||
All your Act 1 projects and credits are safe and still accessible.
|
||||
Here's how to work with them in Act 2.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="text-center">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleVisitAct1}
|
||||
className="gap-2"
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
Visit Act 1
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<Download className="h-5 w-5 text-green-500" />
|
||||
Export from Act 1
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
In Act 1, you can export your projects as ZIP files using the project menu.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<Upload className="h-5 w-5 text-purple-500" />
|
||||
Import to Act 2
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
In Act 2, use the "Import Project" option in the sidebar to upload your exported ZIP files.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end pt-4">
|
||||
<Button
|
||||
onClick={handleContinue}
|
||||
className="gap-2"
|
||||
>
|
||||
Continue
|
||||
<ArrowRight className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'credits' && (
|
||||
<div className="text-center space-y-6">
|
||||
<div className="text-6xl mb-4">💳</div>
|
||||
<div className="space-y-3">
|
||||
<h2 className="text-2xl font-bold">Your Credits</h2>
|
||||
<p className="text-lg text-muted-foreground max-w-md mx-auto">
|
||||
Your Act 1 credits are still available through the Shakespeare AI provider.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Card className="max-w-md mx-auto">
|
||||
<CardContent className="pt-6">
|
||||
{creditsData?.amount && creditsData.amount > 0 ? (
|
||||
<div className="text-center space-y-4">
|
||||
<div className="space-y-2">
|
||||
<div className="text-3xl font-bold text-green-600 dark:text-green-400">
|
||||
${creditsData.amount.toFixed(2)}
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Available credits
|
||||
</p>
|
||||
</div>
|
||||
<div className="bg-green-50 dark:bg-green-950/20 border border-green-200 dark:border-green-800 rounded-lg p-3">
|
||||
<p className="text-sm text-green-800 dark:text-green-200">
|
||||
✅ You're all set! We've configured the premium Shakespeare model for you.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-center space-y-4">
|
||||
<div className="space-y-2">
|
||||
<div className="text-2xl">🆓</div>
|
||||
<p className="font-medium">Free Access</p>
|
||||
</div>
|
||||
<div className="bg-blue-50 dark:bg-blue-950/20 border border-blue-200 dark:border-blue-800 rounded-lg p-3">
|
||||
<p className="text-sm text-blue-800 dark:text-blue-200">
|
||||
You can continue using Shakespeare for free with the Tybalt model.
|
||||
It's perfect for learning and building amazing projects!
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="flex justify-end pt-4">
|
||||
<Button
|
||||
onClick={handleCreditsNext}
|
||||
className="gap-2"
|
||||
>
|
||||
Continue
|
||||
<ArrowRight className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'conclusion' && (
|
||||
<div className="text-center space-y-6">
|
||||
<div className="text-5xl mb-4">🎉</div>
|
||||
<div className="space-y-3">
|
||||
<h2 className="text-2xl font-bold">Welcome to the Future!</h2>
|
||||
<p className="text-lg text-muted-foreground max-w-md mx-auto">
|
||||
You're all up to speed with Act 2! Get ready to build amazing Nostr applications.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<Button onClick={handleFinish} size="lg" className="gap-2">
|
||||
<Sparkles className="h-4 w-4" />
|
||||
Start Building in Act 2
|
||||
</Button>
|
||||
|
||||
<div className="text-xs text-muted-foreground">
|
||||
Remember: You can always access Act 1 at{' '}
|
||||
<button
|
||||
onClick={handleVisitAct1}
|
||||
className="text-primary hover:underline"
|
||||
>
|
||||
act1.shakespeare.diy
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -18,7 +18,6 @@ interface AppLayoutProps {
|
||||
export function AppLayout({
|
||||
children,
|
||||
selectedProject = null,
|
||||
title = "Shakespeare",
|
||||
showSidebar = true,
|
||||
headerContent
|
||||
}: AppLayoutProps) {
|
||||
@@ -85,9 +84,6 @@ export function AppLayout({
|
||||
<Menu className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
<h1 className="text-lg font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||
{title}
|
||||
</h1>
|
||||
</div>
|
||||
{headerContent}
|
||||
</header>
|
||||
|
||||
@@ -399,7 +399,7 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-lg w-full max-h-[75vh] overflow-hidden flex flex-col sm:max-w-lg sm:max-h-[75vh] max-sm:w-full max-sm:h-full max-sm:max-w-none max-sm:max-h-none max-sm:m-0 max-sm:rounded-none">
|
||||
<DialogContent onOpenAutoFocus={(e) => e.preventDefault()} className="max-w-lg w-full max-h-[75vh] overflow-hidden flex flex-col sm:max-w-lg sm:max-h-[75vh] max-sm:w-full max-sm:h-full max-sm:max-w-none max-sm:max-h-none max-sm:m-0 max-sm:rounded-none">
|
||||
<DialogHeader className="flex-shrink-0">
|
||||
<DialogTitle className="flex items-center gap-2 text-lg">
|
||||
{lightningInvoice ? (
|
||||
@@ -509,17 +509,13 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
|
||||
</div>
|
||||
<div className="flex-1 min-h-0 overflow-y-auto">
|
||||
{isLoadingPayments ? (
|
||||
<div className="space-y-3">
|
||||
{Array.from({ length: 3 }).map((_, i) => (
|
||||
<div key={i} className="p-3 border rounded-lg space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="h-4 w-4 rounded" />
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-4 w-16 ml-auto" />
|
||||
</div>
|
||||
<Skeleton className="h-3 w-32" />
|
||||
</div>
|
||||
))}
|
||||
<div className="p-3 border rounded-lg space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Skeleton className="h-4 w-4 rounded" />
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-4 w-16 ml-auto" />
|
||||
</div>
|
||||
<Skeleton className="h-3 w-32" />
|
||||
</div>
|
||||
) : !payments || payments.length === 0 ? (
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Mail, CheckCircle } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
export function EmailSubscription() {
|
||||
const { t } = useTranslation();
|
||||
const { user } = useCurrentUser();
|
||||
const { toast } = useToast();
|
||||
|
||||
const [email, setEmail] = useState('');
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [isSubmitted, setIsSubmitted] = useState(false);
|
||||
|
||||
const url = new URL('https://pub.us7.list-manage.com/subscribe/post?u=f1f718a93795f42a604d558d8&id=f7271442a0&f_id=00ffa3e4f0');
|
||||
const honeypot = `b_${url.searchParams.get('u')}_${url.searchParams.get('id')}`;
|
||||
const tag = '8982396';
|
||||
|
||||
// Check localStorage on component mount
|
||||
useEffect(() => {
|
||||
const hasSubscribed = localStorage.getItem('shakespeare-email-subscribed');
|
||||
if (hasSubscribed === 'true') {
|
||||
setIsSubmitted(true);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!email.trim()) {
|
||||
toast({
|
||||
title: "Email required",
|
||||
description: "Please enter your email address",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Basic email validation
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(email)) {
|
||||
toast({
|
||||
title: "Invalid email",
|
||||
description: "Please enter a valid email address",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSubmitting(true);
|
||||
|
||||
try {
|
||||
// Submit to Mailchimp
|
||||
const form = document.createElement('form');
|
||||
form.method = 'POST';
|
||||
form.action = url.href;
|
||||
form.target = '_blank'; // Open in new tab
|
||||
form.style.display = 'none';
|
||||
|
||||
// Add email field
|
||||
const emailInput = document.createElement('input');
|
||||
emailInput.type = 'email';
|
||||
emailInput.name = 'EMAIL';
|
||||
emailInput.value = email.trim();
|
||||
form.appendChild(emailInput);
|
||||
|
||||
// Add tag field with the new Shakespeare tag ID
|
||||
const tagInput = document.createElement('input');
|
||||
tagInput.type = 'hidden';
|
||||
tagInput.name = 'tags';
|
||||
tagInput.value = tag;
|
||||
form.appendChild(tagInput);
|
||||
|
||||
// Add npub if available
|
||||
if (user?.pubkey) {
|
||||
const npubInput = document.createElement('input');
|
||||
npubInput.type = 'text';
|
||||
npubInput.name = 'NPUB';
|
||||
npubInput.value = nip19.npubEncode(user.pubkey);
|
||||
npubInput.style.display = 'none';
|
||||
form.appendChild(npubInput);
|
||||
}
|
||||
|
||||
// Add honeypot field
|
||||
const honeypotInput = document.createElement('input');
|
||||
honeypotInput.type = 'text';
|
||||
honeypotInput.name = honeypot;
|
||||
honeypotInput.tabIndex = -1;
|
||||
honeypotInput.style.position = 'absolute';
|
||||
honeypotInput.style.left = '-5000px';
|
||||
form.appendChild(honeypotInput);
|
||||
|
||||
// Add form to document and submit
|
||||
document.body.appendChild(form);
|
||||
form.submit();
|
||||
|
||||
// Clean up after a short delay
|
||||
setTimeout(() => {
|
||||
document.body.removeChild(form);
|
||||
}, 1000);
|
||||
|
||||
// Save subscription status to localStorage
|
||||
localStorage.setItem('shakespeare-email-subscribed', 'true');
|
||||
|
||||
setIsSubmitted(true);
|
||||
toast({
|
||||
title: "Successfully subscribed!",
|
||||
description: "You'll receive Shakespeare updates and resources occasionally.",
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Email signup error:', error);
|
||||
toast({
|
||||
title: "Subscription failed",
|
||||
description: "There was an error subscribing you to updates. Please try again.",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (isSubmitted) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="text-center space-y-4">
|
||||
<CheckCircle className="h-12 w-12 mx-auto text-green-500" />
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-lg font-semibold">
|
||||
Thanks for subscribing!
|
||||
</h3>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
You can opt out at any time using the unsubscribe link in our emails.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => {
|
||||
localStorage.removeItem('shakespeare-email-subscribed');
|
||||
setIsSubmitted(false);
|
||||
setEmail('');
|
||||
}}
|
||||
variant="outline"
|
||||
className="w-full text-xs"
|
||||
>
|
||||
Subscribe with different email
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<Mail className="h-5 w-5 text-primary" />
|
||||
{t('emailUpdates')}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{t('emailUpdatesDescription')}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">
|
||||
Email Address
|
||||
</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder="[email protected]"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
disabled={isSubmitting}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full"
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
{isSubmitting ? 'Subscribing...' : 'Subscribe to Updates'}
|
||||
</Button>
|
||||
|
||||
<p className="text-xs text-muted-foreground text-center">
|
||||
You can opt out at any time using the unsubscribe link in our emails.
|
||||
</p>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
@@ -47,7 +47,7 @@ import { cn } from '@/lib/utils';
|
||||
import { findCredentialsForRepo } from '@/lib/gitCredentials';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
const GRASP_SERVERS = ["git.shakespeare.diy", "relay.ngit.dev", "gitnostr.com"];
|
||||
const GRASP_SERVERS = ["git.shakespeare.diy", "relay.ngit.dev"];
|
||||
|
||||
interface GitDialogProps {
|
||||
projectId: string;
|
||||
@@ -62,6 +62,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
const [isPushingToNostr, setIsPushingToNostr] = useState(false);
|
||||
const [originUrl, setOriginUrl] = useState('');
|
||||
const [isSavingOrigin, setIsSavingOrigin] = useState(false);
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId);
|
||||
@@ -334,6 +335,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
title: "Push to Nostr failed",
|
||||
description: errorMessage,
|
||||
variant: "destructive",
|
||||
duration: Infinity,
|
||||
});
|
||||
} finally {
|
||||
setIsPushingToNostr(false);
|
||||
@@ -395,6 +397,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
title: "Push failed",
|
||||
description: errorMessage,
|
||||
variant: "destructive",
|
||||
duration: Infinity,
|
||||
});
|
||||
} finally {
|
||||
setIsPushing(false);
|
||||
@@ -425,6 +428,12 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
try {
|
||||
const remote = gitStatus.remotes[0]; // Use first remote (usually 'origin')
|
||||
|
||||
// Get the current HEAD commit before pulling
|
||||
const beforeCommit = await git.resolveRef({
|
||||
dir: projectPath,
|
||||
ref: 'HEAD',
|
||||
});
|
||||
|
||||
await git.pull({
|
||||
dir: projectPath,
|
||||
ref: gitStatus.currentBranch,
|
||||
@@ -436,20 +445,38 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
onAuth: (url) => findCredentialsForRepo(url, settings.credentials),
|
||||
});
|
||||
|
||||
// Get the current HEAD commit after pulling
|
||||
const afterCommit = await git.resolveRef({
|
||||
dir: projectPath,
|
||||
ref: 'HEAD',
|
||||
});
|
||||
|
||||
// Check if the repository actually changed
|
||||
const repoChanged = beforeCommit !== afterCommit;
|
||||
|
||||
toast({
|
||||
title: "Pull successful",
|
||||
description: `Latest changes pulled from ${remote.name}/${gitStatus.currentBranch}`,
|
||||
description: repoChanged
|
||||
? `Latest changes pulled from ${remote.name}/${gitStatus.currentBranch}`
|
||||
: `Already up to date with ${remote.name}/${gitStatus.currentBranch}`,
|
||||
});
|
||||
|
||||
// Refresh git status after pull
|
||||
await refetchGitStatus();
|
||||
|
||||
// Only trigger build if the repository actually changed
|
||||
if (repoChanged) {
|
||||
const newSearchParams = new URLSearchParams(searchParams);
|
||||
newSearchParams.set('build', '');
|
||||
setSearchParams(newSearchParams);
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
|
||||
toast({
|
||||
title: "Pull failed",
|
||||
description: errorMessage,
|
||||
variant: "destructive",
|
||||
duration: Infinity,
|
||||
});
|
||||
} finally {
|
||||
setIsPulling(false);
|
||||
|
||||
@@ -168,7 +168,9 @@ export function ModelSelector({
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-96 p-0" align="end">
|
||||
<Command>
|
||||
{isConfigured && <CommandInput placeholder={t('searchModels')} className="h-9" />}
|
||||
{(isConfigured && models.length >= 5) && (
|
||||
<CommandInput placeholder={t('searchModels')} className="h-9" />
|
||||
)}
|
||||
<CommandList className="max-h-[300px]">
|
||||
<CommandEmpty>
|
||||
<div className="py-6 text-center text-sm text-muted-foreground">
|
||||
|
||||
@@ -18,7 +18,6 @@ const GIT_KINDS = [
|
||||
const GIT_RELAYS = [
|
||||
'wss://git.shakespeare.diy/',
|
||||
'wss://relay.ngit.dev/',
|
||||
'wss://gitnostr.com/',
|
||||
];
|
||||
|
||||
const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { OnboardingCreditsBadge } from './OnboardingCreditsBadge';
|
||||
import type { UseQueryResult } from '@tanstack/react-query';
|
||||
import type { CreditsResponse } from '@/hooks/useAICredits';
|
||||
|
||||
// Mock the useAICredits hook
|
||||
vi.mock('@/hooks/useAICredits', () => ({
|
||||
useAICredits: vi.fn(),
|
||||
}));
|
||||
|
||||
import { useAICredits } from '@/hooks/useAICredits';
|
||||
|
||||
const mockUseAICredits = vi.mocked(useAICredits);
|
||||
|
||||
describe('OnboardingCreditsBadge', () => {
|
||||
const mockProvider = {
|
||||
id: 'shakespeare',
|
||||
baseURL: 'https://ai.shakespeare.diy/v1',
|
||||
nostr: true,
|
||||
};
|
||||
|
||||
it('renders credits badge when data is available', () => {
|
||||
mockUseAICredits.mockReturnValue({
|
||||
data: { object: 'credits', amount: 25.50 },
|
||||
isLoading: false,
|
||||
error: null,
|
||||
} as UseQueryResult<CreditsResponse, Error>);
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<OnboardingCreditsBadge provider={mockProvider} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('$25.50')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not render when loading', () => {
|
||||
mockUseAICredits.mockReturnValue({
|
||||
data: undefined,
|
||||
isLoading: true,
|
||||
error: null,
|
||||
} as UseQueryResult<CreditsResponse, Error>);
|
||||
|
||||
const { container } = render(
|
||||
<TestApp>
|
||||
<OnboardingCreditsBadge provider={mockProvider} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it('does not render when there is an error', () => {
|
||||
mockUseAICredits.mockReturnValue({
|
||||
data: undefined,
|
||||
isLoading: false,
|
||||
error: new Error('Provider does not support credits'),
|
||||
} as UseQueryResult<CreditsResponse, Error>);
|
||||
|
||||
const { container } = render(
|
||||
<TestApp>
|
||||
<OnboardingCreditsBadge provider={mockProvider} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it('does not render when no credits data is available', () => {
|
||||
mockUseAICredits.mockReturnValue({
|
||||
data: undefined,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
} as UseQueryResult<CreditsResponse, Error>);
|
||||
|
||||
const { container } = render(
|
||||
<TestApp>
|
||||
<OnboardingCreditsBadge provider={mockProvider} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it('does not render when credits amount is 0', () => {
|
||||
mockUseAICredits.mockReturnValue({
|
||||
data: { object: 'credits', amount: 0 },
|
||||
isLoading: false,
|
||||
error: null,
|
||||
} as UseQueryResult<CreditsResponse, Error>);
|
||||
|
||||
const { container } = render(
|
||||
<TestApp>
|
||||
<OnboardingCreditsBadge provider={mockProvider} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { AIProvider } from '@/contexts/AISettingsContext';
|
||||
import { useAICredits } from '@/hooks/useAICredits';
|
||||
|
||||
interface OnboardingCreditsBadgeProps {
|
||||
provider: AIProvider;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays a non-clickable credits badge for onboarding showing the remaining credits for an AI provider
|
||||
*/
|
||||
export function OnboardingCreditsBadge({ provider, className }: OnboardingCreditsBadgeProps) {
|
||||
const { data: credits, isLoading, error } = useAICredits(provider);
|
||||
|
||||
// Don't render anything if there's an error (provider doesn't support credits endpoint)
|
||||
if (error || isLoading) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Don't render if no credits data is available or if amount is 0
|
||||
if (!credits || credits.amount === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Format the amount as currency
|
||||
const formattedAmount = new Intl.NumberFormat('en-US', {
|
||||
style: 'currency',
|
||||
currency: 'USD',
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
}).format(credits.amount);
|
||||
|
||||
return (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className={`text-xs ${className}`}
|
||||
>
|
||||
{formattedAmount}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
@@ -42,7 +42,7 @@ describe('OnboardingDialog', () => {
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getAllByText('Welcome to Shakespeare!')).toHaveLength(2); // Title and heading
|
||||
expect(screen.getByText('Welcome to Shakespeare!')).toBeInTheDocument(); // Only in dialog title now
|
||||
expect(screen.getByText(/Your AI-powered development assistant/)).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /Get Started/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -1,59 +1,100 @@
|
||||
import { Decimal } from 'decimal.js';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { generateSecretKey } from 'nostr-tools';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { Bot, Check, Sparkles, ArrowRight, ArrowLeft } from 'lucide-react';
|
||||
import { Bot, Check, Sparkles, ArrowRight, ArrowLeft, ExternalLink } from 'lucide-react';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { PasswordInput } from '@/components/ui/password-input';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useLoginActions } from '@/hooks/useLoginActions';
|
||||
import { useProviderModels } from '@/hooks/useProviderModels';
|
||||
import { CreditsDialog } from '@/components/CreditsDialog';
|
||||
import { OnboardingCreditsBadge } from '@/components/OnboardingCreditsBadge';
|
||||
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
||||
import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface OnboardingDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
type OnboardingStep = 'welcome' | 'model-selection' | 'conclusion';
|
||||
|
||||
const SHAKESPEARE_PROVIDER = {
|
||||
id: "shakespeare",
|
||||
baseURL: "https://ai.shakespeare.diy/v1",
|
||||
nostr: true,
|
||||
};
|
||||
type OnboardingStep = 'welcome' | 'open-source' | 'provider-selection' | 'model-selection' | 'conclusion';
|
||||
|
||||
export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) {
|
||||
const [step, setStep] = useState<OnboardingStep>('welcome');
|
||||
const [selectedProvider, setSelectedProvider] = useState<PresetProvider | null>(null);
|
||||
const [providerApiKey, setProviderApiKey] = useState<string>('');
|
||||
const [selectedModel, setSelectedModel] = useState<string>('');
|
||||
const [isSettingUp, setIsSettingUp] = useState(false);
|
||||
const [showCreditsDialog, setShowCreditsDialog] = useState(false);
|
||||
const [agreedToTerms, setAgreedToTerms] = useState(false);
|
||||
const [agreedToProviderTerms, setAgreedToProviderTerms] = useState(false);
|
||||
|
||||
// Ref for the scrollable content area
|
||||
const scrollableContentRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const { setProvider, addRecentlyUsedModel } = useAISettings();
|
||||
const { user } = useCurrentUser();
|
||||
const login = useLoginActions();
|
||||
const { models, isLoading: isLoadingModels } = useProviderModels();
|
||||
|
||||
// Filter models to only show Shakespeare provider models
|
||||
const shakespeareModels = models.filter(model => model.provider === 'shakespeare');
|
||||
// Filter models to only show selected provider models
|
||||
const providerModels = selectedProvider
|
||||
? models.filter(model => model.provider === selectedProvider.id)
|
||||
: [];
|
||||
|
||||
const handleGetStarted = () => {
|
||||
setStep('open-source');
|
||||
};
|
||||
|
||||
const handleContinueFromOpenSource = () => {
|
||||
if (!agreedToTerms) return;
|
||||
setStep('provider-selection');
|
||||
};
|
||||
|
||||
const handleProviderSelect = (provider: PresetProvider) => {
|
||||
setSelectedProvider(provider);
|
||||
// Clear API key when switching providers
|
||||
setProviderApiKey('');
|
||||
// Reset provider terms agreement when switching providers
|
||||
setAgreedToProviderTerms(false);
|
||||
};
|
||||
|
||||
const handleContinueFromProviderSelection = async () => {
|
||||
if (!selectedProvider) return;
|
||||
|
||||
// Check if user agreed to provider terms
|
||||
if (!agreedToProviderTerms) return;
|
||||
|
||||
// Check if provider requires API key and if it's provided
|
||||
const requiresApiKey = selectedProvider.apiKeysURL && !selectedProvider.nostr;
|
||||
if (requiresApiKey && !providerApiKey.trim()) return;
|
||||
|
||||
const handleGetStarted = async () => {
|
||||
setIsSettingUp(true);
|
||||
|
||||
try {
|
||||
// If user is not logged in, generate and login with secret key
|
||||
if (!user) {
|
||||
// If user is not logged in and provider uses Nostr auth, generate and login with secret key
|
||||
if (!user && selectedProvider.nostr) {
|
||||
const secretKey = generateSecretKey();
|
||||
const nsec = nip19.nsecEncode(secretKey);
|
||||
login.nsec(nsec);
|
||||
}
|
||||
|
||||
// Add Shakespeare provider to their config
|
||||
setProvider(SHAKESPEARE_PROVIDER);
|
||||
// Add selected provider to their config
|
||||
const providerConfig = {
|
||||
id: selectedProvider.id,
|
||||
baseURL: selectedProvider.baseURL,
|
||||
nostr: selectedProvider.nostr || undefined,
|
||||
apiKey: requiresApiKey ? providerApiKey.trim() : undefined,
|
||||
};
|
||||
setProvider(providerConfig);
|
||||
|
||||
// Move to model selection
|
||||
setStep('model-selection');
|
||||
@@ -75,7 +116,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
addRecentlyUsedModel(selectedModel);
|
||||
|
||||
// Find the selected model to check if it's free
|
||||
const model = shakespeareModels.find(m => m.fullId === selectedModel);
|
||||
const model = providerModels.find(m => m.fullId === selectedModel);
|
||||
const isFreeModel = !model?.pricing || (
|
||||
model.pricing.prompt.equals(0) && model.pricing.completion.equals(0)
|
||||
);
|
||||
@@ -110,19 +151,30 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setStep('welcome');
|
||||
setSelectedProvider(null);
|
||||
setProviderApiKey('');
|
||||
setSelectedModel('');
|
||||
setIsSettingUp(false);
|
||||
setShowCreditsDialog(false);
|
||||
setAgreedToTerms(false);
|
||||
setAgreedToProviderTerms(false);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
// Scroll to top when step changes
|
||||
useEffect(() => {
|
||||
if (scrollableContentRef.current) {
|
||||
scrollableContentRef.current.scrollTop = 0;
|
||||
}
|
||||
}, [step]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl max-h-[80vh] overflow-hidden">
|
||||
<DialogHeader>
|
||||
<DialogContent className="max-w-2xl h-[100dvh] sm:h-auto sm:max-h-[90vh] flex flex-col">
|
||||
<DialogHeader className="flex-shrink-0">
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
{step === 'model-selection' && (
|
||||
{step === 'open-source' && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
@@ -132,18 +184,48 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
{step === 'provider-selection' && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setStep('open-source')}
|
||||
className="mr-2 p-1 h-auto"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
{step === 'model-selection' && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setStep('provider-selection')}
|
||||
className="mr-2 p-1 h-auto"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
{step === 'conclusion' && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setStep('model-selection')}
|
||||
className="mr-2 p-1 h-auto"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
<span className="text-xl">
|
||||
{step === 'welcome' && 'Welcome to Shakespeare!'}
|
||||
{step === 'model-selection' && 'Choose Your AI Model'}
|
||||
{step === 'conclusion' && "You're All Set!"}
|
||||
</span>
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex-1 overflow-hidden">
|
||||
<div ref={scrollableContentRef} className="flex-1 overflow-y-auto min-h-0">
|
||||
{step === 'welcome' && (
|
||||
<div className="text-center space-y-6 py-4">
|
||||
<div className="text-6xl mb-4">🎭</div>
|
||||
<div className="mb-4">
|
||||
<ShakespeareLogo className="w-16 h-16 mx-auto" />
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
<h2 className="text-2xl font-bold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||
Welcome to Shakespeare!
|
||||
@@ -190,16 +272,213 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'model-selection' && (
|
||||
<div className="space-y-4">
|
||||
<div className="text-center space-y-2">
|
||||
<p className="text-muted-foreground">
|
||||
Choose an AI model to power your development experience.
|
||||
Different models offer various capabilities and pricing.
|
||||
{step === 'open-source' && (
|
||||
<div className="space-y-6 py-4">
|
||||
<div className="text-center space-y-4">
|
||||
<h2 className="text-2xl font-bold">Shakespeare is Open Source software that runs entirely in your web browser</h2>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-1 max-w-md mx-auto">
|
||||
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
|
||||
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
|
||||
<p className="text-sm">Your browser connects directly to third-party AI providers of your choice</p>
|
||||
</div>
|
||||
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
|
||||
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
|
||||
<p className="text-sm">Your files are stored on your device in your browser</p>
|
||||
</div>
|
||||
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
|
||||
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
|
||||
<p className="text-sm">Be careful not to delete your browser data or you may lose project files</p>
|
||||
</div>
|
||||
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
|
||||
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
|
||||
<p className="text-sm">You are responsible for taking backups or syncing to git</p>
|
||||
</div>
|
||||
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
|
||||
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
|
||||
<p className="text-sm">Quality of output depends on quality of input and models used, and is not guaranteed</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3 max-w-md mx-auto">
|
||||
<p className="text-xs text-muted-foreground max-w-xl mx-auto">
|
||||
Shakespeare is not a cloud service. It's Open Source software that runs in your web browser.
|
||||
You agree to the Terms of Service of AI providers you interact with.
|
||||
Shakespeare is provided "as is" without warranty of any kind.
|
||||
</p>
|
||||
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
<Checkbox
|
||||
id="agree-terms"
|
||||
checked={agreedToTerms}
|
||||
onCheckedChange={(checked) => setAgreedToTerms(checked === true)}
|
||||
/>
|
||||
<label
|
||||
htmlFor="agree-terms"
|
||||
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
|
||||
>
|
||||
I agree
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-center">
|
||||
<Button
|
||||
onClick={handleContinueFromOpenSource}
|
||||
disabled={!agreedToTerms}
|
||||
className="gap-2 rounded-full w-full max-w-md"
|
||||
>
|
||||
Continue
|
||||
<ArrowRight className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'provider-selection' && (
|
||||
<div className="space-y-6 py-4">
|
||||
<div className="text-center space-y-4">
|
||||
<h2 className="text-2xl font-bold">Choose your AI provider</h2>
|
||||
<p className="text-muted-foreground max-w-md mx-auto">
|
||||
Select an AI provider to power your development assistant. You can add more providers later in settings.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<ScrollArea className="h-96">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 p-1 gap-3 max-w-4xl mx-auto">
|
||||
{AI_PROVIDER_PRESETS.map((provider) => {
|
||||
const isSelected = selectedProvider?.id === provider.id;
|
||||
const isShakespeare = provider.id === 'shakespeare';
|
||||
|
||||
return (
|
||||
<Card
|
||||
key={provider.id}
|
||||
className={cn('cursor-pointer transition-all hover:shadow-md', {
|
||||
'ring-2 ring-primary': isSelected,
|
||||
})}
|
||||
onClick={() => handleProviderSelect(provider)}
|
||||
>
|
||||
<div className="flex items-center justify-between p-3">
|
||||
<div className="flex-1">
|
||||
<CardTitle className={cn('text-lg font-semibold', {
|
||||
'bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent': isShakespeare,
|
||||
})}>
|
||||
{provider.name}
|
||||
</CardTitle>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<OnboardingCreditsBadge provider={provider} />
|
||||
{isSelected && (
|
||||
<div className="h-5 w-5 rounded-full bg-primary flex items-center justify-center">
|
||||
<Check className="h-3 w-3 text-primary-foreground" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* API Key Input Section */}
|
||||
{selectedProvider && selectedProvider.apiKeysURL && !selectedProvider.nostr && (
|
||||
<div className="space-y-3 max-w-md mx-auto">
|
||||
<div className="text-center">
|
||||
<h3 className="text-lg font-semibold">
|
||||
{selectedProvider.id === 'routstr' ? 'Enter Cashu Token' : 'Enter API Key'}
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{selectedProvider.id === 'routstr' ? (
|
||||
<>{selectedProvider.name} requires a Cashu token</>
|
||||
) : (
|
||||
<>
|
||||
{selectedProvider.name} requires an {selectedProvider.apiKeysURL ? (
|
||||
<a className="text-foreground underline" href={selectedProvider.apiKeysURL} target="_blank">
|
||||
API key
|
||||
<ExternalLink className="inline-block h-4 w-4 ml-1" />
|
||||
</a>
|
||||
) : (
|
||||
<>API key</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<PasswordInput
|
||||
placeholder={selectedProvider.id === 'routstr' ? 'Enter a Cashu Token' : 'Enter your API key'}
|
||||
value={providerApiKey}
|
||||
onChange={(e) => setProviderApiKey(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && providerApiKey.trim()) {
|
||||
handleContinueFromProviderSelection();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Terms of Service Agreement */}
|
||||
{selectedProvider && (
|
||||
<div className="space-y-3 max-w-md mx-auto">
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
<Checkbox
|
||||
id="agree-provider-terms"
|
||||
checked={agreedToProviderTerms}
|
||||
onCheckedChange={(checked) => setAgreedToProviderTerms(checked === true)}
|
||||
/>
|
||||
<label
|
||||
htmlFor="agree-provider-terms"
|
||||
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
|
||||
>
|
||||
I agree to {selectedProvider.name}'s{' '}
|
||||
{selectedProvider.tosURL ? (
|
||||
<a
|
||||
href={selectedProvider.tosURL}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary underline hover:no-underline"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
Terms of Service
|
||||
</a>
|
||||
) : (
|
||||
'Terms of Service'
|
||||
)}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-center">
|
||||
<Button
|
||||
onClick={handleContinueFromProviderSelection}
|
||||
disabled={
|
||||
!selectedProvider ||
|
||||
isSettingUp ||
|
||||
!agreedToProviderTerms ||
|
||||
!!(selectedProvider?.apiKeysURL && !selectedProvider?.nostr && !providerApiKey.trim())
|
||||
}
|
||||
className="gap-2 rounded-full w-full max-w-md"
|
||||
>
|
||||
{isSettingUp ? (
|
||||
<>
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white" />
|
||||
Setting up...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
Continue
|
||||
<ArrowRight className="h-4 w-4" />
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'model-selection' && (
|
||||
<div className="flex flex-col h-full">
|
||||
<div className="flex-1 overflow-y-auto min-h-0 my-4">
|
||||
<div className="space-y-3 p-1">
|
||||
{isLoadingModels ? (
|
||||
<>
|
||||
@@ -219,7 +498,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
</Card>
|
||||
))}
|
||||
</>
|
||||
) : shakespeareModels.length === 0 ? (
|
||||
) : providerModels.length === 0 ? (
|
||||
<Card className="p-6 text-center">
|
||||
<div className="space-y-2">
|
||||
<Bot className="h-8 w-8 mx-auto text-muted-foreground" />
|
||||
@@ -229,9 +508,11 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
</div>
|
||||
</Card>
|
||||
) : (
|
||||
shakespeareModels.map((model) => {
|
||||
providerModels.map((model) => {
|
||||
const isSelected = selectedModel === model.fullId;
|
||||
const isFree = model.pricing?.prompt.equals(0) && model.pricing?.completion.equals(0);
|
||||
const isPremium = !!model.pricing && !isFree;
|
||||
const modelName = model.name || model.id;
|
||||
|
||||
return (
|
||||
<Card
|
||||
@@ -241,15 +522,19 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
}`}
|
||||
onClick={() => handleModelSelect(model.fullId)}
|
||||
>
|
||||
<CardHeader className="pb-3">
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex-1">
|
||||
<CardTitle className="text-base font-semibold">
|
||||
{model.description || model.name || model.id}
|
||||
<CardTitle className={cn('text-xl font-semibold', {
|
||||
'bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent': isPremium,
|
||||
})}>
|
||||
{modelName}
|
||||
</CardTitle>
|
||||
{model.description && (
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{model.name || model.id}
|
||||
{model.description.length > 70
|
||||
? model.description.slice(0, 70) + '...'
|
||||
: model.description}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
@@ -259,6 +544,11 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
Free
|
||||
</Badge>
|
||||
)}
|
||||
{isPremium && (
|
||||
<Badge className="text-xs bg-primary text-white border-0">
|
||||
Premium
|
||||
</Badge>
|
||||
)}
|
||||
{isSelected && (
|
||||
<div className="h-5 w-5 rounded-full bg-primary flex items-center justify-center">
|
||||
<Check className="h-3 w-3 text-primary-foreground" />
|
||||
@@ -267,27 +557,29 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0">
|
||||
<div className="flex items-center gap-4 text-xs text-muted-foreground">
|
||||
{model.pricing && (
|
||||
<>
|
||||
<span>Input: {formatPrice(model.pricing.prompt)}</span>
|
||||
<span>Output: {formatPrice(model.pricing.completion)}</span>
|
||||
</>
|
||||
)}
|
||||
{model.contextLength && (
|
||||
<span>Context: {model.contextLength.toLocaleString()} tokens</span>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
{(model.pricing || model.contextLength) && (
|
||||
<CardContent className="pt-0">
|
||||
<div className="flex items-end justify-end gap-4 text-xs text-muted-foreground">
|
||||
{model.pricing && (
|
||||
<div className="text-right">
|
||||
<div>Input: {formatPrice(model.pricing.prompt)}</div>
|
||||
<div>Output: {formatPrice(model.pricing.completion)}</div>
|
||||
</div>
|
||||
)}
|
||||
{model.contextLength && (
|
||||
<span>Context: {model.contextLength.toLocaleString()} tokens</span>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2 pt-4 border-t">
|
||||
<div className="flex justify-end gap-2 pt-4 flex-shrink-0">
|
||||
<Button
|
||||
onClick={handleContinue}
|
||||
disabled={!selectedModel}
|
||||
@@ -310,11 +602,6 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
Just enter your prompt to start building amazing Nostr applications.
|
||||
</p>
|
||||
</div>
|
||||
<div className="bg-muted/50 rounded-lg p-4 max-w-md mx-auto">
|
||||
<p className="text-sm text-muted-foreground italic">
|
||||
"Create a farming equipment marketplace for local farmers to buy and sell tractors, tools, and supplies..."
|
||||
</p>
|
||||
</div>
|
||||
<Button onClick={handleFinish} size="lg" className="gap-2">
|
||||
<Sparkles className="h-4 w-4" />
|
||||
Start Building
|
||||
@@ -326,7 +613,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
</Dialog>
|
||||
|
||||
{/* Credits Dialog */}
|
||||
{showCreditsDialog && selectedModel && (
|
||||
{showCreditsDialog && selectedModel && selectedProvider && (
|
||||
<CreditsDialog
|
||||
open={showCreditsDialog}
|
||||
onOpenChange={(open) => {
|
||||
@@ -334,7 +621,11 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
handleCreditsDialogClose();
|
||||
}
|
||||
}}
|
||||
provider={SHAKESPEARE_PROVIDER}
|
||||
provider={{
|
||||
id: selectedProvider.id,
|
||||
baseURL: selectedProvider.baseURL,
|
||||
nostr: selectedProvider.nostr || undefined,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
|
||||
@@ -208,7 +208,7 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogContent className="max-w-md" onOpenAutoFocus={(e) => e.preventDefault()}>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Folder className="h-5 w-5" />
|
||||
|
||||
@@ -60,7 +60,7 @@ describe('ProjectSidebar', () => {
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('🎭')).toBeInTheDocument();
|
||||
expect(screen.getByAltText('Shakespeare')).toBeInTheDocument();
|
||||
expect(screen.getByText('Shakespeare')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import React, { useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle, FileArchive } from 'lucide-react';
|
||||
import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
|
||||
@@ -9,12 +9,10 @@ import { useProjects } from '@/hooks/useProjects';
|
||||
import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { ZipImportDialog } from '@/components/ZipImportDialog';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import type { Project } from '@/lib/ProjectsManager';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
||||
|
||||
interface ProjectItemProps {
|
||||
project: Project;
|
||||
@@ -95,9 +93,6 @@ export function ProjectSidebar({
|
||||
const queryClient = useQueryClient();
|
||||
const { data: projects = [], isLoading, error } = useProjects();
|
||||
const [favorites] = useLocalStorage<string[]>('project-favorites', []);
|
||||
const projectsManager = useProjectsManager();
|
||||
const { toast } = useToast();
|
||||
const [isZipDialogOpen, setIsZipDialogOpen] = useState(false);
|
||||
|
||||
const isMobile = useIsMobile();
|
||||
const navigate = useNavigate();
|
||||
@@ -123,24 +118,7 @@ export function ProjectSidebar({
|
||||
}
|
||||
};
|
||||
|
||||
const handleImportZip = async (file: File, overwrite = false, projectId?: string) => {
|
||||
try {
|
||||
// Import project from zip file
|
||||
const project = await projectsManager.importProjectFromZip(file, projectId, overwrite);
|
||||
|
||||
// Show success toast
|
||||
toast({
|
||||
title: overwrite ? "Project Overwritten Successfully" : "Project Imported Successfully",
|
||||
description: `"${project.name}" has been ${overwrite ? 'overwritten' : 'imported'} and is ready to use.`,
|
||||
});
|
||||
|
||||
// Navigate to the imported project
|
||||
navigate(`/project/${project.id}`);
|
||||
} catch (error) {
|
||||
console.error('Failed to import project:', error);
|
||||
throw error; // Re-throw to let the dialog handle the error display
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
queryClient.invalidateQueries({ queryKey: ['projects'] });
|
||||
@@ -159,7 +137,7 @@ export function ProjectSidebar({
|
||||
onClick={() => navigateAndClose('/')}
|
||||
className="flex items-center gap-3 hover:opacity-80 transition-opacity text-left"
|
||||
>
|
||||
<span className="text-2xl">🎭</span>
|
||||
<ShakespeareLogo className="w-6 h-6" />
|
||||
<h1 className="text-xl font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||
Shakespeare
|
||||
</h1>
|
||||
@@ -211,13 +189,6 @@ export function ProjectSidebar({
|
||||
<GitBranch className="h-4 w-4" />
|
||||
{t('importRepository')}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => setIsZipDialogOpen(true)}
|
||||
className="flex items-center gap-2 w-full"
|
||||
>
|
||||
<FileArchive className="h-4 w-4" />
|
||||
Import ZIP File
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
@@ -281,12 +252,7 @@ export function ProjectSidebar({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ZIP Import Dialog */}
|
||||
<ZipImportDialog
|
||||
onImport={handleImportZip}
|
||||
open={isZipDialogOpen}
|
||||
onOpenChange={setIsZipDialogOpen}
|
||||
/>
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import OpenAI from 'openai';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { X } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { QuillySVG } from '@/components/ui/QuillySVG';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
import { useAICredits } from '@/hooks/useAICredits';
|
||||
import { CreditsDialog } from './CreditsDialog';
|
||||
import { ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||
import { useState } from 'react';
|
||||
|
||||
export interface QuillyProps {
|
||||
error: Error;
|
||||
onDismiss: () => void;
|
||||
onNewChat: () => void;
|
||||
onOpenModelSelector: () => void;
|
||||
onRequestConsoleErrorHelp?: (error: ProjectPreviewConsoleError) => void;
|
||||
providerModel: string;
|
||||
}
|
||||
|
||||
interface ErrorBody {
|
||||
message: string;
|
||||
action?: {
|
||||
label: string;
|
||||
onClick: () => void;
|
||||
};
|
||||
}
|
||||
|
||||
export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onRequestConsoleErrorHelp, providerModel }: QuillyProps) {
|
||||
const navigate = useNavigate();
|
||||
const { settings } = useAISettings();
|
||||
|
||||
// Handle empty provider model gracefully
|
||||
let provider;
|
||||
try {
|
||||
provider = parseProviderModel(providerModel, settings.providers).provider;
|
||||
} catch {
|
||||
// If no valid provider model, use a default or undefined
|
||||
provider = undefined;
|
||||
}
|
||||
|
||||
const credits = useAICredits(provider || { id: '', name: '', apiKey: '', nostr: false });
|
||||
const [showCreditsDialog, setShowCreditsDialog] = useState(false);
|
||||
|
||||
const renderBody = (error: Error): ErrorBody => {
|
||||
// Handle Project Preview Console Errors
|
||||
if (error instanceof ProjectPreviewConsoleError) {
|
||||
return {
|
||||
message: 'I noticed some console errors in your project preview. Would you like me to take a look and help fix them?',
|
||||
action: {
|
||||
label: 'Help fix errors',
|
||||
onClick: () => {
|
||||
onRequestConsoleErrorHelp?.(error);
|
||||
onDismiss();
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Handle OpenAI API errors with specific error codes
|
||||
if (error instanceof OpenAI.APIError) {
|
||||
switch (error.code) {
|
||||
case 'invalid_api_key':
|
||||
case 'invalid_request_error':
|
||||
return {
|
||||
message: 'Authentication error: Please check your API key in AI settings.',
|
||||
action: {
|
||||
label: 'Check API key',
|
||||
onClick: () => navigate('/settings/ai'),
|
||||
}
|
||||
};
|
||||
|
||||
case 'insufficient_quota': {
|
||||
if (credits.data) {
|
||||
return {
|
||||
message: `Your account has $${credits.data.amount.toFixed(2)} credits. Please add credits to keep creating.`,
|
||||
action: {
|
||||
label: 'Add credits',
|
||||
onClick: () => setShowCreditsDialog(true),
|
||||
}
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
message: 'Your API key has reached its usage limit. Please check your billing or try a different provider.',
|
||||
action: {
|
||||
label: 'Check AI settings',
|
||||
onClick: () => navigate('/settings/ai'),
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
case 'rate_limit_exceeded':
|
||||
return {
|
||||
message: 'Rate limit exceeded. Please wait a moment before trying again.',
|
||||
};
|
||||
|
||||
case 'model_not_found':
|
||||
return {
|
||||
message: 'The selected AI model is not available. Please choose a different model.',
|
||||
action: {
|
||||
label: 'Choose model',
|
||||
onClick: onOpenModelSelector,
|
||||
},
|
||||
};
|
||||
|
||||
case 'context_length_exceeded':
|
||||
return {
|
||||
message: 'Your conversation is too long for this model. Try starting a new chat or switching to a model with a larger context window.',
|
||||
action: {
|
||||
label: 'New chat',
|
||||
onClick: onNewChat,
|
||||
},
|
||||
};
|
||||
|
||||
case 'server_error':
|
||||
case 'service_unavailable':
|
||||
return {
|
||||
message: 'The AI service is temporarily unavailable. Please try again in a moment.',
|
||||
};
|
||||
|
||||
default:
|
||||
return {
|
||||
message: `AI service error: ${error.message}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Default fallback
|
||||
return {
|
||||
message: error.message
|
||||
? `AI service error: ${error.message}`
|
||||
: 'Sorry, I encountered an unexpected error. Please try again.',
|
||||
};
|
||||
};
|
||||
|
||||
const { message, action } = renderBody(error);
|
||||
|
||||
return (
|
||||
<div className="py-2 px-3 bg-primary/5 border border-primary/20 rounded-lg">
|
||||
<div className="flex items-start gap-2">
|
||||
<QuillySVG className="h-20 px-2 flex-shrink-0" fillColor="hsl(var(--primary))" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="space-y-1">
|
||||
<h4 className="font-semibold text-primary">
|
||||
Pardon the interruption
|
||||
</h4>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{message}
|
||||
{' '}
|
||||
{action && (
|
||||
<button className="text-primary underline" onClick={action.onClick}>
|
||||
{action.label}
|
||||
</button>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onDismiss}
|
||||
className="h-5 w-5 p-0 hover:text-foreground/70 hover:bg-transparent flex-shrink-0"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<CreditsDialog
|
||||
open={showCreditsDialog}
|
||||
onOpenChange={setShowCreditsDialog}
|
||||
provider={provider}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import { useNavigate, useLocation, Outlet } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Menu, Bot, GitBranch, Database, Wifi, Settings2, Info, Mail } from 'lucide-react';
|
||||
import { Menu, Bot, GitBranch, Database, Wifi, Settings2, Info } from 'lucide-react';
|
||||
import { ProjectSidebar } from '@/components/ProjectSidebar';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
@@ -56,13 +56,6 @@ const getSettingsItems = (t: (key: string) => string): SettingsItem[] => [
|
||||
icon: Database,
|
||||
href: '/settings/data',
|
||||
},
|
||||
{
|
||||
id: 'email',
|
||||
title: t('emailUpdates'),
|
||||
description: t('emailUpdatesDescription'),
|
||||
icon: Mail,
|
||||
href: '/settings/email',
|
||||
},
|
||||
{
|
||||
id: 'about',
|
||||
title: t('aboutShakespeare'),
|
||||
|
||||
@@ -1,313 +0,0 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent, act } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { ChatPane } from './ChatPane';
|
||||
|
||||
// Mock the AI settings hook to return configured state
|
||||
vi.mock('@/hooks/useAISettings', () => ({
|
||||
useAISettings: () => ({
|
||||
isConfigured: true,
|
||||
settings: {
|
||||
providers: [],
|
||||
recentlyUsedModels: ['gpt-4'],
|
||||
},
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
updateSettings: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock other hooks
|
||||
vi.mock('@/hooks/useFS', () => ({
|
||||
useFS: () => ({
|
||||
fs: {},
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useCurrentUser', () => ({
|
||||
useCurrentUser: () => ({
|
||||
user: null,
|
||||
metadata: null,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useKeepAlive', () => ({
|
||||
useKeepAlive: () => ({
|
||||
updateMetadata: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useAIChat', () => ({
|
||||
useAIChat: () => ({
|
||||
messages: [],
|
||||
streamingMessage: null,
|
||||
isLoading: false,
|
||||
totalCost: 0,
|
||||
lastInputTokens: 0,
|
||||
sendMessage: vi.fn(),
|
||||
startGeneration: vi.fn(),
|
||||
stopGeneration: vi.fn(),
|
||||
startNewSession: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useProviderModels', () => ({
|
||||
useProviderModels: () => ({
|
||||
models: [
|
||||
{
|
||||
fullId: 'gpt-4',
|
||||
contextLength: 8192,
|
||||
},
|
||||
],
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useToast', () => ({
|
||||
useToast: () => ({
|
||||
toast: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
describe('ChatPane', () => {
|
||||
describe('Placeholder switching', () => {
|
||||
it('shows "Please select a model" placeholder when providerModel is empty', () => {
|
||||
// Create a test that doesn't require modifying mocks
|
||||
// Instead, we'll test the existing behavior which shows the placeholder when configured
|
||||
render(
|
||||
<TestApp>
|
||||
<ChatPane projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const textarea = screen.getByPlaceholderText(/Ask me to add features/);
|
||||
expect(textarea).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows "Ask me to add features" placeholder when providerModel is set', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ChatPane projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const textarea = screen.getByPlaceholderText(/Ask me to add features/);
|
||||
expect(textarea).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Drag and drop functionality', () => {
|
||||
it('handles dropping a single valid file', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ChatPane projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const chatContainer = screen.getByPlaceholderText(/Ask me to add features/).closest('div')?.parentElement;
|
||||
expect(chatContainer).toBeInTheDocument();
|
||||
|
||||
const validFile = new File(['test content'], 'test.txt', { type: 'text/plain' });
|
||||
|
||||
// Simulate drag and drop events
|
||||
act(() => {
|
||||
if (chatContainer) {
|
||||
fireEvent.dragEnter(chatContainer, {
|
||||
dataTransfer: { files: [] },
|
||||
preventDefault: vi.fn(),
|
||||
stopPropagation: vi.fn(),
|
||||
});
|
||||
|
||||
fireEvent.dragOver(chatContainer, {
|
||||
dataTransfer: { files: [validFile] },
|
||||
preventDefault: vi.fn(),
|
||||
stopPropagation: vi.fn(),
|
||||
});
|
||||
|
||||
fireEvent.drop(chatContainer, {
|
||||
dataTransfer: { files: [validFile] },
|
||||
preventDefault: vi.fn(),
|
||||
stopPropagation: vi.fn(),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Verify the drop was handled (no errors thrown)
|
||||
expect(chatContainer).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('handles dropping multiple valid files', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ChatPane projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const chatContainer = screen.getByPlaceholderText(/Ask me to add features/).closest('div')?.parentElement;
|
||||
expect(chatContainer).toBeInTheDocument();
|
||||
|
||||
const files = [
|
||||
new File(['content1'], 'file1.txt', { type: 'text/plain' }),
|
||||
new File(['content2'], 'file2.txt', { type: 'text/plain' }),
|
||||
];
|
||||
|
||||
// Simulate drag and drop events
|
||||
act(() => {
|
||||
if (chatContainer) {
|
||||
fireEvent.dragEnter(chatContainer, {
|
||||
dataTransfer: { files: [] },
|
||||
preventDefault: vi.fn(),
|
||||
stopPropagation: vi.fn(),
|
||||
});
|
||||
|
||||
fireEvent.dragOver(chatContainer, {
|
||||
dataTransfer: { files },
|
||||
preventDefault: vi.fn(),
|
||||
stopPropagation: vi.fn(),
|
||||
});
|
||||
|
||||
fireEvent.drop(chatContainer, {
|
||||
dataTransfer: { files },
|
||||
preventDefault: vi.fn(),
|
||||
stopPropagation: vi.fn(),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Verify the drop was handled (no errors thrown)
|
||||
expect(chatContainer).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('handles dropping an unsupported file type', () => {
|
||||
// Test that the drop handler exists and doesn't throw errors
|
||||
render(
|
||||
<TestApp>
|
||||
<ChatPane projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const chatContainer = screen.getByPlaceholderText(/Ask me to add features/).closest('div')?.parentElement;
|
||||
expect(chatContainer).toBeInTheDocument();
|
||||
|
||||
const unsupportedFile = new File(['malicious content'], 'virus.exe', { type: 'application/x-executable' });
|
||||
|
||||
// Simulate drag and drop events - should not throw errors
|
||||
act(() => {
|
||||
if (chatContainer) {
|
||||
fireEvent.dragEnter(chatContainer, {
|
||||
dataTransfer: { files: [] },
|
||||
preventDefault: vi.fn(),
|
||||
stopPropagation: vi.fn(),
|
||||
});
|
||||
|
||||
fireEvent.dragOver(chatContainer, {
|
||||
dataTransfer: { files: [unsupportedFile] },
|
||||
preventDefault: vi.fn(),
|
||||
stopPropagation: vi.fn(),
|
||||
});
|
||||
|
||||
fireEvent.drop(chatContainer, {
|
||||
dataTransfer: { files: [unsupportedFile] },
|
||||
preventDefault: vi.fn(),
|
||||
stopPropagation: vi.fn(),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Test passes if no errors are thrown during drop
|
||||
expect(chatContainer).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('adds visual drag-over state during drag operations', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ChatPane projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const chatContainer = screen.getByPlaceholderText(/Ask me to add features/).closest('div')?.parentElement;
|
||||
expect(chatContainer).toBeInTheDocument();
|
||||
|
||||
const _file = new File(['test content'], 'test.txt', { type: 'text/plain' });
|
||||
|
||||
// Simulate drag enter - should not throw errors
|
||||
act(() => {
|
||||
if (chatContainer) {
|
||||
fireEvent.dragEnter(chatContainer, {
|
||||
dataTransfer: { files: [] },
|
||||
preventDefault: vi.fn(),
|
||||
stopPropagation: vi.fn(),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Test passes if no errors are thrown during drag operations
|
||||
expect(chatContainer).toBeInTheDocument();
|
||||
|
||||
// Simulate drag leave
|
||||
act(() => {
|
||||
if (chatContainer) {
|
||||
fireEvent.dragLeave(chatContainer, {
|
||||
dataTransfer: { files: [] },
|
||||
preventDefault: vi.fn(),
|
||||
stopPropagation: vi.fn(),
|
||||
relatedTarget: null, // Simulate leaving the container
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Test passes if no errors are thrown during drag operations
|
||||
expect(chatContainer).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('handles image paste from clipboard', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ChatPane projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const textarea = screen.getByPlaceholderText(/Ask me to add features/);
|
||||
expect(textarea).toBeInTheDocument();
|
||||
|
||||
// Create a mock image file
|
||||
const imageFile = new File(['fake-image-data'], 'test.png', {
|
||||
type: 'image/png',
|
||||
});
|
||||
|
||||
// Create mock clipboard data
|
||||
const mockClipboardItem = {
|
||||
type: 'image/png',
|
||||
getAsFile: () => imageFile,
|
||||
} as DataTransferItem;
|
||||
|
||||
const mockClipboardData = {
|
||||
items: [mockClipboardItem],
|
||||
length: 1,
|
||||
} as unknown as DataTransfer;
|
||||
|
||||
// Fire the paste event on the textarea using fireEvent
|
||||
fireEvent.paste(textarea, {
|
||||
clipboardData: mockClipboardData,
|
||||
});
|
||||
|
||||
// The file should be added to the attached files
|
||||
// We can't easily test the internal state, but we can verify the event was handled
|
||||
// without throwing an error
|
||||
expect(textarea).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders welcome message when no messages exist', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ChatPane projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Welcome to Shakespeare')).toBeInTheDocument();
|
||||
expect(screen.getByText(/Your AI-powered development assistant/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -8,7 +8,7 @@ import { CircularProgress } from '@/components/ui/circular-progress';
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import { FileAttachment } from '@/components/ui/file-attachment';
|
||||
import { OnboardingDialog } from '@/components/OnboardingDialog';
|
||||
import { Square, Loader2, ChevronDown, ArrowUp, X } from 'lucide-react';
|
||||
import { Square, Loader2, ChevronDown, ArrowUp } from 'lucide-react';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
@@ -34,67 +34,26 @@ import { NostrReadNipsIndexTool } from '@/lib/tools/NostrReadNipsIndexTool';
|
||||
import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool';
|
||||
import { ShellTool } from '@/lib/tools/ShellTool';
|
||||
import { TypecheckTool } from '@/lib/tools/TypecheckTool';
|
||||
import { ReadConsoleMessagesTool, ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
|
||||
import { Tool } from '@/lib/tools/Tool';
|
||||
import OpenAI from 'openai';
|
||||
import { saveFileToTmp } from '@/lib/fileUtils';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useConsoleErrorAlert, useAIModelErrorAlert } from '@/hooks/useErrorDetection';
|
||||
import { QuillySVG } from '@/components/ui/QuillySVG';
|
||||
|
||||
|
||||
function ChatIntervention({
|
||||
message,
|
||||
onDismiss,
|
||||
action,
|
||||
}: {
|
||||
message: string;
|
||||
onDismiss: () => void;
|
||||
action?: { label: string; onClick: () => void };
|
||||
}) {
|
||||
return (
|
||||
<div className="py-2 px-3 bg-primary/5 border border-primary/20 rounded-lg">
|
||||
<div className="flex items-start gap-2">
|
||||
<QuillySVG className="h-20 px-2 flex-shrink-0" fillColor="hsl(var(--primary))" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="space-y-1">
|
||||
<h4 className="font-semibold text-primary">
|
||||
Pardon the interruption
|
||||
</h4>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{message}
|
||||
{' '}
|
||||
{action && (
|
||||
<button className="text-primary underline" onClick={action.onClick}>
|
||||
{action.label}
|
||||
</button>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onDismiss}
|
||||
className="h-5 w-5 p-0 hover:text-foreground/70 hover:bg-transparent flex-shrink-0"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
import { Quilly } from '@/components/Quilly';
|
||||
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
||||
|
||||
// Clean interfaces now handled by proper hooks
|
||||
|
||||
interface ChatPaneProps {
|
||||
projectId: string;
|
||||
onNewChat?: () => void;
|
||||
onBuild?: () => void;
|
||||
onNewChat: () => void;
|
||||
onFirstInteraction?: () => void;
|
||||
onLoadingChange?: (isLoading: boolean) => void;
|
||||
isLoading?: boolean;
|
||||
isBuildLoading?: boolean;
|
||||
consoleError?: ProjectPreviewConsoleError | null;
|
||||
onDismissConsoleError?: () => void;
|
||||
}
|
||||
|
||||
export interface ChatPaneRef {
|
||||
@@ -103,14 +62,20 @@ export interface ChatPaneRef {
|
||||
|
||||
export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
projectId,
|
||||
onNewChat: _onNewChat,
|
||||
onBuild: _onBuild,
|
||||
onNewChat,
|
||||
onFirstInteraction,
|
||||
onLoadingChange,
|
||||
isLoading: externalIsLoading,
|
||||
isBuildLoading: externalIsBuildLoading,
|
||||
consoleError,
|
||||
onDismissConsoleError,
|
||||
}, ref) => {
|
||||
const { t } = useTranslation();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const { fs } = useFS();
|
||||
const { git } = useGit();
|
||||
const { user } = useCurrentUser();
|
||||
const { models } = useProviderModels();
|
||||
const [input, setInput] = useState('');
|
||||
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
|
||||
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
|
||||
@@ -118,6 +83,10 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
const [scrolledProjects] = useState(() => new Set<string>());
|
||||
const [showOnboarding, setShowOnboarding] = useState(false);
|
||||
const [isStuck, setIsStuck] = useState(false);
|
||||
const [aiError, setAIError] = useState<Error | null>(null);
|
||||
|
||||
// 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;
|
||||
@@ -129,6 +98,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
});
|
||||
// State to control model selector dropdown
|
||||
const [isModelSelectorOpen, setIsModelSelectorOpen] = useState(false);
|
||||
const [shouldAutostart, setShouldAutostart] = useState(false);
|
||||
const autostartedRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -137,11 +107,28 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
}, [providerModel, settings.recentlyUsedModels]);
|
||||
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const { fs } = useFS();
|
||||
const { git } = useGit();
|
||||
const { user } = useCurrentUser();
|
||||
const { models } = useProviderModels();
|
||||
useEffect(() => {
|
||||
const urlModel = searchParams.get('model');
|
||||
const autostart = searchParams.get('autostart');
|
||||
|
||||
if (urlModel && !providerModel) {
|
||||
setProviderModel(urlModel);
|
||||
}
|
||||
if (autostart === 'true') {
|
||||
setShouldAutostart(true);
|
||||
}
|
||||
|
||||
// Clear the autostart and model parameters
|
||||
const newSearchParams = new URLSearchParams(searchParams);
|
||||
newSearchParams.delete('autostart');
|
||||
newSearchParams.delete('model');
|
||||
setSearchParams(newSearchParams, { replace: true });
|
||||
}, [providerModel, searchParams, setSearchParams])
|
||||
|
||||
// Reset error state when navigating between projects and switching models
|
||||
useEffect(() => {
|
||||
setAIError(null);
|
||||
}, [projectId, providerModel]);
|
||||
|
||||
// Initialize AI chat with tools
|
||||
const cwd = `/projects/${projectId}`;
|
||||
@@ -163,6 +150,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
nostr_read_nips_index: new NostrReadNipsIndexTool(),
|
||||
nostr_generate_kind: new NostrGenerateKindTool(),
|
||||
shell: new ShellTool(fs, cwd, git),
|
||||
read_console_messages: new ReadConsoleMessagesTool(),
|
||||
};
|
||||
|
||||
// Add deploy tool only if user is logged in
|
||||
@@ -192,7 +180,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
artist: `Working on ${projectId}...`,
|
||||
artwork: [
|
||||
{
|
||||
src: '/favicon.png',
|
||||
src: '/shakespeare.png',
|
||||
sizes: '512x512',
|
||||
type: 'image/png'
|
||||
}
|
||||
@@ -204,12 +192,18 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
updateMetadata(title, description);
|
||||
}, [updateMetadata]);
|
||||
|
||||
// Handle AI errors from the SessionManager
|
||||
const onAIError = useCallback((error: Error) => {
|
||||
setAIError(error);
|
||||
}, []);
|
||||
|
||||
const {
|
||||
messages,
|
||||
streamingMessage,
|
||||
isLoading: internalIsLoading,
|
||||
totalCost,
|
||||
lastInputTokens,
|
||||
addMessage,
|
||||
sendMessage,
|
||||
startGeneration,
|
||||
stopGeneration,
|
||||
@@ -219,8 +213,47 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
tools,
|
||||
customTools,
|
||||
onUpdateMetadata,
|
||||
onAIError,
|
||||
});
|
||||
|
||||
// Handle console error help requests
|
||||
const handleConsoleErrorHelp = useCallback(async () => {
|
||||
const tool = new ReadConsoleMessagesTool();
|
||||
const toolCallId = `call_${crypto.randomUUID().replace(/-/g, '')}`;
|
||||
|
||||
await addMessage({
|
||||
role: 'assistant',
|
||||
content: 'Let me take a look at the console messages to help diagnose the issue.',
|
||||
tool_calls: [
|
||||
{
|
||||
id: toolCallId,
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'read_console_messages',
|
||||
arguments: '{}',
|
||||
}
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
await addMessage({
|
||||
role: 'tool',
|
||||
content: await tool.execute({ filter: 'error' }),
|
||||
tool_call_id: toolCallId,
|
||||
});
|
||||
|
||||
await startGeneration(providerModel);
|
||||
}, [addMessage, providerModel, startGeneration]);
|
||||
|
||||
// Handle error dismissal
|
||||
const handleErrorDismiss = useCallback(() => {
|
||||
if (consoleError && onDismissConsoleError) {
|
||||
onDismissConsoleError();
|
||||
} else {
|
||||
setAIError(null);
|
||||
}
|
||||
}, [consoleError, onDismissConsoleError]);
|
||||
|
||||
// Use external loading state if provided, otherwise use internal state
|
||||
const isLoading = externalIsLoading !== undefined ? externalIsLoading : internalIsLoading;
|
||||
|
||||
@@ -267,50 +300,24 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
setIsModelSelectorOpen(true);
|
||||
}, []);
|
||||
|
||||
// Function to suggest error fix
|
||||
// Clean alert hooks with proper interfaces
|
||||
const aiModelAlert = useAIModelErrorAlert(messages, _onNewChat, openModelSelector);
|
||||
const consoleAlert = useConsoleErrorAlert(messages, isBuildLoading, internalIsLoading);
|
||||
|
||||
// Scroll to bottom when alerts appear
|
||||
// Scroll to bottom when any error occurs (AI error or console error)
|
||||
useEffect(() => {
|
||||
if (aiModelAlert.hasError || consoleAlert.hasError) {
|
||||
setTimeout(() => {
|
||||
scrollToBottom();
|
||||
}, 50);
|
||||
if (displayError) {
|
||||
scrollToBottom();
|
||||
}
|
||||
}, [aiModelAlert.hasError, consoleAlert.hasError, scrollToBottom]);
|
||||
}, [displayError, scrollToBottom]);
|
||||
|
||||
// Check for autostart parameter and trigger AI generation
|
||||
useEffect(() => {
|
||||
if (autostartedRef.current) return;
|
||||
|
||||
const autostart = searchParams.get('autostart');
|
||||
const urlModel = searchParams.get('model');
|
||||
|
||||
if (autostart === 'true' && isConfigured) {
|
||||
// Use model from URL if available, otherwise use current selection
|
||||
const modelToUse = urlModel?.trim() || providerModel.trim();
|
||||
|
||||
if (modelToUse) {
|
||||
// Update provider model if it came from URL
|
||||
if (urlModel?.trim() && urlModel.trim() !== providerModel) {
|
||||
setProviderModel(urlModel.trim());
|
||||
}
|
||||
|
||||
// Clear the autostart and model parameters so they don't trigger again
|
||||
const newSearchParams = new URLSearchParams(searchParams);
|
||||
newSearchParams.delete('autostart');
|
||||
newSearchParams.delete('model');
|
||||
setSearchParams(newSearchParams, { replace: true });
|
||||
|
||||
// Start AI generation
|
||||
addRecentlyUsedModel(modelToUse);
|
||||
startGeneration(modelToUse);
|
||||
autostartedRef.current = true;
|
||||
}
|
||||
if (shouldAutostart && providerModel && isConfigured) {
|
||||
// Start AI generation
|
||||
addRecentlyUsedModel(providerModel);
|
||||
startGeneration(providerModel);
|
||||
autostartedRef.current = true;
|
||||
}
|
||||
}, [addRecentlyUsedModel, isConfigured, providerModel, searchParams, setSearchParams, startGeneration]);
|
||||
}, [addRecentlyUsedModel, isConfigured, providerModel, shouldAutostart, startGeneration]);
|
||||
|
||||
// Simple scroll event listener
|
||||
useEffect(() => {
|
||||
@@ -425,6 +432,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
// If configured but no model selected, don't proceed
|
||||
if (!providerModel.trim()) return;
|
||||
|
||||
setAIError(null);
|
||||
|
||||
const modelToUse = providerModel.trim();
|
||||
|
||||
// Build message content as text parts
|
||||
@@ -467,14 +476,9 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
// Add model to recently used when sending a message
|
||||
addRecentlyUsedModel(modelToUse);
|
||||
|
||||
try {
|
||||
// Send as text parts if we have multiple parts, otherwise send as string for simplicity
|
||||
const messageContent = contentParts.length === 1 ? contentParts[0].text : contentParts;
|
||||
await sendMessage(messageContent, modelToUse);
|
||||
} catch (error) {
|
||||
console.error('AI chat error:', error);
|
||||
// Error handling is done in the useAIChat hook and SessionManager
|
||||
}
|
||||
// Send as text parts if we have multiple parts, otherwise send as string for simplicity
|
||||
const messageContent = contentParts.length === 1 ? contentParts[0].text : contentParts;
|
||||
await sendMessage(messageContent, modelToUse);
|
||||
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage]);
|
||||
|
||||
const handleSend = useCallback(async () => {
|
||||
@@ -543,10 +547,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
}), [internalStartNewSession]);
|
||||
|
||||
const suggestErrorFix = useCallback(async (errorMessage: string) => {
|
||||
await send(errorMessage, attachedFiles);
|
||||
}, [send, attachedFiles]);
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col relative">
|
||||
|
||||
@@ -556,7 +556,9 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
{messages.length === 0 && !streamingMessage && !isLoading && (
|
||||
<div className="flex-1 flex items-center justify-center min-h-[400px]">
|
||||
<div className="text-center space-y-4 max-w-md mx-auto">
|
||||
<div className="text-6xl mb-6">🎭</div>
|
||||
<div className="mb-6">
|
||||
<ShakespeareLogo className="w-16 h-16 mx-auto" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-xl font-semibold mb-2 bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||
{t('welcomeToShakespeare')}
|
||||
@@ -639,27 +641,17 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* AI Model Alert */}
|
||||
{aiModelAlert.hasError && (
|
||||
<ChatIntervention
|
||||
message={aiModelAlert.errorMessage || ''}
|
||||
onDismiss={aiModelAlert.dismiss}
|
||||
action={aiModelAlert.action}
|
||||
{/* Error Alert (Console or AI) */}
|
||||
{displayError && (
|
||||
<Quilly
|
||||
error={displayError}
|
||||
onDismiss={handleErrorDismiss}
|
||||
onNewChat={onNewChat}
|
||||
onOpenModelSelector={openModelSelector}
|
||||
onRequestConsoleErrorHelp={handleConsoleErrorHelp}
|
||||
providerModel={providerModel}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Console Error Alert */}
|
||||
{consoleAlert.hasError && (
|
||||
<ChatIntervention
|
||||
message={`Console ${consoleAlert.errorCount === 1 ? 'error' : 'errors'} detected in your app. Would you like me to help fix ${consoleAlert.errorCount === 1 ? 'it' : 'them'}?`}
|
||||
onDismiss={consoleAlert.dismiss}
|
||||
action={{
|
||||
label: `Fix ${consoleAlert.errorCount === 1 ? 'error' : 'errors'}`,
|
||||
onClick: () => suggestErrorFix(consoleAlert.errorSummary || '')
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -3,12 +3,12 @@ import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useConsoleMessages, addConsoleMessage, clearConsoleMessages, type ConsoleMessage } from '@/hooks/useConsoleMessages';
|
||||
import { addConsoleMessage, getConsoleMessages, type ConsoleMessage } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||
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, X, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, CloudUpload } from 'lucide-react';
|
||||
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, CloudUpload, X, Terminal } from 'lucide-react';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
|
||||
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
|
||||
@@ -18,10 +18,16 @@ import {
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from '@/components/ui/popover';
|
||||
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';
|
||||
|
||||
// Get iframe domain from environment variable
|
||||
@@ -66,24 +72,24 @@ interface JSONRPCResponse {
|
||||
id: number;
|
||||
}
|
||||
|
||||
|
||||
export function PreviewPane({ projectId, activeTab, onToggleView, projectName, onFirstInteraction, isPreviewable = true }: PreviewPaneProps) {
|
||||
const { t } = useTranslation();
|
||||
const [selectedFile, setSelectedFile] = useState<string | null>(null);
|
||||
const [fileContent, setFileContent] = useState<string>('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [mobileCodeView, setMobileCodeView] = useState<'explorer' | 'editor'>('explorer');
|
||||
const [mobileCodeView, setMobileCodeView] = useState<'explorer' | 'editor' | 'terminal'>('explorer');
|
||||
const [desktopCodeView, setDesktopCodeView] = useState<'files' | 'terminal'>('files');
|
||||
const isMobile = useIsMobile();
|
||||
const [hasBuiltProject, setHasBuiltProject] = useState(false);
|
||||
const [currentPath, setCurrentPath] = useState('/');
|
||||
const [navigationHistory, setNavigationHistory] = useState<string[]>(['/']);
|
||||
const [historyIndex, setHistoryIndex] = useState(0);
|
||||
const [copiedMessageId, setCopiedMessageId] = useState<number | null>(null);
|
||||
|
||||
const [deployDialogOpen, setDeployDialogOpen] = useState(false);
|
||||
const iframeRef = useRef<HTMLIFrameElement>(null);
|
||||
const { fs } = useFS();
|
||||
const projectsManager = useProjectsManager();
|
||||
const { messages: consoleMessages } = useConsoleMessages();
|
||||
|
||||
const { mutate: buildProject, isPending: isBuildLoading } = useBuildProject(projectId);
|
||||
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
@@ -166,67 +172,23 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
}
|
||||
}, [projectId, projectsManager]);
|
||||
|
||||
const refreshIframe = useCallback(() => {
|
||||
// Legacy refresh function for build completion events
|
||||
const refreshIframeLegacy = useCallback(() => {
|
||||
if (iframeRef.current) {
|
||||
// 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 = `https://${projectId}.${IFRAME_DOMAIN}${currentPath}`;
|
||||
iframeRef.current.src = `https://${projectId}.${IFRAME_DOMAIN}/`;
|
||||
}
|
||||
}, 10);
|
||||
}
|
||||
}, [currentPath, projectId]);
|
||||
|
||||
const navigateToPath = useCallback((path: string) => {
|
||||
if (iframeRef.current) {
|
||||
const baseUrl = `https://${projectId}.${IFRAME_DOMAIN}`;
|
||||
const newUrl = `${baseUrl}${path}`;
|
||||
iframeRef.current.src = newUrl;
|
||||
setCurrentPath(path);
|
||||
|
||||
// Update navigation history
|
||||
const newHistory = navigationHistory.slice(0, historyIndex + 1);
|
||||
newHistory.push(path);
|
||||
setNavigationHistory(newHistory);
|
||||
setHistoryIndex(newHistory.length - 1);
|
||||
}
|
||||
}, [projectId, navigationHistory, historyIndex]);
|
||||
|
||||
const goBack = useCallback(() => {
|
||||
if (historyIndex > 0) {
|
||||
const newIndex = historyIndex - 1;
|
||||
const path = navigationHistory[newIndex];
|
||||
setHistoryIndex(newIndex);
|
||||
setCurrentPath(path);
|
||||
|
||||
if (iframeRef.current) {
|
||||
const baseUrl = `https://${projectId}.${IFRAME_DOMAIN}`;
|
||||
const newUrl = `${baseUrl}${path}`;
|
||||
iframeRef.current.src = newUrl;
|
||||
}
|
||||
}
|
||||
}, [historyIndex, navigationHistory, projectId]);
|
||||
|
||||
const goForward = useCallback(() => {
|
||||
if (historyIndex < navigationHistory.length - 1) {
|
||||
const newIndex = historyIndex + 1;
|
||||
const path = navigationHistory[newIndex];
|
||||
setHistoryIndex(newIndex);
|
||||
setCurrentPath(path);
|
||||
|
||||
if (iframeRef.current) {
|
||||
const baseUrl = `https://${projectId}.${IFRAME_DOMAIN}`;
|
||||
const newUrl = `${baseUrl}${path}`;
|
||||
iframeRef.current.src = newUrl;
|
||||
}
|
||||
}
|
||||
}, [historyIndex, navigationHistory, projectId]);
|
||||
}, [projectId]);
|
||||
|
||||
const sendResponse = useCallback((message: JSONRPCResponse) => {
|
||||
if (iframeRef.current?.contentWindow) {
|
||||
console.log(`Sending response to iframe:`, message);
|
||||
|
||||
const targetOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
|
||||
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
|
||||
}
|
||||
@@ -255,19 +217,98 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
normalizedLevel = params.level as ConsoleMessage['level'];
|
||||
}
|
||||
|
||||
// Add to global console messages
|
||||
// Add to console messages
|
||||
addConsoleMessage(normalizedLevel, params.message);
|
||||
|
||||
// Log to parent console for debugging with appropriate level
|
||||
console[normalizedLevel](`[IFRAME ${params.level.toUpperCase()}] ${params.message}`);
|
||||
}, []);
|
||||
|
||||
const handleUpdateNavigationState = useCallback((message: {
|
||||
jsonrpc: '2.0';
|
||||
method: 'updateNavigationState';
|
||||
params: {
|
||||
currentUrl: string;
|
||||
canGoBack: boolean;
|
||||
canGoForward: boolean;
|
||||
};
|
||||
}) => {
|
||||
const { params } = message;
|
||||
|
||||
try {
|
||||
// params.currentUrl is now just a semantic path (e.g., "/about", "/contact?param=value#section")
|
||||
const path = params.currentUrl;
|
||||
|
||||
setCurrentPath(path);
|
||||
|
||||
// Update navigation history if this is a new navigation
|
||||
// But only if it's different from current path (avoid duplicates)
|
||||
if (path !== navigationHistory[historyIndex]) {
|
||||
const newHistory = navigationHistory.slice(0, historyIndex + 1);
|
||||
newHistory.push(path);
|
||||
setNavigationHistory(newHistory);
|
||||
setHistoryIndex(newHistory.length - 1);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to handle navigation state:', params.currentUrl, error);
|
||||
}
|
||||
}, [historyIndex, navigationHistory]);
|
||||
|
||||
const sendNavigationCommand = useCallback((method: string, params?: Record<string, unknown>) => {
|
||||
if (iframeRef.current?.contentWindow) {
|
||||
const message = {
|
||||
jsonrpc: '2.0',
|
||||
method,
|
||||
params: params || {},
|
||||
id: Date.now()
|
||||
};
|
||||
const targetOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
|
||||
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
|
||||
}
|
||||
}, [projectId]);
|
||||
|
||||
const navigateIframe = useCallback((url: string) => {
|
||||
// Send semantic path directly (e.g., "/about", "/contact")
|
||||
// The iframe's NavigationHandler will handle this as semantic navigation
|
||||
sendNavigationCommand('navigate', { url });
|
||||
}, [sendNavigationCommand]);
|
||||
|
||||
const refreshIframe = useCallback(() => {
|
||||
sendNavigationCommand('refresh');
|
||||
}, [sendNavigationCommand]);
|
||||
|
||||
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;
|
||||
const { request: fetchRequest } = params;
|
||||
|
||||
console.log(`Preview iframe requesting: ${fetchRequest.url}`);
|
||||
|
||||
try {
|
||||
// Parse the URL and validate origin
|
||||
const url = new URL(fetchRequest.url);
|
||||
@@ -290,6 +331,9 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
const path = url.pathname;
|
||||
const filePath = path;
|
||||
|
||||
// Skip SPA fallback for static assets (files with extensions)
|
||||
const isStaticAsset = /\.[a-zA-Z0-9]+$/.test(path);
|
||||
|
||||
// SPA routing: try to serve the exact file first
|
||||
try {
|
||||
const bytes = await projectsManager.readFileBytes(projectId, 'dist' + filePath);
|
||||
@@ -310,11 +354,27 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
});
|
||||
return;
|
||||
} catch {
|
||||
// File not found, try SPA fallback to index.html
|
||||
console.log(`File not found: ${filePath}, trying index.html fallback`);
|
||||
|
||||
// For static assets, return 404 immediately
|
||||
if (isStaticAsset) {
|
||||
|
||||
sendResponse({
|
||||
jsonrpc: '2.0',
|
||||
result: {
|
||||
status: 404,
|
||||
statusText: 'Not Found',
|
||||
headers: {
|
||||
'Content-Type': 'text/plain',
|
||||
},
|
||||
body: encodeBase64(`Static asset not found: ${path}`),
|
||||
},
|
||||
id
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// SPA fallback: serve index.html for non-file requests
|
||||
// SPA fallback: serve index.html for non-file requests (SPA routing)
|
||||
try {
|
||||
const bytes = await projectsManager.readFileBytes(projectId, 'dist/index.html');
|
||||
console.log(`Serving index.html fallback for: ${path}`);
|
||||
@@ -334,8 +394,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
});
|
||||
} catch {
|
||||
// Even index.html doesn't exist
|
||||
console.log(`No files found, returning 404 for: ${path}`);
|
||||
|
||||
sendResponse({
|
||||
jsonrpc: '2.0',
|
||||
result: {
|
||||
@@ -379,12 +437,14 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
handleFetch(message);
|
||||
} else if (message.jsonrpc === '2.0' && message.method === 'console') {
|
||||
handleConsoleMessage(message);
|
||||
} else if (message.jsonrpc === '2.0' && message.method === 'updateNavigationState') {
|
||||
handleUpdateNavigationState(message);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('message', handleMessage);
|
||||
return () => window.removeEventListener('message', handleMessage);
|
||||
}, [handleFetch, handleConsoleMessage, projectId]);
|
||||
}, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, projectId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedFile) {
|
||||
@@ -392,11 +452,17 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
}
|
||||
}, [selectedFile, loadFileContent]);
|
||||
|
||||
// Reset selected file when projectId changes
|
||||
// Reset selected file and navigation history when projectId changes
|
||||
useEffect(() => {
|
||||
setSelectedFile(null);
|
||||
setFileContent('');
|
||||
setMobileCodeView('explorer');
|
||||
setDesktopCodeView('files');
|
||||
|
||||
// Reset navigation history and state
|
||||
setCurrentPath('/');
|
||||
setNavigationHistory(['/']);
|
||||
setHistoryIndex(0);
|
||||
}, [projectId]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -410,13 +476,13 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
console.log('Build completed for project, refreshing preview');
|
||||
// Check for built project and refresh iframe
|
||||
checkForBuiltProject();
|
||||
refreshIframe();
|
||||
refreshIframeLegacy();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('buildComplete', handleBuildComplete as EventListener);
|
||||
return () => window.removeEventListener('buildComplete', handleBuildComplete as EventListener);
|
||||
}, [projectId, checkForBuiltProject, refreshIframe]);
|
||||
}, [projectId, checkForBuiltProject, refreshIframeLegacy]);
|
||||
|
||||
const handleFileSelect = (filePath: string) => {
|
||||
setSelectedFile(filePath);
|
||||
@@ -431,104 +497,113 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
try {
|
||||
await fs.writeFile(`/projects/${projectId}/${selectedFile}`, content);
|
||||
setFileContent(content);
|
||||
|
||||
// Automatically trigger a rebuild after saving a file
|
||||
if (isPreviewable) {
|
||||
console.log('File saved, triggering rebuild...');
|
||||
handleBuildProject();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to save file:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const ConsoleDropdown = () => {
|
||||
const getLevelColor = (level: ConsoleMessage['level']) => {
|
||||
switch (level) {
|
||||
case 'error': return 'text-red-500';
|
||||
case 'warn': return 'text-yellow-500';
|
||||
case 'info': return 'text-blue-500';
|
||||
case 'debug': return 'text-gray-500';
|
||||
default: return 'text-gray-400';
|
||||
}
|
||||
};
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null);
|
||||
|
||||
const getLevelIcon = (level: ConsoleMessage['level']) => {
|
||||
switch (level) {
|
||||
case 'error': return '!';
|
||||
case 'warn': return '⚠';
|
||||
case 'info': return 'ℹ';
|
||||
case 'debug': return '🔍';
|
||||
default: return '•';
|
||||
}
|
||||
};
|
||||
|
||||
const clearConsole = () => {
|
||||
clearConsoleMessages();
|
||||
};
|
||||
|
||||
const copyMessageToClipboard = async (msg: ConsoleMessage) => {
|
||||
const copyMessageToClipboard = async (msg: ConsoleMessage, index: number) => {
|
||||
try {
|
||||
// Create a formatted string with all message details
|
||||
const formattedMessage = `[${msg.level.toUpperCase()}] ${msg.message}`;
|
||||
|
||||
await navigator.clipboard.writeText(formattedMessage);
|
||||
setCopiedMessageId(msg.id);
|
||||
|
||||
// Reset the copied state after 2 seconds
|
||||
setTimeout(() => {
|
||||
setCopiedMessageId(null);
|
||||
}, 2000);
|
||||
await navigator.clipboard.writeText(msg.message);
|
||||
setCopiedMessageIndex(index);
|
||||
setTimeout(() => setCopiedMessageIndex(null), 2000);
|
||||
} catch (error) {
|
||||
console.error('Failed to copy message to clipboard:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const consoleMessages = getConsoleMessages();
|
||||
const messageCount = consoleMessages.length;
|
||||
const hasErrors = consoleMessages.some(msg => msg.level === 'error');
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-8 w-8 p-0 relative">
|
||||
<Popover open={isOpen} onOpenChange={setIsOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0 relative"
|
||||
>
|
||||
<Bug className="h-4 w-4" />
|
||||
{consoleMessages.some(msg => msg.level === 'error') && (
|
||||
<span className="absolute bottom-0 left-0 h-2 w-2 bg-red-500 rounded-full"></span>
|
||||
{hasErrors && (
|
||||
<span className="absolute -top-1 -right-1 h-3 w-3 rounded-full border-2 border-background bg-red-500" />
|
||||
)}
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-96 max-w-96 max-h-96 overflow-x-hidden">
|
||||
<div className="flex items-center justify-between p-2 border-b">
|
||||
<span className="font-medium text-sm">Console Output ({consoleMessages.length})</span>
|
||||
<Button variant="ghost" size="sm" onClick={clearConsole}>
|
||||
<X className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
<ScrollArea className="h-80 w-full max-w-full overflow-x-hidden">
|
||||
<div className="space-y-1 p-2 w-full max-w-full overflow-x-hidden">
|
||||
{consoleMessages.length === 0 ? (
|
||||
<div className="text-center text-muted-foreground text-sm py-4">
|
||||
No console messages
|
||||
</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"
|
||||
sideOffset={4}
|
||||
>
|
||||
|
||||
{/* Messages */}
|
||||
<div className="h-[60vh] max-h-[512px] w-full bg-background text-foreground font-mono text-xs relative overflow-y-auto overflow-x-hidden [&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none]">
|
||||
<div className="py-2 px-1 space-y-0">
|
||||
{messageCount === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center py-12 text-center">
|
||||
<p className="text-sm text-muted-foreground font-medium">No console messages</p>
|
||||
<p className="text-xs text-muted-foreground mt-1">Messages from your project will appear here</p>
|
||||
</div>
|
||||
) : (
|
||||
consoleMessages.map((msg) => (
|
||||
consoleMessages.map((msg, index) => (
|
||||
<div
|
||||
key={msg.id}
|
||||
className={`text-xs font-mono p-2 rounded ${getLevelColor(msg.level)} bg-muted/50 group relative w-full overflow-hidden`}
|
||||
key={index}
|
||||
className="group relative py-0.5 px-1 hover:bg-muted/50 transition-colors duration-150 rounded cursor-pointer"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
copyMessageToClipboard(msg, index);
|
||||
}}
|
||||
>
|
||||
<div className="flex items-start justify-between w-full">
|
||||
<div className="whitespace-pre-wrap break-all flex-1 pr-2 overflow-x-hidden">{getLevelIcon(msg.level)} {msg.message}</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => copyMessageToClipboard(msg)}
|
||||
className="h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity duration-200 flex-shrink-0"
|
||||
>
|
||||
{copiedMessageId === msg.id ? (
|
||||
<Check className="h-3 w-3 text-green-500" />
|
||||
) : (
|
||||
<Copy className="h-3 w-3" />
|
||||
)}
|
||||
</Button>
|
||||
<div className={cn(
|
||||
"text-xs font-mono leading-tight whitespace-pre-wrap break-words",
|
||||
msg.level === 'error' ? "text-destructive" :
|
||||
msg.level === 'warn' ? "text-warning" :
|
||||
msg.level === 'info' ? "text-primary" :
|
||||
"text-muted-foreground"
|
||||
)}>
|
||||
{msg.message}
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
copyMessageToClipboard(msg, index);
|
||||
}}
|
||||
className="h-3 w-3 p-0 opacity-0 group-hover:opacity-100 transition-all duration-200 absolute right-1 top-1 hover:bg-muted/70 text-muted-foreground hover:text-foreground bg-background/80 rounded border"
|
||||
>
|
||||
{copiedMessageIndex === index ? (
|
||||
<Check className="h-2 w-2 text-success" />
|
||||
) : (
|
||||
<Copy className="h-2 w-2" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
|
||||
{/* Close button */}
|
||||
<button
|
||||
onClick={() => setIsOpen(false)}
|
||||
className="absolute top-2 right-2 h-8 w-8 p-0 bg-muted/50 hover:bg-muted/70 rounded-md z-10 flex items-center justify-center border"
|
||||
>
|
||||
<X className="h-5 w-5 text-muted-foreground" />
|
||||
</button>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -547,7 +622,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
<span className="sr-only">Open menu</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-48">
|
||||
<DropdownMenuContent align="end" className="w-48 sm:w-48">
|
||||
<DropdownMenuItem
|
||||
onClick={handleBuildProject}
|
||||
disabled={isBuildLoading}
|
||||
@@ -583,10 +658,10 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
<div className="h-12 flex items-center w-full">
|
||||
<BrowserAddressBar
|
||||
currentPath={currentPath}
|
||||
onNavigate={hasBuiltProject ? navigateToPath : undefined}
|
||||
onNavigate={hasBuiltProject ? navigateIframe : undefined}
|
||||
onRefresh={hasBuiltProject ? refreshIframe : undefined}
|
||||
onBack={hasBuiltProject ? goBack : undefined}
|
||||
onForward={hasBuiltProject ? goForward : undefined}
|
||||
onBack={hasBuiltProject ? goBackIframe : undefined}
|
||||
onForward={hasBuiltProject ? goForwardIframe : undefined}
|
||||
canGoBack={hasBuiltProject && historyIndex > 0}
|
||||
canGoForward={hasBuiltProject && historyIndex < navigationHistory.length - 1}
|
||||
extraContent={(
|
||||
@@ -613,7 +688,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
{hasBuiltProject ? (
|
||||
<iframe
|
||||
ref={iframeRef}
|
||||
src={`https://${projectId}.${IFRAME_DOMAIN}${currentPath}`}
|
||||
src={`https://${projectId}.${IFRAME_DOMAIN}/`}
|
||||
className="w-full h-full border-0"
|
||||
title="Project Preview"
|
||||
sandbox="allow-scripts allow-same-origin"
|
||||
@@ -663,18 +738,48 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
|
||||
<TabsContent value="code" className="h-full mt-0">
|
||||
{isMobile ? (
|
||||
<div className="h-full flex flex-col">
|
||||
<div className="h-full flex flex-col min-h-0">
|
||||
{mobileCodeView === 'explorer' ? (
|
||||
<ScrollArea className="flex-1">
|
||||
<ScrollBar orientation="horizontal" />
|
||||
<div className="min-w-max">
|
||||
<FileTree
|
||||
projectId={projectId}
|
||||
onFileSelect={handleFileSelect}
|
||||
selectedFile={selectedFile}
|
||||
/>
|
||||
<div className="flex-1 relative min-h-0">
|
||||
<ScrollArea className="h-full">
|
||||
<ScrollBar orientation="horizontal" />
|
||||
<div className="min-w-max">
|
||||
<FileTree
|
||||
projectId={projectId}
|
||||
onFileSelect={handleFileSelect}
|
||||
selectedFile={selectedFile}
|
||||
/>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
{/* Floating Terminal Button */}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setMobileCodeView('terminal')}
|
||||
className="fixed right-4 bottom-safe-nav z-20 h-12 w-12 p-0 rounded-full shadow-lg bg-background border-2"
|
||||
>
|
||||
<Terminal className="h-6 w-6" />
|
||||
</Button>
|
||||
</div>
|
||||
) : mobileCodeView === 'terminal' ? (
|
||||
<>
|
||||
<div className="h-12 px-3 flex items-center gap-2 bg-black text-purple-400 flex-shrink-0">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setMobileCodeView('explorer')}
|
||||
className="p-1 hover:bg-transparent hover:text-white"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<h3 className="font-semibold">
|
||||
Terminal
|
||||
</h3>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
<div className="flex-1 min-h-0">
|
||||
<TerminalComponent projectId={projectId} />
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="p-3 border-b bg-gradient-to-r from-primary/5 to-accent/5 flex items-center gap-2">
|
||||
@@ -737,50 +842,73 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
{t('backToPreview')}
|
||||
</Button>
|
||||
<div className="flex-1" />
|
||||
<GitStatusIndicator projectId={projectId} />
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setDesktopCodeView(desktopCodeView === 'terminal' ? 'files' : 'terminal')}
|
||||
className="gap-2 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<Terminal className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{/* Code view header without back button for non-previewable projects */}
|
||||
{!isMobile && !isPreviewable && (
|
||||
<div className="h-12 px-4 border-b flex items-center bg-gradient-to-r from-muted/20 to-background">
|
||||
<div className="flex-1" />
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setDesktopCodeView(desktopCodeView === 'terminal' ? 'files' : 'terminal')}
|
||||
className="gap-2 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<Terminal className="h-4 w-4" />
|
||||
</Button>
|
||||
<GitStatusIndicator projectId={projectId} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex-1 flex min-h-0">
|
||||
<div className="w-1/3 border-r flex flex-col">
|
||||
<ScrollArea className="flex-1">
|
||||
<ScrollBar orientation="horizontal" />
|
||||
<div className="min-w-max">
|
||||
<FileTree
|
||||
projectId={projectId}
|
||||
onFileSelect={handleFileSelect}
|
||||
selectedFile={selectedFile}
|
||||
/>
|
||||
{desktopCodeView === 'terminal' ? (
|
||||
<div className="flex-1">
|
||||
<TerminalComponent projectId={projectId} />
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="w-1/3 border-r flex flex-col">
|
||||
<ScrollArea className="flex-1">
|
||||
<ScrollBar orientation="horizontal" />
|
||||
<div className="min-w-max">
|
||||
<FileTree
|
||||
projectId={projectId}
|
||||
onFileSelect={handleFileSelect}
|
||||
selectedFile={selectedFile}
|
||||
/>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
<div className="flex-1">
|
||||
{selectedFile ? (
|
||||
<FileEditor
|
||||
filePath={selectedFile}
|
||||
content={fileContent}
|
||||
onSave={handleFileSave}
|
||||
isLoading={isLoading}
|
||||
projectId={projectId}
|
||||
/>
|
||||
) : (
|
||||
<div className="h-full flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<p className="text-muted-foreground">
|
||||
{t('selectFileFromExplorer')}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
{selectedFile ? (
|
||||
<FileEditor
|
||||
filePath={selectedFile}
|
||||
content={fileContent}
|
||||
onSave={handleFileSave}
|
||||
isLoading={isLoading}
|
||||
projectId={projectId}
|
||||
/>
|
||||
) : (
|
||||
<div className="h-full flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<p className="text-muted-foreground">
|
||||
{t('selectFileFromExplorer')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
export interface ShakespeareLogoProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function ShakespeareLogo({ className }: ShakespeareLogoProps) {
|
||||
return (
|
||||
<img
|
||||
src="/shakespeare.svg"
|
||||
alt="Shakespeare"
|
||||
className={className}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
import { useState, useRef, useEffect, useCallback } from 'react';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Copy } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { ShellTool } from '@/lib/tools/ShellTool';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
|
||||
interface TerminalProps {
|
||||
projectId: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
interface TerminalLine {
|
||||
id: string;
|
||||
type: 'input' | 'output' | 'error';
|
||||
content: string;
|
||||
timestamp: Date;
|
||||
}
|
||||
|
||||
export function Terminal({ projectId, className }: TerminalProps) {
|
||||
const [lines, setLines] = useState<TerminalLine[]>([]);
|
||||
const [currentInput, setCurrentInput] = useState('');
|
||||
const [isExecuting, setIsExecuting] = useState(false);
|
||||
const [commandHistory, setCommandHistory] = useState<string[]>([]);
|
||||
const [historyIndex, setHistoryIndex] = useState(-1);
|
||||
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const shellToolRef = useRef<ShellTool | null>(null);
|
||||
|
||||
const { fs } = useFS();
|
||||
const { git } = useGit();
|
||||
|
||||
// Initialize ShellTool
|
||||
useEffect(() => {
|
||||
shellToolRef.current = new ShellTool(fs, `/projects/${projectId}`, git);
|
||||
|
||||
// Add welcome message
|
||||
setLines([{
|
||||
id: Date.now().toString(),
|
||||
type: 'output',
|
||||
content: `Welcome to Shakespeare Terminal\nType 'help' to see available commands.`,
|
||||
timestamp: new Date()
|
||||
}]);
|
||||
}, [projectId, fs, git]);
|
||||
|
||||
// Auto-scroll to bottom when new lines are added or execution state changes
|
||||
useEffect(() => {
|
||||
if (scrollRef.current) {
|
||||
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
|
||||
}
|
||||
}, [lines, isExecuting]);
|
||||
|
||||
// Focus input when component mounts
|
||||
useEffect(() => {
|
||||
if (inputRef.current) {
|
||||
inputRef.current.focus();
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Refocus input after command execution
|
||||
useEffect(() => {
|
||||
if (!isExecuting && inputRef.current) {
|
||||
inputRef.current.focus();
|
||||
}
|
||||
}, [isExecuting]);
|
||||
|
||||
const addLine = useCallback((type: TerminalLine['type'], content: string) => {
|
||||
const newLine: TerminalLine = {
|
||||
id: Date.now().toString() + Math.random(),
|
||||
type,
|
||||
content,
|
||||
timestamp: new Date()
|
||||
};
|
||||
setLines(prev => [...prev, newLine]);
|
||||
}, []);
|
||||
|
||||
const executeCommand = useCallback(async (command: string) => {
|
||||
if (!shellToolRef.current || !command.trim()) return;
|
||||
|
||||
// Add command to history
|
||||
if (command.trim() && !commandHistory.includes(command.trim())) {
|
||||
setCommandHistory(prev => [...prev, command.trim()]);
|
||||
}
|
||||
setHistoryIndex(-1);
|
||||
|
||||
// Add input line
|
||||
addLine('input', command);
|
||||
|
||||
setIsExecuting(true);
|
||||
|
||||
try {
|
||||
// Handle special help command
|
||||
if (command.trim() === 'help') {
|
||||
const availableCommands = shellToolRef.current.getAvailableCommands();
|
||||
const helpText = `Available commands:\n\n${availableCommands.map(cmd =>
|
||||
`${cmd.name.padEnd(12)} - ${cmd.description}`
|
||||
).join('\n')}\n\nUse 'which <command>' for more details about a specific command.`;
|
||||
addLine('output', helpText);
|
||||
} else if (command.trim() === 'clear') {
|
||||
setLines([]);
|
||||
} else {
|
||||
const result = await shellToolRef.current.execute({ command });
|
||||
|
||||
// Add output
|
||||
if (result && result.trim()) {
|
||||
addLine('output', result);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
addLine('error', `Error: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
} finally {
|
||||
setIsExecuting(false);
|
||||
}
|
||||
}, [addLine, commandHistory]);
|
||||
|
||||
const handleSubmit = useCallback((e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (currentInput.trim() && !isExecuting) {
|
||||
executeCommand(currentInput);
|
||||
setCurrentInput('');
|
||||
}
|
||||
}, [currentInput, isExecuting, executeCommand]);
|
||||
|
||||
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
|
||||
if (e.key === 'ArrowUp') {
|
||||
e.preventDefault();
|
||||
if (commandHistory.length > 0) {
|
||||
const newIndex = historyIndex === -1 ? commandHistory.length - 1 : Math.max(0, historyIndex - 1);
|
||||
setHistoryIndex(newIndex);
|
||||
setCurrentInput(commandHistory[newIndex]);
|
||||
}
|
||||
} else if (e.key === 'ArrowDown') {
|
||||
e.preventDefault();
|
||||
if (historyIndex >= 0) {
|
||||
const newIndex = historyIndex + 1;
|
||||
if (newIndex >= commandHistory.length) {
|
||||
setHistoryIndex(-1);
|
||||
setCurrentInput('');
|
||||
} else {
|
||||
setHistoryIndex(newIndex);
|
||||
setCurrentInput(commandHistory[newIndex]);
|
||||
}
|
||||
}
|
||||
} else if (e.key === 'Tab') {
|
||||
e.preventDefault();
|
||||
// Basic tab completion could be added here
|
||||
}
|
||||
}, [commandHistory, historyIndex]);
|
||||
|
||||
const copyToClipboard = useCallback(async (content: string) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(content);
|
||||
} catch (error) {
|
||||
console.error('Failed to copy to clipboard:', error);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Focus input when clicking anywhere in the terminal
|
||||
const handleTerminalClick = useCallback(() => {
|
||||
if (inputRef.current) {
|
||||
inputRef.current.focus();
|
||||
}
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className={cn("h-full flex flex-col bg-black text-slate-300 font-mono text-sm", className)}>
|
||||
{/* Terminal Content */}
|
||||
<div className="flex-1 flex flex-col min-h-0" onClick={handleTerminalClick}>
|
||||
<ScrollArea className="flex-1" ref={scrollRef}>
|
||||
<div className="p-2 space-y-1">
|
||||
{lines.map((line) => (
|
||||
<div
|
||||
key={line.id}
|
||||
className={cn(
|
||||
"group relative",
|
||||
line.type === 'input' && "text-white",
|
||||
line.type === 'error' && "text-red-400",
|
||||
line.type === 'output' && "text-slate-300"
|
||||
)}
|
||||
>
|
||||
<pre className="whitespace-pre-wrap break-words font-mono leading-relaxed">
|
||||
{line.type === 'input' ? (
|
||||
<span className="text-purple-400 font-mono whitespace-nowrap">
|
||||
${' '}
|
||||
</span>
|
||||
) : null}
|
||||
{line.content}
|
||||
</pre>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
copyToClipboard(line.content);
|
||||
}}
|
||||
className="absolute right-0 top-0 h-4 w-4 p-0 opacity-0 group-hover:opacity-100 transition-opacity text-gray-500 hover:text-white hover:bg-gray-700"
|
||||
>
|
||||
<Copy className="h-2 w-2" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* Current Command Input - inline with content */}
|
||||
{!isExecuting && (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-purple-400 font-mono whitespace-nowrap">
|
||||
$
|
||||
</span>
|
||||
<form onSubmit={handleSubmit} className="flex-1 relative">
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="text"
|
||||
value={currentInput}
|
||||
onChange={(e) => setCurrentInput(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
disabled={isExecuting}
|
||||
className="w-full bg-transparent border-none outline-none text-white font-mono placeholder-gray-500 caret-white leading-relaxed"
|
||||
placeholder=""
|
||||
autoComplete="off"
|
||||
spellCheck="false"
|
||||
autoCapitalize="off"
|
||||
autoCorrect="off"
|
||||
/>
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Cloud } from 'lucide-react';
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { Cloud, Upload } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
@@ -32,6 +32,7 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
|
||||
}) => {
|
||||
// Removed step state - we only have one step now
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isFileLoading, setIsFileLoading] = useState(false);
|
||||
const [nsec, setNsec] = useState('');
|
||||
const [bunkerUri, setBunkerUri] = useState('');
|
||||
const [activeTab, setActiveTab] = useState<'nsec' | 'bunker'>('nsec');
|
||||
@@ -39,7 +40,9 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
|
||||
nsec?: string;
|
||||
bunker?: string;
|
||||
extension?: string;
|
||||
file?: string;
|
||||
}>({});
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const login = useLoginActions();
|
||||
|
||||
@@ -47,10 +50,15 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
setIsLoading(false);
|
||||
setIsFileLoading(false);
|
||||
setNsec('');
|
||||
setBunkerUri('');
|
||||
setActiveTab('nsec');
|
||||
setErrors({});
|
||||
// Reset file input
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = '';
|
||||
}
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
@@ -86,20 +94,7 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
|
||||
setErrors(prev => ({ ...prev, nsec: 'Invalid secret key format. Must be a valid nsec starting with nsec1.' }));
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setErrors({});
|
||||
|
||||
setTimeout(() => {
|
||||
try {
|
||||
login.nsec(nsec);
|
||||
onLogin();
|
||||
onClose();
|
||||
} catch {
|
||||
setErrors({ nsec: "Failed to login with this key. Please check that it's correct." });
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, 50);
|
||||
executeLogin(nsec);
|
||||
};
|
||||
|
||||
const handleBunkerLogin = async () => {
|
||||
@@ -131,6 +126,52 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
|
||||
}
|
||||
};
|
||||
|
||||
const executeLogin = (key: string) => {
|
||||
setIsLoading(true);
|
||||
setErrors({});
|
||||
|
||||
// Use a timeout to allow the UI to update before the synchronous login call
|
||||
setTimeout(() => {
|
||||
try {
|
||||
login.nsec(key);
|
||||
onLogin();
|
||||
onClose();
|
||||
} catch {
|
||||
setErrors({ nsec: "Failed to login with this key. Please check that it's correct." });
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, 50);
|
||||
};
|
||||
|
||||
const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
setIsFileLoading(true);
|
||||
setErrors({});
|
||||
|
||||
const reader = new FileReader();
|
||||
reader.onload = (event) => {
|
||||
setIsFileLoading(false);
|
||||
const content = event.target?.result as string;
|
||||
if (content) {
|
||||
const trimmedContent = content.trim();
|
||||
if (validateNsec(trimmedContent)) {
|
||||
executeLogin(trimmedContent);
|
||||
} else {
|
||||
setErrors({ file: 'File does not contain a valid secret key.' });
|
||||
}
|
||||
} else {
|
||||
setErrors({ file: 'Could not read file content.' });
|
||||
}
|
||||
};
|
||||
reader.onerror = () => {
|
||||
setIsFileLoading(false);
|
||||
setErrors({ file: 'Failed to read file.' });
|
||||
};
|
||||
reader.readAsText(file);
|
||||
};
|
||||
|
||||
const handleSignupClick = () => {
|
||||
onClose();
|
||||
if (onSignup) {
|
||||
@@ -202,14 +243,37 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Button
|
||||
size="lg"
|
||||
onClick={handleKeyLogin}
|
||||
disabled={isLoading || !nsec.trim()}
|
||||
className="w-full"
|
||||
>
|
||||
{isLoading ? 'Verifying...' : 'Add Key'}
|
||||
</Button>
|
||||
<div className="flex space-x-2">
|
||||
<Button
|
||||
size="lg"
|
||||
onClick={handleKeyLogin}
|
||||
disabled={isLoading || !nsec.trim()}
|
||||
className="flex-1"
|
||||
>
|
||||
{isLoading ? 'Verifying...' : 'Add Key'}
|
||||
</Button>
|
||||
|
||||
<input
|
||||
type="file"
|
||||
accept=".txt"
|
||||
className="hidden"
|
||||
ref={fileInputRef}
|
||||
onChange={handleFileUpload}
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="lg"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
disabled={isLoading || isFileLoading}
|
||||
className="px-3"
|
||||
>
|
||||
<Upload className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{errors.file && (
|
||||
<p className="text-sm text-red-500 text-center">{errors.file}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -81,4 +81,21 @@ describe('BrowserAddressBar', () => {
|
||||
expect(onForward).toHaveBeenCalled();
|
||||
expect(onRefresh).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('updates input value when currentPath prop changes', () => {
|
||||
const { rerender } = render(<BrowserAddressBar currentPath="/" />);
|
||||
|
||||
const input = screen.getByPlaceholderText('Enter path (e.g., /, /about)');
|
||||
expect(input).toHaveValue('/');
|
||||
|
||||
// Re-render with new currentPath
|
||||
rerender(<BrowserAddressBar currentPath="/about" />);
|
||||
|
||||
expect(input).toHaveValue('/about');
|
||||
|
||||
// Re-render with another path
|
||||
rerender(<BrowserAddressBar currentPath="/contact" />);
|
||||
|
||||
expect(input).toHaveValue('/contact');
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState } from 'react';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { ChevronLeft, ChevronRight, RefreshCw } from 'lucide-react';
|
||||
@@ -30,6 +30,11 @@ export function BrowserAddressBar({
|
||||
}: BrowserAddressBarProps) {
|
||||
const [inputValue, setInputValue] = useState(currentPath);
|
||||
|
||||
// Update input value when currentPath changes (e.g., when iframe navigates)
|
||||
useEffect(() => {
|
||||
setInputValue(currentPath);
|
||||
}, [currentPath]);
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!onNavigate) return;
|
||||
|
||||
@@ -9,10 +9,10 @@ export const buttonVariants = cva(
|
||||
destructive:
|
||||
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
|
||||
outline:
|
||||
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
|
||||
"border border-input bg-background hover:bg-border/20 dark:hover:bg-border/50",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
ghost: "hover:bg-accent hover:text-accent-foreground",
|
||||
ghost: "",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
|
||||
+25
-7
@@ -12,6 +12,7 @@ interface UseAIChatSessionOptions {
|
||||
customTools?: Record<string, Tool<unknown>>;
|
||||
maxSteps?: number;
|
||||
onUpdateMetadata?: (title: string, description: string) => void;
|
||||
onAIError?: (error: Error) => void;
|
||||
}
|
||||
|
||||
interface StreamingMessage {
|
||||
@@ -30,7 +31,8 @@ export function useAIChat({
|
||||
tools = {},
|
||||
customTools = {},
|
||||
maxSteps = 50,
|
||||
onUpdateMetadata
|
||||
onUpdateMetadata,
|
||||
onAIError
|
||||
}: UseAIChatSessionOptions) {
|
||||
const sessionManager = useSessionManager();
|
||||
const { isConfigured } = useAISettings();
|
||||
@@ -113,14 +115,30 @@ export function useAIChat({
|
||||
|
||||
// Actions
|
||||
const sendMessage = useCallback(async (content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText>, providerModel: string) => {
|
||||
await initSession();
|
||||
await sessionManager.sendMessage(projectId, content, providerModel);
|
||||
}, [projectId, sessionManager, initSession]);
|
||||
try {
|
||||
await initSession();
|
||||
await sessionManager.sendMessage(projectId, content, providerModel);
|
||||
} catch (error) {
|
||||
if (onAIError && error instanceof Error) {
|
||||
onAIError(error);
|
||||
} else {
|
||||
console.error('AI chat error:', error);
|
||||
}
|
||||
}
|
||||
}, [projectId, sessionManager, initSession, onAIError]);
|
||||
|
||||
const startGeneration = useCallback(async (providerModel: string) => {
|
||||
await initSession();
|
||||
await sessionManager.startGeneration(projectId, providerModel);
|
||||
}, [projectId, sessionManager, initSession]);
|
||||
try {
|
||||
await initSession();
|
||||
await sessionManager.startGeneration(projectId, providerModel);
|
||||
} catch (error) {
|
||||
if (onAIError && error instanceof Error) {
|
||||
onAIError(error);
|
||||
} else {
|
||||
console.error('AI chat error:', error);
|
||||
}
|
||||
}
|
||||
}, [projectId, sessionManager, initSession, onAIError]);
|
||||
|
||||
const stopGeneration = useCallback(() => {
|
||||
sessionManager.stopGeneration(projectId);
|
||||
|
||||
@@ -4,34 +4,18 @@ import { createAIClient } from '@/lib/ai-client';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
// Zod schemas for the two possible response formats
|
||||
const creditsResponseV1Schema = z.object({
|
||||
const creditsResponseSchema = z.object({
|
||||
object: z.literal('credits'),
|
||||
amount: z.number(),
|
||||
});
|
||||
|
||||
const creditsResponseV2Schema = z.object({
|
||||
data: z.object({
|
||||
total_credits: z.number(),
|
||||
total_usage: z.number(),
|
||||
}),
|
||||
});
|
||||
|
||||
// Union schema to handle both response formats
|
||||
const creditsResponseSchema = z.union([creditsResponseV1Schema, creditsResponseV2Schema]);
|
||||
|
||||
// Normalized response type (always in V1 format)
|
||||
export interface CreditsResponse {
|
||||
object: 'credits';
|
||||
amount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Custom hook to fetch AI provider credits
|
||||
* @param providerId - The ID of the AI provider
|
||||
* @param connection - The AI connection configuration
|
||||
* @returns Query result with credits information
|
||||
*/
|
||||
/** Custom hook to fetch AI provider credits */
|
||||
export function useAICredits(provider: AIProvider) {
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
@@ -41,20 +25,7 @@ export function useAICredits(provider: AIProvider) {
|
||||
try {
|
||||
const ai = createAIClient(provider, user);
|
||||
const data = await ai.get('/credits');
|
||||
|
||||
// Validate and normalize the response
|
||||
const parsed = creditsResponseSchema.parse(data);
|
||||
|
||||
// Convert V2 format to V1 format if needed
|
||||
if ('data' in parsed) {
|
||||
return {
|
||||
object: 'credits',
|
||||
amount: parsed.data.total_credits - parsed.data.total_usage,
|
||||
};
|
||||
}
|
||||
|
||||
// Already in V1 format
|
||||
return parsed;
|
||||
return creditsResponseSchema.parse(data);
|
||||
} catch (error) {
|
||||
if (error instanceof Error && !error.message.includes('Connection error')) {
|
||||
console.error('Error fetching AI credits:', error);
|
||||
@@ -65,6 +36,6 @@ export function useAICredits(provider: AIProvider) {
|
||||
retry: false, // Don't retry as not all providers support this endpoint
|
||||
refetchOnWindowFocus: false,
|
||||
staleTime: 5 * 60 * 1000, // 5 minutes
|
||||
enabled: provider.id === 'shakespeare' && !!user,
|
||||
enabled: !!provider.nostr && !!user,
|
||||
});
|
||||
}
|
||||
@@ -80,7 +80,7 @@ export function useAIProjectId({ onError }: UseAIProjectIdOptions = {}) {
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Failed to generate project ID';
|
||||
onError?.(errorMessage);
|
||||
throw new Error(errorMessage);
|
||||
throw error;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
|
||||
export interface ConsoleMessage {
|
||||
id: number;
|
||||
level: 'log' | 'warn' | 'error' | 'info' | 'debug';
|
||||
message: string;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
// Global state for console messages
|
||||
let globalConsoleMessages: ConsoleMessage[] = [];
|
||||
const listeners: Set<(messages: ConsoleMessage[]) => void> = new Set();
|
||||
|
||||
const notifyListeners = () => {
|
||||
listeners.forEach(listener => listener([...globalConsoleMessages]));
|
||||
};
|
||||
|
||||
export const useConsoleMessages = () => {
|
||||
const [messages, setMessages] = useState<ConsoleMessage[]>(globalConsoleMessages);
|
||||
|
||||
const addMessage = useCallback((level: ConsoleMessage['level'], message: string) => {
|
||||
const newMessage: ConsoleMessage = {
|
||||
id: Date.now() + Math.random(), // Ensure uniqueness
|
||||
level,
|
||||
message,
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
|
||||
globalConsoleMessages = [...globalConsoleMessages, newMessage];
|
||||
notifyListeners();
|
||||
}, []);
|
||||
|
||||
const clearMessages = useCallback(() => {
|
||||
globalConsoleMessages = [];
|
||||
notifyListeners();
|
||||
}, []);
|
||||
|
||||
const getErrorsSince = useCallback((timestamp: number) => {
|
||||
return globalConsoleMessages.filter(
|
||||
msg => msg.level === 'error' && msg.timestamp > timestamp
|
||||
);
|
||||
}, []);
|
||||
|
||||
// Subscribe to global state changes
|
||||
useEffect(() => {
|
||||
const listener = (newMessages: ConsoleMessage[]) => {
|
||||
setMessages(newMessages);
|
||||
};
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return {
|
||||
messages,
|
||||
addMessage,
|
||||
clearMessages,
|
||||
getErrorsSince,
|
||||
};
|
||||
};
|
||||
|
||||
// Export functions for external use (like PreviewPane)
|
||||
export const addConsoleMessage = (level: ConsoleMessage['level'], message: string) => {
|
||||
const newMessage: ConsoleMessage = {
|
||||
id: Date.now() + Math.random(),
|
||||
level,
|
||||
message,
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
|
||||
globalConsoleMessages = [...globalConsoleMessages, newMessage];
|
||||
notifyListeners();
|
||||
};
|
||||
|
||||
export const clearConsoleMessages = () => {
|
||||
globalConsoleMessages = [];
|
||||
notifyListeners();
|
||||
};
|
||||
@@ -1,153 +0,0 @@
|
||||
import { useState, useCallback, useMemo } from 'react';
|
||||
import type { AIMessage } from '@/lib/SessionManager';
|
||||
import { useConsoleMessages } from './useConsoleMessages';
|
||||
|
||||
export interface ConsoleErrorAlert {
|
||||
hasError: boolean;
|
||||
errorSummary: string | null;
|
||||
errorCount: number;
|
||||
dismiss: () => void;
|
||||
}
|
||||
|
||||
export const useConsoleErrorAlert = (
|
||||
aiMessages: AIMessage[],
|
||||
isBuilding?: boolean,
|
||||
isLoading?: boolean
|
||||
): ConsoleErrorAlert => {
|
||||
const { messages } = useConsoleMessages();
|
||||
const [dismissedErrorSummary, setDismissedErrorSummary] = useState<string>('');
|
||||
|
||||
const { hasError, errorSummary, errorCount } = useMemo(() => {
|
||||
// Don't show alerts while building or AI is working
|
||||
if (isBuilding || isLoading) {
|
||||
return { hasError: false, errorSummary: null, errorCount: 0 };
|
||||
}
|
||||
|
||||
// Find the timestamp of the last AI assistant message
|
||||
// Since AIMessage doesn't have timestamps, we'll use a different approach:
|
||||
// Only show errors if there are any errors at all and no recent user activity
|
||||
const lastMessage = aiMessages[aiMessages.length - 1];
|
||||
const isLastMessageFromAssistant = lastMessage?.role === 'assistant';
|
||||
|
||||
// Only show console errors if the last message was from assistant (AI just responded)
|
||||
if (!isLastMessageFromAssistant) {
|
||||
return { hasError: false, errorSummary: null, errorCount: 0 };
|
||||
}
|
||||
|
||||
// Get recent errors (last 10 seconds worth to catch errors from recent AI actions)
|
||||
const recentTimeThreshold = Date.now() - (10 * 1000); // 10 seconds ago
|
||||
const recentErrors = messages.filter(msg =>
|
||||
msg.level === 'error' &&
|
||||
msg.timestamp > recentTimeThreshold
|
||||
);
|
||||
|
||||
if (recentErrors.length === 0) {
|
||||
return { hasError: false, errorSummary: null, errorCount: 0 };
|
||||
}
|
||||
|
||||
// Just return the raw error messages, no formatting
|
||||
const summary = recentErrors.slice(-3).map(e => e.message).join('\n');
|
||||
|
||||
return {
|
||||
hasError: dismissedErrorSummary !== summary,
|
||||
errorSummary: summary,
|
||||
errorCount: recentErrors.length
|
||||
};
|
||||
}, [messages, dismissedErrorSummary, aiMessages, isBuilding, isLoading]);
|
||||
|
||||
const dismiss = useCallback(() => {
|
||||
if (errorSummary) {
|
||||
setDismissedErrorSummary(errorSummary);
|
||||
}
|
||||
}, [errorSummary]);
|
||||
|
||||
return {
|
||||
hasError,
|
||||
errorSummary,
|
||||
errorCount,
|
||||
dismiss
|
||||
};
|
||||
};
|
||||
|
||||
export interface AIModelErrorAlert {
|
||||
hasError: boolean;
|
||||
errorMessage: string | null;
|
||||
errorType: 'warn' | 'error' | null;
|
||||
action?: { label: string; onClick: () => void };
|
||||
dismiss: () => void;
|
||||
}
|
||||
|
||||
export const useAIModelErrorAlert = (
|
||||
messages: AIMessage[],
|
||||
onNewChat?: () => void,
|
||||
onChangeModel?: () => void
|
||||
): AIModelErrorAlert => {
|
||||
const [dismissedAlertKey, setDismissedAlertKey] = useState<string>('');
|
||||
|
||||
const { hasError, errorMessage, errorType, action } = useMemo(() => {
|
||||
const lastMessage = messages[messages.length - 1];
|
||||
|
||||
// Only show AI model alerts if the last message is from the assistant
|
||||
// This ensures we don't show stale alerts when user continues the conversation
|
||||
if (!lastMessage || lastMessage.role !== 'assistant') {
|
||||
return { hasError: false, errorMessage: null, errorType: null, action: undefined };
|
||||
}
|
||||
|
||||
const content = typeof lastMessage.content === 'string' ? lastMessage.content : '';
|
||||
|
||||
// Define error patterns with actions
|
||||
const errorPatterns = [
|
||||
{
|
||||
test: (content: string) => /AI service error: 422/.test(content) || /Provider returned error/.test(content),
|
||||
type: 'error' as const,
|
||||
message: 'The AI model encountered an issue. Try switching to a different model or starting a new chat.',
|
||||
action: onChangeModel ? { label: 'Change model', onClick: onChangeModel } : undefined
|
||||
},
|
||||
{
|
||||
test: (content: string) => /maximum context length is \d+ tokens/.test(content) || /context length/.test(content),
|
||||
type: 'warn' as const,
|
||||
message: 'Your conversation is too long for this model. Try starting a new chat or switching to a model with a larger context window.',
|
||||
action: onNewChat ? { label: 'New chat', onClick: onNewChat } : undefined
|
||||
},
|
||||
{
|
||||
test: (content: string) => /rate limit/i.test(content) || /too many requests/i.test(content),
|
||||
type: 'warn' as const,
|
||||
message: 'You\'re sending requests too quickly. Please wait a moment before trying again.'
|
||||
}
|
||||
];
|
||||
|
||||
for (const pattern of errorPatterns) {
|
||||
if (pattern.test(content)) {
|
||||
const messageContent = typeof lastMessage.content === 'string' ? lastMessage.content : JSON.stringify(lastMessage.content);
|
||||
const alertKey = `${pattern.message}_${messageContent.slice(0, 50)}_${Date.now()}`;
|
||||
|
||||
return {
|
||||
hasError: dismissedAlertKey !== alertKey,
|
||||
errorMessage: pattern.message,
|
||||
errorType: pattern.type,
|
||||
action: pattern.action,
|
||||
alertKey
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return { hasError: false, errorMessage: null, errorType: null, action: undefined };
|
||||
}, [messages, dismissedAlertKey, onNewChat, onChangeModel]);
|
||||
|
||||
const dismiss = useCallback(() => {
|
||||
const lastMessage = messages[messages.length - 1];
|
||||
if (errorMessage && lastMessage) {
|
||||
const messageContent = typeof lastMessage.content === 'string' ? lastMessage.content : JSON.stringify(lastMessage.content);
|
||||
const alertKey = `${errorMessage}_${messageContent.slice(0, 50)}_${Date.now()}`;
|
||||
setDismissedAlertKey(alertKey);
|
||||
}
|
||||
}, [errorMessage, messages]);
|
||||
|
||||
return {
|
||||
hasError,
|
||||
errorMessage,
|
||||
errorType,
|
||||
action,
|
||||
dismiss
|
||||
};
|
||||
};
|
||||
+37
-4
@@ -110,11 +110,13 @@
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border;
|
||||
border-color: hsl(var(--border));
|
||||
}
|
||||
|
||||
body {
|
||||
@apply bg-background text-foreground font-sans;
|
||||
background-color: hsl(var(--background));
|
||||
color: hsl(var(--foreground));
|
||||
font-family: 'Inter Variable', 'Inter', 'system-ui', 'sans-serif';
|
||||
font-feature-settings: "rlig" 1, "calt" 1;
|
||||
}
|
||||
|
||||
@@ -138,8 +140,10 @@
|
||||
}
|
||||
|
||||
/* GitHub-style focus rings */
|
||||
.focus-ring {
|
||||
@apply focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2;
|
||||
.focus-ring:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 2px hsl(var(--ring));
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
/* Smooth transitions for theme switching */
|
||||
@@ -247,6 +251,35 @@
|
||||
max-height: 100dvh;
|
||||
}
|
||||
|
||||
/* iOS Safe Area Support */
|
||||
.safe-area-inset-bottom {
|
||||
padding-bottom: env(safe-area-inset-bottom);
|
||||
}
|
||||
|
||||
.safe-area-inset-top {
|
||||
padding-top: env(safe-area-inset-top);
|
||||
}
|
||||
|
||||
.bottom-safe-nav {
|
||||
bottom: calc(env(safe-area-inset-bottom) + 3.75rem);
|
||||
}
|
||||
|
||||
/* 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;
|
||||
}
|
||||
|
||||
@@ -98,8 +98,6 @@ invalid json line
|
||||
it('should create history directory if it does not exist', async () => {
|
||||
// Mock historyDirExists to return false initially
|
||||
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(false);
|
||||
// Mock setupAiHistoryDir
|
||||
vi.spyOn(dotAI, 'setupAiHistoryDir').mockResolvedValue();
|
||||
|
||||
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
|
||||
{ role: 'user', content: 'Hello' }
|
||||
@@ -107,8 +105,8 @@ invalid json line
|
||||
|
||||
await dotAI.setHistory('test-session', messages);
|
||||
|
||||
// Verify setupAiHistoryDir was called
|
||||
expect(dotAI.setupAiHistoryDir).toHaveBeenCalled();
|
||||
// Verify mkdir was called with recursive option
|
||||
expect(mockFS.mkdir).toHaveBeenCalledWith('/test-project/.git/ai/history', { recursive: true });
|
||||
});
|
||||
|
||||
it('should write messages as JSONL format', async () => {
|
||||
@@ -124,7 +122,7 @@ invalid json line
|
||||
|
||||
// Verify writeFile was called with correct content
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||
'/test-project/.ai/history/test-session.jsonl',
|
||||
'/test-project/.git/ai/history/test-session.jsonl',
|
||||
'{"role":"user","content":"Hello"}\n{"role":"assistant","content":"Hi there!"}\n'
|
||||
);
|
||||
});
|
||||
@@ -137,7 +135,7 @@ invalid json line
|
||||
|
||||
// Verify writeFile was called with empty content
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||
'/test-project/.ai/history/test-session.jsonl',
|
||||
'/test-project/.git/ai/history/test-session.jsonl',
|
||||
''
|
||||
);
|
||||
});
|
||||
|
||||
+16
-86
@@ -2,7 +2,7 @@ import { join } from "path-browserify";
|
||||
import type OpenAI from "openai";
|
||||
import type { JSRuntimeFS } from "./JSRuntime";
|
||||
|
||||
/** AI message history manager and .ai directory utilities */
|
||||
/** AI message history manager and .git/ai directory utilities */
|
||||
export class DotAI {
|
||||
readonly fs: JSRuntimeFS;
|
||||
readonly historyDir: string;
|
||||
@@ -11,7 +11,7 @@ export class DotAI {
|
||||
constructor(fs: JSRuntimeFS, workingDir: string = "/") {
|
||||
this.fs = fs;
|
||||
this.workingDir = workingDir;
|
||||
this.historyDir = join(workingDir, ".ai", "history");
|
||||
this.historyDir = join(workingDir, ".git", "ai", "history");
|
||||
}
|
||||
|
||||
/** Generate a unique session name based on the current date and time */
|
||||
@@ -31,8 +31,6 @@ export class DotAI {
|
||||
return filename;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/** Check if the history directory exists */
|
||||
async historyDirExists(): Promise<boolean> {
|
||||
try {
|
||||
@@ -51,10 +49,9 @@ export class DotAI {
|
||||
// Validate messages before saving
|
||||
this.validateMessages(messages);
|
||||
|
||||
// Always create the .ai directory and write session history
|
||||
// Create the history directory if it doesn't exist
|
||||
if (!(await this.historyDirExists())) {
|
||||
await this.setupAiHistoryDir();
|
||||
await this.fs.mkdir(this.historyDir, { recursive: true });
|
||||
}
|
||||
|
||||
const sessionFile = join(this.historyDir, sessionName + ".jsonl");
|
||||
@@ -122,29 +119,11 @@ export class DotAI {
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates .ai/history directory and ensures .ai/ is gitignored at the project root.
|
||||
*/
|
||||
async setupAiHistoryDir(): Promise<void> {
|
||||
const aiHistoryDir = join(this.workingDir, ".ai", "history");
|
||||
|
||||
try {
|
||||
// Create .ai/history directory
|
||||
await this.fs.mkdir(aiHistoryDir, { recursive: true });
|
||||
|
||||
// Ensure .ai/ is gitignored at the project root
|
||||
await this.ensureAiGitignored();
|
||||
} catch (error) {
|
||||
// Log error but don't fail the main operation
|
||||
console.warn(`Failed to setup .ai/history directory: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the model from .ai/MODEL file
|
||||
* Read the model from .git/ai/MODEL file
|
||||
*/
|
||||
async readAiModel(): Promise<string | undefined> {
|
||||
try {
|
||||
const modelPath = join(this.workingDir, ".ai", "MODEL");
|
||||
const modelPath = join(this.workingDir, ".git", "ai", "MODEL");
|
||||
const content = await this.fs.readFile(modelPath, "utf8");
|
||||
return content.trim();
|
||||
} catch {
|
||||
@@ -153,32 +132,29 @@ export class DotAI {
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the model to .ai/MODEL file
|
||||
* Write the model to .git/ai/MODEL file
|
||||
*/
|
||||
async writeAiModel(model: string): Promise<void> {
|
||||
const aiDir = join(this.workingDir, ".ai");
|
||||
const aiDir = join(this.workingDir, ".git", "ai");
|
||||
const modelPath = join(aiDir, "MODEL");
|
||||
|
||||
try {
|
||||
// Ensure .ai directory exists
|
||||
// Ensure .git/ai directory exists
|
||||
await this.fs.mkdir(aiDir, { recursive: true });
|
||||
|
||||
// Ensure .ai/ is gitignored
|
||||
await this.ensureAiGitignored();
|
||||
|
||||
// Write the model
|
||||
await this.fs.writeFile(modelPath, model.trim() + "\n");
|
||||
} catch (error) {
|
||||
console.warn(`Failed to write .ai/MODEL file: ${error}`);
|
||||
console.warn(`Failed to write .git/ai/MODEL file: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read parameters from .ai/PARAMETERS file
|
||||
* Read parameters from .git/ai/PARAMETERS file
|
||||
*/
|
||||
async readAiParameters(): Promise<Record<string, string>> {
|
||||
try {
|
||||
const parametersPath = join(this.workingDir, ".ai", "PARAMETERS");
|
||||
const parametersPath = join(this.workingDir, ".git", "ai", "PARAMETERS");
|
||||
const content = await this.fs.readFile(parametersPath, "utf8");
|
||||
|
||||
const parameters: Record<string, string> = {};
|
||||
@@ -203,19 +179,16 @@ export class DotAI {
|
||||
}
|
||||
|
||||
/**
|
||||
* Write parameters to .ai/PARAMETERS file
|
||||
* Write parameters to .git/ai/PARAMETERS file
|
||||
*/
|
||||
async writeAiParameters(parameters: Record<string, string>): Promise<void> {
|
||||
const aiDir = join(this.workingDir, ".ai");
|
||||
const aiDir = join(this.workingDir, ".git", "ai");
|
||||
const parametersPath = join(aiDir, "PARAMETERS");
|
||||
|
||||
try {
|
||||
// Ensure .ai directory exists
|
||||
// Ensure .git/ai directory exists
|
||||
await this.fs.mkdir(aiDir, { recursive: true });
|
||||
|
||||
// Ensure .ai/ is gitignored
|
||||
await this.ensureAiGitignored();
|
||||
|
||||
// Format parameters as key=value pairs
|
||||
const lines = Object.entries(parameters).map(([key, value]) =>
|
||||
`${key}=${value}`
|
||||
@@ -225,12 +198,12 @@ export class DotAI {
|
||||
// Write the parameters
|
||||
await this.fs.writeFile(parametersPath, content);
|
||||
} catch (error) {
|
||||
console.warn(`Failed to write .ai/PARAMETERS file: ${error}`);
|
||||
console.warn(`Failed to write .git/ai/PARAMETERS file: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a single parameter in .ai/PARAMETERS file
|
||||
* Update a single parameter in .git/ai/PARAMETERS file
|
||||
*/
|
||||
async updateAiParameter(key: string, value: string): Promise<void> {
|
||||
const currentParameters = await this.readAiParameters();
|
||||
@@ -301,47 +274,4 @@ export class DotAI {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures that .ai/ is gitignored at the project root level.
|
||||
* Creates a .gitignore file if it doesn't exist, or adds the line if not already present.
|
||||
*/
|
||||
async ensureAiGitignored(): Promise<void> {
|
||||
const gitignorePath = join(this.workingDir, ".gitignore");
|
||||
const aiPattern = ".ai/";
|
||||
|
||||
try {
|
||||
// Try to read existing .gitignore
|
||||
let gitignoreContent = "";
|
||||
try {
|
||||
gitignoreContent = await this.fs.readFile(gitignorePath, "utf8");
|
||||
} catch {
|
||||
// .gitignore doesn't exist, will create it
|
||||
}
|
||||
|
||||
// Check if .ai/ is already gitignored
|
||||
const lines = gitignoreContent.split("\n").map((line) => line.trim());
|
||||
const hasAiPattern = lines.some((line) => {
|
||||
if (line.startsWith("#") || line === "") {
|
||||
return false;
|
||||
}
|
||||
// Check for various .ai patterns
|
||||
return line === ".ai" || line === ".ai/" || line === "/.ai" ||
|
||||
line === "/.ai/" ||
|
||||
line === ".ai/*" || line === "/.ai/*";
|
||||
});
|
||||
|
||||
if (!hasAiPattern) {
|
||||
// Add .ai/ to .gitignore
|
||||
const newContent = gitignoreContent.trim() === ""
|
||||
? aiPattern
|
||||
: gitignoreContent.trim() + "\n" + aiPattern;
|
||||
|
||||
await this.fs.writeFile(gitignorePath, newContent + "\n");
|
||||
}
|
||||
} catch (error) {
|
||||
// Log error but don't fail the main operation
|
||||
console.warn(`Failed to ensure .ai/ is gitignored: ${error}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -440,6 +440,67 @@ describe('ProjectsManager', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('cloneProject', () => {
|
||||
it('should clean up project directory when clone fails', async () => {
|
||||
await projectsManager.init();
|
||||
|
||||
// Mock git.clone to fail
|
||||
const mockGit = {
|
||||
clone: vi.fn().mockRejectedValue(new Error('Clone failed')),
|
||||
} as Partial<import('./git').Git>;
|
||||
|
||||
// Replace git instance
|
||||
Object.assign(projectsManager, { git: mockGit });
|
||||
|
||||
// Attempt to clone a project
|
||||
await expect(projectsManager.cloneProject('test-project', 'https://github.com/test/repo.git'))
|
||||
.rejects.toThrow('Clone failed');
|
||||
|
||||
// Verify that the project directory was cleaned up
|
||||
const project = await projectsManager.getProject('test-project');
|
||||
expect(project).toBeNull();
|
||||
|
||||
// Verify directory doesn't exist in filesystem
|
||||
await expect(fs.stat('/projects/test-project')).rejects.toThrow('ENOENT');
|
||||
});
|
||||
|
||||
it('should handle cleanup errors gracefully', async () => {
|
||||
await projectsManager.init();
|
||||
|
||||
// Mock git.clone to fail
|
||||
const mockGit = {
|
||||
clone: vi.fn().mockRejectedValue(new Error('Clone failed')),
|
||||
} as Partial<import('./git').Git>;
|
||||
|
||||
// Replace git instance
|
||||
Object.assign(projectsManager, { git: mockGit });
|
||||
|
||||
// Spy on console.warn to check for cleanup warnings
|
||||
const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
|
||||
// Mock fs.rmdir to fail (simulate cleanup error)
|
||||
const originalRmdir = fs.rmdir;
|
||||
fs.rmdir = vi.fn().mockRejectedValue(new Error('Cleanup failed'));
|
||||
|
||||
try {
|
||||
// Attempt to clone a project
|
||||
await expect(projectsManager.cloneProject('test-project', 'https://github.com/test/repo.git'))
|
||||
.rejects.toThrow('Clone failed');
|
||||
|
||||
// Should have logged a cleanup warning
|
||||
expect(consoleSpy).toHaveBeenCalledWith(
|
||||
'Failed to clean up directory after clone failure:',
|
||||
expect.any(Error)
|
||||
);
|
||||
|
||||
} finally {
|
||||
// Restore mocks
|
||||
consoleSpy.mockRestore();
|
||||
fs.rmdir = originalRmdir;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('renameProject', () => {
|
||||
it('should rename a project directory', async () => {
|
||||
await projectsManager.init();
|
||||
|
||||
+56
-40
@@ -2,6 +2,7 @@ import { Buffer } from 'buffer';
|
||||
import JSZip from 'jszip';
|
||||
import { Git } from '@/lib/git';
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
import { ensurePersistentStorage } from '@/lib/persistentStorage';
|
||||
|
||||
// Polyfill Buffer for browser
|
||||
if (typeof window !== 'undefined') {
|
||||
@@ -45,12 +46,6 @@ export class ProjectsManager {
|
||||
async createProject(name: string, customId?: string): Promise<Project> {
|
||||
const project = await this.cloneProject(name, GIT_TEMPLATE_URL, customId, { depth: 1 });
|
||||
|
||||
try {
|
||||
await this.fs.mkdir(this.dir + `/${project.id}/.ai/history`, { recursive: true });
|
||||
} catch {
|
||||
// Directory might already exist
|
||||
}
|
||||
|
||||
// Delete README.md if it exists
|
||||
try {
|
||||
await this.fs.unlink(`${project.path}/README.md`);
|
||||
@@ -74,8 +69,8 @@ export class ProjectsManager {
|
||||
// Add all files to git
|
||||
const files = await this.getAllFiles(project.path);
|
||||
for (const file of files) {
|
||||
// Skip .git directory and other hidden files we don't want to track
|
||||
if (!file.startsWith('.git/') && !file.startsWith('.ai/')) {
|
||||
// Skip .git directory
|
||||
if (!file.startsWith('.git/')) {
|
||||
await this.git.add({
|
||||
dir: project.path,
|
||||
filepath: file,
|
||||
@@ -93,6 +88,14 @@ export class ProjectsManager {
|
||||
},
|
||||
});
|
||||
|
||||
// Automatically request persistent storage after project creation
|
||||
try {
|
||||
await ensurePersistentStorage();
|
||||
} catch (error) {
|
||||
// Don't fail project creation if persistent storage request fails
|
||||
console.warn('Failed to request persistent storage after project creation:', error);
|
||||
}
|
||||
|
||||
return project;
|
||||
}
|
||||
|
||||
@@ -135,12 +138,12 @@ export class ProjectsManager {
|
||||
// Create project directory (or ensure it exists for overwrite)
|
||||
await this.fs.mkdir(projectPath, { recursive: true });
|
||||
|
||||
// If overwriting, delete existing files except .ai directory and .git directory
|
||||
// If overwriting, delete existing files except .git directory
|
||||
if (projectExists && overwrite) {
|
||||
const existingFiles = await this.getAllFiles(projectPath);
|
||||
for (const file of existingFiles) {
|
||||
// Preserve .ai directory and .git directory
|
||||
if (!file.startsWith('.ai/') && !file.startsWith('.git/')) {
|
||||
// Preserve .git directory
|
||||
if (!file.startsWith('.git/')) {
|
||||
try {
|
||||
await this.fs.unlink(`${projectPath}/${file}`);
|
||||
} catch {
|
||||
@@ -203,8 +206,8 @@ export class ProjectsManager {
|
||||
if (overwrite) {
|
||||
const projectFiles = await this.getAllFiles(projectPath);
|
||||
for (const file of projectFiles) {
|
||||
// Skip .git directory and .ai directory
|
||||
if (!file.startsWith('.git/') && !file.startsWith('.ai/')) {
|
||||
// Skip .git directory
|
||||
if (!file.startsWith('.git/')) {
|
||||
try {
|
||||
await this.git.add({
|
||||
dir: projectPath,
|
||||
@@ -233,11 +236,11 @@ export class ProjectsManager {
|
||||
defaultBranch: 'main',
|
||||
});
|
||||
|
||||
// Add all files to git (excluding .ai directory)
|
||||
// Add all files to git
|
||||
const projectFiles = await this.getAllFiles(projectPath);
|
||||
for (const file of projectFiles) {
|
||||
// Skip .git directory and .ai directory
|
||||
if (!file.startsWith('.git/') && !file.startsWith('.ai/')) {
|
||||
// Skip .git directory
|
||||
if (!file.startsWith('.git/')) {
|
||||
await this.git.add({
|
||||
dir: projectPath,
|
||||
filepath: file,
|
||||
@@ -256,13 +259,6 @@ export class ProjectsManager {
|
||||
});
|
||||
}
|
||||
|
||||
// Create .ai/history directory
|
||||
try {
|
||||
await this.fs.mkdir(`${projectPath}/.ai/history`, { recursive: true });
|
||||
} catch {
|
||||
// Directory might already exist
|
||||
}
|
||||
|
||||
return {
|
||||
id,
|
||||
name: projectName,
|
||||
@@ -294,25 +290,45 @@ export class ProjectsManager {
|
||||
|
||||
await this.fs.mkdir(projectPath);
|
||||
|
||||
// Clone the repository (Git class now handles Nostr URIs automatically)
|
||||
await this.git.clone({
|
||||
dir: projectPath,
|
||||
url: repoUrl,
|
||||
singleBranch: true,
|
||||
depth: options?.depth, // Use depth if provided, otherwise clone full history
|
||||
});
|
||||
try {
|
||||
// Clone the repository (Git class now handles Nostr URIs automatically)
|
||||
await this.git.clone({
|
||||
dir: projectPath,
|
||||
url: repoUrl,
|
||||
singleBranch: true,
|
||||
depth: options?.depth, // Use depth if provided, otherwise clone full history
|
||||
});
|
||||
|
||||
// Get filesystem stats for timestamps
|
||||
const stats = await this.fs.stat(projectPath);
|
||||
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||
// Get filesystem stats for timestamps
|
||||
const stats = await this.fs.stat(projectPath);
|
||||
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||
|
||||
// Return the full project object with dynamically generated properties
|
||||
return {
|
||||
id,
|
||||
name: this.formatProjectName(id), // Use formatted directory name
|
||||
path: projectPath,
|
||||
lastModified: timestamp,
|
||||
};
|
||||
// Automatically request persistent storage after project cloning
|
||||
try {
|
||||
await ensurePersistentStorage();
|
||||
} catch (error) {
|
||||
// Don't fail project cloning if persistent storage request fails
|
||||
console.warn('Failed to request persistent storage after project cloning:', error);
|
||||
}
|
||||
|
||||
// Return the full project object with dynamically generated properties
|
||||
return {
|
||||
id,
|
||||
name: this.formatProjectName(id), // Use formatted directory name
|
||||
path: projectPath,
|
||||
lastModified: timestamp,
|
||||
};
|
||||
} catch (error) {
|
||||
// Clean up the directory that was created if cloning fails
|
||||
try {
|
||||
await this.deleteDirectory(projectPath);
|
||||
} catch (cleanupError) {
|
||||
// Log cleanup error but don't mask the original clone error
|
||||
console.warn('Failed to clean up directory after clone failure:', cleanupError);
|
||||
}
|
||||
// Re-throw the original clone error
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async getProjects(): Promise<Project[]> {
|
||||
|
||||
@@ -95,4 +95,26 @@ describe('SessionManager', () => {
|
||||
expect(messageWithReasoning.reasoning_content).toBe('Let me think about this step by step...');
|
||||
}
|
||||
});
|
||||
|
||||
it('should throw service errors instead of adding them to message history', async () => {
|
||||
const projectId = 'test-project';
|
||||
const tools = {};
|
||||
const customTools = {};
|
||||
|
||||
// Load a session
|
||||
await sessionManager.loadSession(projectId, tools, customTools);
|
||||
|
||||
// Add a user message to enable generation
|
||||
await sessionManager.addMessage(projectId, { role: 'user', content: 'test message' });
|
||||
|
||||
// Attempt to start generation with invalid provider - should throw error instead of adding to messages
|
||||
await expect(
|
||||
sessionManager.startGeneration(projectId, 'invalid-provider/invalid-model')
|
||||
).rejects.toThrow('Provider "invalid-provider" not found');
|
||||
|
||||
// Verify that no error message was added to the conversation
|
||||
const updatedSession = sessionManager.getSession(projectId);
|
||||
expect(updatedSession?.messages).toHaveLength(1); // Only the user message
|
||||
expect(updatedSession?.messages[0].role).toBe('user');
|
||||
});
|
||||
});
|
||||
@@ -188,10 +188,6 @@ export class SessionManager {
|
||||
throw new Error('No messages in session');
|
||||
}
|
||||
|
||||
// Check if last message is from user
|
||||
const lastMessage = session.messages[session.messages.length - 1];
|
||||
if (lastMessage.role !== 'user') return;
|
||||
|
||||
session.isLoading = true;
|
||||
session.abortController = new AbortController();
|
||||
session.lastActivity = new Date();
|
||||
@@ -250,7 +246,6 @@ export class SessionManager {
|
||||
model,
|
||||
messages,
|
||||
tools: session.tools && Object.keys(session.tools).length > 0 ? Object.values(session.tools) : undefined,
|
||||
tool_choice: session.tools && Object.keys(session.tools).length > 0 ? 'auto' : undefined,
|
||||
stream: true,
|
||||
stream_options: {
|
||||
include_usage: true,
|
||||
@@ -301,9 +296,9 @@ export class SessionManager {
|
||||
}
|
||||
|
||||
if (delta?.tool_calls) {
|
||||
for (const toolCallDelta of delta.tool_calls) {
|
||||
const index = toolCallDelta.index;
|
||||
if (index === undefined) continue;
|
||||
for (let i = 0; i < delta.tool_calls.length; i++) {
|
||||
const toolCallDelta = delta.tool_calls[i];
|
||||
const index = toolCallDelta.index ?? i; // Fix for Gemini models
|
||||
|
||||
accumulatedToolCalls[index] ??= {
|
||||
id: '',
|
||||
@@ -404,25 +399,13 @@ export class SessionManager {
|
||||
} catch (error) {
|
||||
console.error('AI generation error:', error);
|
||||
|
||||
// Handle different error types
|
||||
// Handle user cancellation
|
||||
if (error instanceof OpenAI.APIUserAbortError || error?.name === 'AbortError') {
|
||||
return; // User cancelled
|
||||
}
|
||||
|
||||
let errorMessage = 'Sorry, I encountered an unexpected error. Please try again.';
|
||||
const errorMsg = error?.message || '';
|
||||
|
||||
if (error?.name === 'TypeError' && errorMsg.includes('fetch')) {
|
||||
errorMessage = 'Network error: Unable to connect to AI service. Please check your internet connection and AI settings.';
|
||||
} else if (errorMsg.includes('API key')) {
|
||||
errorMessage = 'Authentication error: Please check your API key in AI settings.';
|
||||
} else if (errorMsg.includes('rate limit')) {
|
||||
errorMessage = 'Rate limit exceeded. Please wait a moment before trying again.';
|
||||
} else if (errorMsg) {
|
||||
errorMessage = `AI service error: ${errorMsg}`;
|
||||
}
|
||||
|
||||
await this.addMessage(projectId, { role: 'assistant', content: errorMessage });
|
||||
// Re-throw service errors to be handled at the UI level
|
||||
throw error;
|
||||
} finally {
|
||||
if (session) {
|
||||
session.isLoading = false;
|
||||
|
||||
@@ -13,11 +13,11 @@ export function createAIClient(provider: AIProvider, user?: NUser): OpenAI {
|
||||
baseURL: provider.baseURL,
|
||||
apiKey: provider.apiKey ?? '',
|
||||
dangerouslyAllowBrowser: true,
|
||||
defaultHeaders: {
|
||||
defaultHeaders: provider.id === 'openrouter' ? {
|
||||
// https://openrouter.ai/docs/app-attribution
|
||||
'HTTP-Referer': 'https://shakespeare.diy',
|
||||
'X-Title': 'Shakespeare',
|
||||
},
|
||||
} : {},
|
||||
};
|
||||
|
||||
let openai: OpenAI;
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { AI_PROVIDER_PRESETS, getPresetProvider, getShakespeareProvider } from './aiProviderPresets';
|
||||
|
||||
describe('AI Provider Presets', () => {
|
||||
it('should export preset providers array', () => {
|
||||
expect(AI_PROVIDER_PRESETS).toBeDefined();
|
||||
expect(Array.isArray(AI_PROVIDER_PRESETS)).toBe(true);
|
||||
expect(AI_PROVIDER_PRESETS.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('should include Shakespeare provider', () => {
|
||||
const shakespeare = AI_PROVIDER_PRESETS.find(p => p.id === 'shakespeare');
|
||||
expect(shakespeare).toBeDefined();
|
||||
expect(shakespeare?.name).toBe('Shakespeare AI');
|
||||
expect(shakespeare?.nostr).toBe(true);
|
||||
});
|
||||
|
||||
it('should include other major providers', () => {
|
||||
const providerIds = AI_PROVIDER_PRESETS.map(p => p.id);
|
||||
expect(providerIds).toContain('openai');
|
||||
expect(providerIds).toContain('anthropic');
|
||||
expect(providerIds).toContain('openrouter');
|
||||
});
|
||||
|
||||
it('should get preset provider by id', () => {
|
||||
const openai = getPresetProvider('openai');
|
||||
expect(openai).toBeDefined();
|
||||
expect(openai?.name).toBe('OpenAI');
|
||||
|
||||
const nonExistent = getPresetProvider('non-existent');
|
||||
expect(nonExistent).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should get Shakespeare provider', () => {
|
||||
const shakespeare = getShakespeareProvider();
|
||||
expect(shakespeare).toBeDefined();
|
||||
expect(shakespeare.id).toBe('shakespeare');
|
||||
expect(shakespeare.name).toBe('Shakespeare AI');
|
||||
expect(shakespeare.nostr).toBe(true);
|
||||
});
|
||||
|
||||
it('should have valid preset structure', () => {
|
||||
AI_PROVIDER_PRESETS.forEach(preset => {
|
||||
expect(preset.id).toBeDefined();
|
||||
expect(typeof preset.id).toBe('string');
|
||||
expect(preset.name).toBeDefined();
|
||||
expect(typeof preset.name).toBe('string');
|
||||
expect(preset.baseURL).toBeDefined();
|
||||
expect(typeof preset.baseURL).toBe('string');
|
||||
expect(preset.baseURL).toMatch(/^https?:\/\//);
|
||||
|
||||
// Optional fields
|
||||
if (preset.apiKeysURL) {
|
||||
expect(typeof preset.apiKeysURL).toBe('string');
|
||||
expect(preset.apiKeysURL).toMatch(/^https?:\/\//);
|
||||
}
|
||||
if (preset.nostr !== undefined) {
|
||||
expect(typeof preset.nostr).toBe('boolean');
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
export interface PresetProvider {
|
||||
id: string;
|
||||
name: string;
|
||||
baseURL: string;
|
||||
apiKeysURL?: string;
|
||||
nostr?: boolean;
|
||||
tosURL?: string;
|
||||
}
|
||||
|
||||
export const AI_PROVIDER_PRESETS: PresetProvider[] = [
|
||||
{
|
||||
id: "shakespeare",
|
||||
name: "Shakespeare AI",
|
||||
baseURL: "https://ai.shakespeare.diy/v1",
|
||||
tosURL: "https://ai.shakespeare.diy/terms",
|
||||
nostr: true,
|
||||
},
|
||||
{
|
||||
id: "openrouter",
|
||||
name: "OpenRouter",
|
||||
baseURL: "https://openrouter.ai/api/v1",
|
||||
apiKeysURL: "https://openrouter.ai/settings/keys",
|
||||
tosURL: "https://openrouter.ai/terms",
|
||||
},
|
||||
{
|
||||
id: "ppq",
|
||||
name: "PayPerQ",
|
||||
baseURL: "https://api.ppq.ai",
|
||||
apiKeysURL: "https://ppq.ai/api-docs",
|
||||
tosURL: "https://ppq.ai/terms",
|
||||
},
|
||||
{
|
||||
id: "routstr",
|
||||
name: "Routstr",
|
||||
baseURL: "https://api.routstr.com/v1",
|
||||
apiKeysURL: "https://chat.routstr.com/",
|
||||
tosURL: "https://routstr.com/terms",
|
||||
},
|
||||
{
|
||||
id: "zai",
|
||||
name: "Z.ai",
|
||||
baseURL: "https://api.z.ai/api/paas/v4",
|
||||
apiKeysURL: "https://z.ai/manage-apikey/apikey-list",
|
||||
tosURL: "https://docs.z.ai/legal-agreement/terms-of-use",
|
||||
},
|
||||
{
|
||||
id: "openai",
|
||||
name: "OpenAI",
|
||||
baseURL: "https://api.openai.com/v1",
|
||||
apiKeysURL: "https://platform.openai.com/api-keys",
|
||||
tosURL: "https://openai.com/policies/",
|
||||
},
|
||||
{
|
||||
id: "anthropic",
|
||||
name: "Anthropic",
|
||||
baseURL: "https://api.anthropic.com/v1",
|
||||
apiKeysURL: "https://console.anthropic.com/settings/keys",
|
||||
tosURL: "https://www.anthropic.com/legal/",
|
||||
},
|
||||
{
|
||||
id: "xai",
|
||||
name: "xAI",
|
||||
baseURL: "https://api.x.ai/v1",
|
||||
apiKeysURL: "https://console.x.ai",
|
||||
tosURL: "https://x.ai/legal",
|
||||
},
|
||||
];
|
||||
|
||||
// Helper function to get a specific preset by ID
|
||||
export function getPresetProvider(id: string): PresetProvider | undefined {
|
||||
return AI_PROVIDER_PRESETS.find(preset => preset.id === id);
|
||||
}
|
||||
|
||||
// Helper function to get the Shakespeare provider preset
|
||||
export function getShakespeareProvider(): PresetProvider {
|
||||
const shakespeare = getPresetProvider("shakespeare");
|
||||
if (!shakespeare) {
|
||||
throw new Error("Shakespeare provider preset not found");
|
||||
}
|
||||
return shakespeare;
|
||||
}
|
||||
@@ -5,6 +5,7 @@ interface PackageLock {
|
||||
[key: string]: {
|
||||
name?: string;
|
||||
version: string;
|
||||
peerDependencies?: { [key: string]: string };
|
||||
} | undefined;
|
||||
};
|
||||
}
|
||||
@@ -61,6 +62,14 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
|
||||
}
|
||||
});
|
||||
|
||||
// Legacy (Internet Explorer) "behavior" syntax
|
||||
build.onResolve({ filter: /^#default#/, namespace: "esm" }, (args) => {
|
||||
return {
|
||||
path: args.path,
|
||||
external: true,
|
||||
};
|
||||
});
|
||||
|
||||
// Handle bare imports like "react"
|
||||
build.onResolve({ filter: /^[^./].*/ }, (args) => {
|
||||
const packageName = args.path.startsWith("@")
|
||||
@@ -69,10 +78,18 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
|
||||
|
||||
// Handle transitive dependency versions
|
||||
const keys: string[] = [];
|
||||
let importerPkg: string | undefined;
|
||||
let importerVersion: string | undefined;
|
||||
try {
|
||||
const importerPackage = extractPackageName(args.importer);
|
||||
const { pathname } = new URL(args.importer);
|
||||
if (/\.css$/.test(pathname)) {
|
||||
return; // CSS imports don't have external dependencies
|
||||
}
|
||||
const result = extractPackageName(args.importer);
|
||||
importerPkg = result.pkg;
|
||||
importerVersion = result.version;
|
||||
keys.push(
|
||||
`node_modules/${importerPackage}/node_modules/${packageName}`,
|
||||
`node_modules/${importerPkg}/node_modules/${packageName}`,
|
||||
);
|
||||
} catch {
|
||||
// fallthrough
|
||||
@@ -89,12 +106,20 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
|
||||
.find((info) => info);
|
||||
|
||||
const packagePath = args.path.slice(packageName.length);
|
||||
const version = packageInfo?.version;
|
||||
|
||||
if (!version) return;
|
||||
let version: string | undefined;
|
||||
|
||||
const name = packageInfo.name ?? packageName;
|
||||
const specifier = `${name}@${version}${packagePath}`;
|
||||
if (importerPkg === packageName && importerVersion) {
|
||||
version = importerVersion;
|
||||
} else {
|
||||
version = packageInfo?.version
|
||||
|| packageLock.packages[`node_modules/${importerPkg}`]?.peerDependencies?.[packageName];
|
||||
}
|
||||
|
||||
const name = packageInfo?.name ?? packageName;
|
||||
const specifier = version
|
||||
? `${name}@${version}${packagePath}`
|
||||
: `${name}${packagePath}`;
|
||||
|
||||
const url = new URL(`https://esm.sh/*${specifier}`);
|
||||
|
||||
@@ -131,6 +156,14 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
|
||||
}
|
||||
}
|
||||
|
||||
// Skip static assets
|
||||
if (/\.(woff2?|ttf|otf|eot)$/.test(fullURL.pathname)) {
|
||||
return {
|
||||
path: fullURL.toString(),
|
||||
external: true,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
path: fullURL.toString(),
|
||||
namespace: "esm",
|
||||
@@ -174,7 +207,7 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
|
||||
}
|
||||
|
||||
/** Extract package name from esm.sh-style URL */
|
||||
function extractPackageName(esmShURL: string): string {
|
||||
function extractPackageName(esmShURL: string): { pkg?: string; version?: string } {
|
||||
const full = new URL(esmShURL)
|
||||
.pathname
|
||||
.slice(1)
|
||||
@@ -184,7 +217,15 @@ function extractPackageName(esmShURL: string): string {
|
||||
? full.split("/").slice(0, 2).join("/")
|
||||
: full.split("/")[0];
|
||||
|
||||
return full.startsWith("@")
|
||||
const pkg = full.startsWith("@")
|
||||
? base.split("@").splice(0, 2).join("@")
|
||||
: base.split("@")[0];
|
||||
|
||||
let version: string | undefined;
|
||||
|
||||
if (full.slice(pkg.length).startsWith("@")) {
|
||||
version = full.slice(pkg.length + 1).split("/")[0];
|
||||
}
|
||||
|
||||
return { pkg, version };
|
||||
}
|
||||
+31
-10
@@ -1,4 +1,4 @@
|
||||
import path from "path-browserify";
|
||||
import { join, dirname, extname } from "path-browserify";
|
||||
|
||||
import type { Loader, Plugin } from "esbuild-wasm";
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
@@ -8,27 +8,37 @@ export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin {
|
||||
name: "fs",
|
||||
|
||||
setup(build) {
|
||||
build.onResolve({ filter: /^data:/ }, (args) => {
|
||||
return {
|
||||
path: args.path,
|
||||
external: true,
|
||||
};
|
||||
});
|
||||
|
||||
build.onResolve({ filter: /.*/ }, async (args) => {
|
||||
let resolved: string;
|
||||
|
||||
if (args.path.startsWith("@/")) {
|
||||
resolved = path.join(cwd, args.path.slice(2));
|
||||
resolved = join(cwd, args.path.slice(2));
|
||||
} else if (args.kind === "entry-point") {
|
||||
resolved = path.join(cwd, args.path);
|
||||
resolved = join(cwd, args.path);
|
||||
} else if (args.importer) {
|
||||
resolved = path.join(path.dirname(args.importer), args.path);
|
||||
resolved = join(dirname(args.importer), args.path);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
// Vite query parameters https://vite.dev/guide/assets
|
||||
const [cleaned, query] = resolved.split("?");
|
||||
|
||||
try {
|
||||
resolved = await tryFileVariants(fs, resolved);
|
||||
resolved = await tryFileVariants(fs, cleaned);
|
||||
} catch {
|
||||
return; // Let other plugins handle this
|
||||
}
|
||||
|
||||
return {
|
||||
path: resolved,
|
||||
path: resolved + (typeof query === "string" ? "?" + query : ""),
|
||||
namespace: "fs",
|
||||
};
|
||||
});
|
||||
@@ -36,14 +46,25 @@ export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin {
|
||||
build.onLoad(
|
||||
{ filter: /.*/, namespace: "fs" },
|
||||
async (args) => {
|
||||
const ext = path.extname(args.path).slice(1);
|
||||
const [path, query] = args.path.split("?");
|
||||
const params = new URLSearchParams(query);
|
||||
|
||||
if (!["ts", "tsx", "js", "jsx", "css"].includes(ext)) {
|
||||
// https://vite.dev/guide/assets.html#importing-asset-as-string
|
||||
if (params.has("raw")) {
|
||||
return {
|
||||
contents: await fs.readFile(path, "utf8"),
|
||||
loader: "text",
|
||||
};
|
||||
}
|
||||
|
||||
const ext = extname(path).slice(1);
|
||||
|
||||
if (!["ts", "tsx", "js", "jsx", "css", "json"].includes(ext)) {
|
||||
return;
|
||||
}
|
||||
|
||||
return {
|
||||
contents: await fs.readFile(args.path, "utf8"),
|
||||
contents: await fs.readFile(path, "utf8"),
|
||||
loader: ext as Loader,
|
||||
};
|
||||
},
|
||||
@@ -67,7 +88,7 @@ async function tryFileVariants(
|
||||
// If it's a directory, try index files
|
||||
if (stat.isDirectory()) {
|
||||
for (const ext of extensions) {
|
||||
const indexFile = path.join(basePath, "index" + ext);
|
||||
const indexFile = join(basePath, "index" + ext);
|
||||
const indexStat = await statSafe(fs, indexFile);
|
||||
if (indexStat.isFile()) {
|
||||
return indexFile;
|
||||
|
||||
+11
-6
@@ -1,6 +1,7 @@
|
||||
import { getEsbuild } from "@/lib/esbuild";
|
||||
import { copyFiles } from "@/lib/copyFiles";
|
||||
|
||||
import { shakespearePlugin } from "./shakespearePlugin";
|
||||
import { esmPlugin } from "./esmPlugin";
|
||||
import { fsPlugin } from "./fsPlugin";
|
||||
|
||||
@@ -49,6 +50,7 @@ async function bundle(
|
||||
outdir: "/",
|
||||
jsx: "automatic",
|
||||
plugins: [
|
||||
shakespearePlugin(), // Takes precedence over esmPlugin
|
||||
fsPlugin(fs, `${projectPath}/src`),
|
||||
esmPlugin(JSON.parse(packageLockText), target),
|
||||
],
|
||||
@@ -71,7 +73,7 @@ async function bundle(
|
||||
}
|
||||
|
||||
// Update index.html with proper script and link tags
|
||||
updateIndexHtml(doc);
|
||||
updateIndexHtml(doc, dist);
|
||||
|
||||
const updatedHtml = "<!DOCTYPE html>\n" + doc.documentElement.outerHTML;
|
||||
dist["index.html"] = new TextEncoder().encode(updatedHtml);
|
||||
@@ -154,7 +156,7 @@ export async function buildProject(options: BuildProjectOptions): Promise<{
|
||||
};
|
||||
}
|
||||
|
||||
function updateIndexHtml(doc: Document): void {
|
||||
function updateIndexHtml(doc: Document, dist: Record<string, Uint8Array>): void {
|
||||
const entrypoint = doc.querySelector('script[src="/src/main.tsx"]');
|
||||
|
||||
if (!entrypoint) {
|
||||
@@ -163,8 +165,11 @@ function updateIndexHtml(doc: Document): void {
|
||||
|
||||
entrypoint.setAttribute("src", "/main.js");
|
||||
|
||||
const style = doc.createElement("link");
|
||||
style.setAttribute("rel", "stylesheet");
|
||||
style.setAttribute("href", "/main.css");
|
||||
doc.head.appendChild(style);
|
||||
const css = dist["main.css"];
|
||||
if (css) {
|
||||
const style = doc.createElement("style");
|
||||
style.setAttribute("type", "text/tailwindcss");
|
||||
style.textContent = new TextDecoder().decode(css);
|
||||
doc.head.appendChild(style);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import type { Plugin } from "esbuild-wasm";
|
||||
|
||||
/**
|
||||
* Shakespeare plugin for dependency polyfills and workarounds.
|
||||
* This plugin handles specific dependencies that need custom implementations
|
||||
* or dummy APIs to work correctly in the browser environment.
|
||||
*/
|
||||
export function shakespearePlugin(): Plugin {
|
||||
return {
|
||||
name: "shakespeare",
|
||||
|
||||
setup(build) {
|
||||
// Handle "sonner" imports with a dummy API
|
||||
build.onResolve({ filter: /^sonner$/ }, (args) => {
|
||||
return {
|
||||
path: args.path,
|
||||
namespace: "shakespeare-sonner",
|
||||
};
|
||||
});
|
||||
|
||||
// Provide dummy sonner implementation
|
||||
build.onLoad({ filter: /.*/, namespace: "shakespeare-sonner" }, () => {
|
||||
return {
|
||||
contents: `
|
||||
// Dummy implementation of sonner toast library
|
||||
|
||||
// Toast function that does nothing
|
||||
const toast = (message, options) => {
|
||||
console.log('[Shakespeare Sonner Mock]:', message, options);
|
||||
return { id: Math.random().toString(36) };
|
||||
};
|
||||
|
||||
// Add common toast methods
|
||||
toast.success = (message, options) => {
|
||||
console.log('[Shakespeare Sonner Mock] Success:', message, options);
|
||||
return { id: Math.random().toString(36) };
|
||||
};
|
||||
|
||||
toast.error = (message, options) => {
|
||||
console.log('[Shakespeare Sonner Mock] Error:', message, options);
|
||||
return { id: Math.random().toString(36) };
|
||||
};
|
||||
|
||||
toast.info = (message, options) => {
|
||||
console.log('[Shakespeare Sonner Mock] Info:', message, options);
|
||||
return { id: Math.random().toString(36) };
|
||||
};
|
||||
|
||||
toast.warning = (message, options) => {
|
||||
console.log('[Shakespeare Sonner Mock] Warning:', message, options);
|
||||
return { id: Math.random().toString(36) };
|
||||
};
|
||||
|
||||
toast.loading = (message, options) => {
|
||||
console.log('[Shakespeare Sonner Mock] Loading:', message, options);
|
||||
return { id: Math.random().toString(36) };
|
||||
};
|
||||
|
||||
toast.promise = (promise, options) => {
|
||||
console.log('[Shakespeare Sonner Mock] Promise:', promise, options);
|
||||
return promise;
|
||||
};
|
||||
|
||||
toast.dismiss = (id) => {
|
||||
console.log('[Shakespeare Sonner Mock] Dismiss:', id);
|
||||
};
|
||||
|
||||
// Toaster component (dummy React component)
|
||||
const Toaster = (props) => {
|
||||
console.log('[Shakespeare Sonner Mock] Toaster component rendered:', props);
|
||||
return null;
|
||||
};
|
||||
|
||||
// Export both named and default exports to match sonner API
|
||||
export { toast, Toaster };
|
||||
export default toast;
|
||||
`,
|
||||
loader: "js",
|
||||
};
|
||||
});
|
||||
|
||||
// Handle "next-themes" imports with a dummy API
|
||||
build.onResolve({ filter: /^next-themes$/ }, (args) => {
|
||||
return {
|
||||
path: args.path,
|
||||
namespace: "shakespeare-next-themes",
|
||||
};
|
||||
});
|
||||
|
||||
// Provide dummy next-themes implementation
|
||||
build.onLoad({ filter: /.*/, namespace: "shakespeare-next-themes" }, () => {
|
||||
return {
|
||||
contents: `
|
||||
// Dummy implementation of next-themes
|
||||
|
||||
// useTheme hook that returns system theme
|
||||
const useTheme = () => {
|
||||
return { theme: "system" };
|
||||
};
|
||||
|
||||
// ThemeProvider component (dummy React component)
|
||||
const ThemeProvider = ({ children, ...props }) => {
|
||||
console.log('[Shakespeare next-themes Mock] ThemeProvider rendered:', props);
|
||||
return children;
|
||||
};
|
||||
|
||||
// Export both named and default exports to match next-themes API
|
||||
export { useTheme, ThemeProvider };
|
||||
`,
|
||||
loader: "js",
|
||||
};
|
||||
});
|
||||
|
||||
// Handle "virtual:pwa-register/react" imports with a dummy API
|
||||
build.onResolve({ filter: /^virtual:pwa-register\/react$/ }, (args) => {
|
||||
return {
|
||||
path: args.path,
|
||||
namespace: "shakespeare-pwa-register",
|
||||
};
|
||||
});
|
||||
|
||||
// Provide dummy PWA register implementation
|
||||
build.onLoad({ filter: /.*/, namespace: "shakespeare-pwa-register" }, () => {
|
||||
return {
|
||||
contents: `
|
||||
// Dummy implementation of virtual:pwa-register/react
|
||||
|
||||
// useRegisterSW hook that returns dummy functions
|
||||
const useRegisterSW = (options = {}) => {
|
||||
console.log('[Shakespeare PWA Mock] useRegisterSW called:', options);
|
||||
|
||||
return {
|
||||
needRefresh: [false, () => {}],
|
||||
offlineReady: [false, () => {}],
|
||||
updateServiceWorker: (reloadPage) => {
|
||||
console.log('[Shakespeare PWA Mock] updateServiceWorker called:', reloadPage);
|
||||
if (reloadPage) {
|
||||
window.location.reload();
|
||||
}
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
// Export the hook
|
||||
export { useRegisterSW };
|
||||
`,
|
||||
loader: "js",
|
||||
};
|
||||
});
|
||||
|
||||
// Add more dependency polyfills here as needed
|
||||
// Example structure for future dependencies:
|
||||
// build.onResolve({ filter: /^some-other-package$/ }, (args) => {
|
||||
// return {
|
||||
// path: args.path,
|
||||
// namespace: "shakespeare-other-package",
|
||||
// };
|
||||
// });
|
||||
//
|
||||
// build.onLoad({ filter: /.*/, namespace: "shakespeare-other-package" }, () => {
|
||||
// return {
|
||||
// contents: `// Custom implementation for some-other-package`,
|
||||
// loader: "js",
|
||||
// };
|
||||
// });
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import { GitCheckoutCommand } from "./git/checkout";
|
||||
import { GitRemoteCommand } from "./git/remote";
|
||||
import { GitPushCommand } from "./git/push";
|
||||
import { GitPullCommand } from "./git/pull";
|
||||
import { GitFetchCommand } from "./git/fetch";
|
||||
import { GitCloneCommand } from "./git/clone";
|
||||
import { GitConfigCommand } from "./git/config";
|
||||
import { GitResetCommand } from "./git/reset";
|
||||
@@ -77,6 +78,7 @@ export class GitCommand implements ShellCommand {
|
||||
this.registerSubcommand(new GitRemoteCommand(subcommandOptions));
|
||||
this.registerSubcommand(new GitPushCommand(subcommandOptions));
|
||||
this.registerSubcommand(new GitPullCommand(subcommandOptions));
|
||||
this.registerSubcommand(new GitFetchCommand(subcommandOptions));
|
||||
this.registerSubcommand(new GitCloneCommand(subcommandOptions));
|
||||
this.registerSubcommand(new GitConfigCommand(subcommandOptions));
|
||||
this.registerSubcommand(new GitResetCommand(subcommandOptions));
|
||||
@@ -144,6 +146,7 @@ grow, mark and tweak your common history
|
||||
tag Create, list, delete or verify a tag object
|
||||
|
||||
collaborate (see also: git help workflows)
|
||||
fetch Download objects and refs from another repository
|
||||
pull Fetch from and integrate with another repository or a local branch
|
||||
push Update remote refs along with associated objects
|
||||
remote Manage set of tracked repositories
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { GitAddCommand } from './add';
|
||||
import type { JSRuntimeFS } from '../../JSRuntime';
|
||||
import type { Git } from '../../git';
|
||||
|
||||
// Mock filesystem
|
||||
const createMockFS = (): JSRuntimeFS => ({
|
||||
readFile: vi.fn().mockResolvedValue('mock content'),
|
||||
writeFile: vi.fn().mockResolvedValue(undefined),
|
||||
readdir: vi.fn().mockResolvedValue([]),
|
||||
mkdir: vi.fn().mockResolvedValue(undefined),
|
||||
stat: vi.fn().mockImplementation((path: string) => {
|
||||
if (path.endsWith('/.git')) {
|
||||
return Promise.resolve({
|
||||
isDirectory: () => true,
|
||||
isFile: () => false,
|
||||
size: 0,
|
||||
mtimeMs: Date.now(),
|
||||
});
|
||||
}
|
||||
return Promise.resolve({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
size: 100,
|
||||
mtimeMs: Date.now(),
|
||||
});
|
||||
}),
|
||||
lstat: vi.fn().mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
size: 100,
|
||||
mtimeMs: Date.now(),
|
||||
}),
|
||||
unlink: vi.fn().mockResolvedValue(undefined),
|
||||
rmdir: vi.fn().mockResolvedValue(undefined),
|
||||
rename: vi.fn().mockResolvedValue(undefined),
|
||||
readlink: vi.fn().mockResolvedValue('mock link'),
|
||||
symlink: vi.fn().mockResolvedValue(undefined),
|
||||
});
|
||||
|
||||
// Mock Git
|
||||
const createMockGit = (): Git => ({
|
||||
statusMatrix: vi.fn(),
|
||||
add: vi.fn(),
|
||||
remove: vi.fn(),
|
||||
} as unknown as Git);
|
||||
|
||||
describe('GitAddCommand', () => {
|
||||
let addCommand: GitAddCommand;
|
||||
let mockFS: JSRuntimeFS;
|
||||
let mockGit: Git;
|
||||
const testCwd = '/test';
|
||||
|
||||
beforeEach(() => {
|
||||
mockFS = createMockFS();
|
||||
mockGit = createMockGit();
|
||||
addCommand = new GitAddCommand({
|
||||
git: mockGit,
|
||||
fs: mockFS,
|
||||
pwd: testCwd,
|
||||
});
|
||||
});
|
||||
|
||||
it('should have correct command properties', () => {
|
||||
expect(addCommand.name).toBe('add');
|
||||
expect(addCommand.description).toBe('Add file contents to the index');
|
||||
expect(addCommand.usage).toBe('git add [--all | -A] [--] [<pathspec>...]');
|
||||
});
|
||||
|
||||
it('should return error when not in a git repository', async () => {
|
||||
// Mock stat to throw error for .git directory
|
||||
vi.mocked(mockFS.stat).mockRejectedValueOnce(new Error('ENOENT'));
|
||||
|
||||
const result = await addCommand.execute(['file.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('fatal: not a git repository');
|
||||
});
|
||||
|
||||
it('should return error when no files specified', async () => {
|
||||
const result = await addCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('Nothing specified, nothing added');
|
||||
expect(result.stderr).toContain('Maybe you wanted to say \'git add .\'?');
|
||||
});
|
||||
|
||||
it('should add all modified files with --all flag', async () => {
|
||||
// Mock status matrix with modified and untracked files
|
||||
// [filepath, headStatus, workdirStatus, stageStatus]
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['modified.txt', 1, 2, 1], // Modified file (not staged)
|
||||
['untracked.txt', 0, 2, 0], // Untracked file
|
||||
['unchanged.txt', 1, 1, 1], // Unchanged file
|
||||
['staged.txt', 1, 2, 2], // Already staged file
|
||||
]);
|
||||
|
||||
const result = await addCommand.execute(['--all']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe(''); // Git add is silent on success
|
||||
|
||||
// Should add modified and untracked files, but not unchanged or already staged
|
||||
expect(mockGit.add).toHaveBeenCalledWith({
|
||||
dir: testCwd,
|
||||
filepath: 'modified.txt',
|
||||
});
|
||||
expect(mockGit.add).toHaveBeenCalledWith({
|
||||
dir: testCwd,
|
||||
filepath: 'untracked.txt',
|
||||
});
|
||||
expect(mockGit.add).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('should handle deleted files with --all flag', async () => {
|
||||
// Mock status matrix with deleted file
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['deleted.txt', 1, 0, 1], // Deleted file (not staged)
|
||||
]);
|
||||
|
||||
const result = await addCommand.execute(['--all']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
|
||||
// Should remove the deleted file
|
||||
expect(mockGit.remove).toHaveBeenCalledWith({
|
||||
dir: testCwd,
|
||||
filepath: 'deleted.txt',
|
||||
});
|
||||
expect(mockGit.remove).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should add specific file', async () => {
|
||||
const result = await addCommand.execute(['file.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
|
||||
expect(mockGit.add).toHaveBeenCalledWith({
|
||||
dir: testCwd,
|
||||
filepath: 'file.txt',
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle git add . (current directory)', async () => {
|
||||
// Mock status matrix with various files
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['file1.txt', 1, 2, 1], // Modified file
|
||||
['file2.txt', 0, 2, 0], // Untracked file
|
||||
['deleted.txt', 1, 0, 1], // Deleted file
|
||||
]);
|
||||
|
||||
const result = await addCommand.execute(['.']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
|
||||
// Should add modified and untracked files
|
||||
expect(mockGit.add).toHaveBeenCalledWith({
|
||||
dir: testCwd,
|
||||
filepath: 'file1.txt',
|
||||
});
|
||||
expect(mockGit.add).toHaveBeenCalledWith({
|
||||
dir: testCwd,
|
||||
filepath: 'file2.txt',
|
||||
});
|
||||
|
||||
// Should remove deleted file
|
||||
expect(mockGit.remove).toHaveBeenCalledWith({
|
||||
dir: testCwd,
|
||||
filepath: 'deleted.txt',
|
||||
});
|
||||
});
|
||||
|
||||
it('should reject absolute paths', async () => {
|
||||
const result = await addCommand.execute(['/absolute/path/file.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('absolute paths are not supported');
|
||||
});
|
||||
|
||||
it('should handle non-existent files', async () => {
|
||||
// Mock stat to throw error for non-existent file
|
||||
vi.mocked(mockFS.stat).mockImplementation((path: string) => {
|
||||
if (path.endsWith('/.git')) {
|
||||
return Promise.resolve({
|
||||
isDirectory: () => true,
|
||||
isFile: () => false,
|
||||
size: 0,
|
||||
mtimeMs: Date.now(),
|
||||
});
|
||||
}
|
||||
if (path.includes('nonexistent')) {
|
||||
throw new Error('ENOENT');
|
||||
}
|
||||
return Promise.resolve({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
size: 100,
|
||||
mtimeMs: Date.now(),
|
||||
});
|
||||
});
|
||||
|
||||
// Mock git.remove to also throw error (file doesn't exist in git either)
|
||||
vi.mocked(mockGit.remove).mockRejectedValueOnce(new Error('File not found'));
|
||||
|
||||
const result = await addCommand.execute(['nonexistent.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('pathspec \'nonexistent.txt\' did not match any files');
|
||||
});
|
||||
|
||||
it('should handle -A flag (same as --all)', async () => {
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['modified.txt', 1, 2, 1], // Modified file
|
||||
]);
|
||||
|
||||
const result = await addCommand.execute(['-A']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
|
||||
expect(mockGit.add).toHaveBeenCalledWith({
|
||||
dir: testCwd,
|
||||
filepath: 'modified.txt',
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle mixed options and paths', async () => {
|
||||
// Mock status matrix for --all to work
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['modified.txt', 1, 2, 1], // Modified file
|
||||
]);
|
||||
|
||||
const result = await addCommand.execute(['--all', 'specific.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
|
||||
// When --all is specified, it should ignore specific paths and add all files
|
||||
expect(mockGit.statusMatrix).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should handle double dash separator', async () => {
|
||||
const result = await addCommand.execute(['--', 'file.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
|
||||
expect(mockGit.add).toHaveBeenCalledWith({
|
||||
dir: testCwd,
|
||||
filepath: 'file.txt',
|
||||
});
|
||||
});
|
||||
|
||||
it('should continue with other files if one fails', async () => {
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['good.txt', 1, 2, 1], // This should succeed
|
||||
['bad.txt', 1, 2, 1], // This will fail
|
||||
]);
|
||||
|
||||
// Mock git.add to fail for bad.txt but succeed for good.txt
|
||||
vi.mocked(mockGit.add).mockImplementation(({ filepath }) => {
|
||||
if (filepath === 'bad.txt') {
|
||||
throw new Error('Permission denied');
|
||||
}
|
||||
return Promise.resolve();
|
||||
});
|
||||
|
||||
const result = await addCommand.execute(['--all']);
|
||||
|
||||
expect(result.exitCode).toBe(0); // Should still succeed overall
|
||||
expect(mockGit.add).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
+20
-39
@@ -77,27 +77,22 @@ export class GitAddCommand implements GitSubcommand {
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
let addedCount = 0;
|
||||
let removedCount = 0;
|
||||
|
||||
for (const [filepath, headStatus, workdirStatus] of statusMatrix) {
|
||||
for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) {
|
||||
try {
|
||||
if (workdirStatus === 0 && headStatus === 1) {
|
||||
// File was deleted
|
||||
// File was deleted in working directory
|
||||
await this.git.remove({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
filepath,
|
||||
});
|
||||
removedCount++;
|
||||
} else if (workdirStatus === 1) {
|
||||
// File exists (new or modified)
|
||||
} else if (workdirStatus === 2 && stageStatus !== 2) {
|
||||
// File exists and has changes that aren't staged yet
|
||||
await this.git.add({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
filepath,
|
||||
});
|
||||
addedCount++;
|
||||
}
|
||||
} catch {
|
||||
// Continue with other files if one fails
|
||||
@@ -105,19 +100,8 @@ export class GitAddCommand implements GitSubcommand {
|
||||
}
|
||||
}
|
||||
|
||||
const messages: string[] = [];
|
||||
if (addedCount > 0) {
|
||||
messages.push(`Added ${addedCount} file${addedCount !== 1 ? 's' : ''}`);
|
||||
}
|
||||
if (removedCount > 0) {
|
||||
messages.push(`Removed ${removedCount} file${removedCount !== 1 ? 's' : ''}`);
|
||||
}
|
||||
|
||||
if (messages.length === 0) {
|
||||
return createSuccessResult('');
|
||||
}
|
||||
|
||||
return createSuccessResult(messages.join(', ') + '\n');
|
||||
// Git add is typically silent on success, like real git
|
||||
return createSuccessResult('');
|
||||
|
||||
} catch (error) {
|
||||
return createErrorResult(`Failed to add all files: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
@@ -133,24 +117,24 @@ export class GitAddCommand implements GitSubcommand {
|
||||
if (path === '.') {
|
||||
// Add current directory (all files in it)
|
||||
const statusMatrix = await this.git.statusMatrix({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
for (const [filepath, headStatus, workdirStatus] of statusMatrix) {
|
||||
for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) {
|
||||
try {
|
||||
if (workdirStatus === 0 && headStatus === 1) {
|
||||
// File was deleted
|
||||
// File was deleted in working directory
|
||||
await this.git.remove({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
filepath,
|
||||
});
|
||||
addedFiles.push(filepath);
|
||||
} else if (workdirStatus === 1) {
|
||||
// File exists
|
||||
} else if (workdirStatus === 2 && stageStatus !== 2) {
|
||||
// File exists and has changes that aren't staged yet
|
||||
await this.git.add({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
filepath,
|
||||
});
|
||||
@@ -179,7 +163,7 @@ export class GitAddCommand implements GitSubcommand {
|
||||
} else {
|
||||
// Add single file
|
||||
await this.git.add({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
filepath: path,
|
||||
});
|
||||
@@ -189,7 +173,7 @@ export class GitAddCommand implements GitSubcommand {
|
||||
// Check if it's a deleted file
|
||||
try {
|
||||
await this.git.remove({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
filepath: path,
|
||||
});
|
||||
@@ -208,11 +192,8 @@ export class GitAddCommand implements GitSubcommand {
|
||||
return createErrorResult(errors.join('\n'));
|
||||
}
|
||||
|
||||
if (addedFiles.length === 0) {
|
||||
return createSuccessResult('');
|
||||
}
|
||||
|
||||
return createSuccessResult(`Added ${addedFiles.length} file${addedFiles.length !== 1 ? 's' : ''}\n`);
|
||||
// Git add is typically silent on success, like real git
|
||||
return createSuccessResult('');
|
||||
}
|
||||
|
||||
private async addDirectory(dirPath: string, addedFiles: string[]): Promise<void> {
|
||||
@@ -231,7 +212,7 @@ export class GitAddCommand implements GitSubcommand {
|
||||
} else {
|
||||
try {
|
||||
await this.git.add({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
filepath: entryPath,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { GitDiffCommand } from './diff';
|
||||
import type { GitSubcommandOptions } from '../git';
|
||||
import type { Git } from '../../git';
|
||||
import type { JSRuntimeFS } from '../../JSRuntime';
|
||||
|
||||
// Mock implementations
|
||||
const mockGit = {
|
||||
statusMatrix: async () => [
|
||||
// [filepath, headStatus, workdirStatus, stageStatus]
|
||||
['modified.txt', 1, 2, 1], // Modified in working dir
|
||||
['staged.txt', 1, 1, 2], // Modified in stage
|
||||
['new.txt', 0, 2, 0], // Untracked file
|
||||
['deleted.txt', 1, 0, 1], // Deleted in working dir
|
||||
],
|
||||
readBlob: async ({ filepath }: { filepath: string }) => {
|
||||
const content = {
|
||||
'modified.txt': 'original content\nline 2',
|
||||
'staged.txt': 'original staged content',
|
||||
'deleted.txt': 'deleted file content',
|
||||
}[filepath] || '';
|
||||
return { blob: new TextEncoder().encode(content) };
|
||||
},
|
||||
log: async () => [],
|
||||
} as unknown as Git;
|
||||
|
||||
const mockFS = {
|
||||
stat: async (path: string) => {
|
||||
if (path.endsWith('/.git')) {
|
||||
return { isDirectory: () => true };
|
||||
}
|
||||
throw new Error('File not found');
|
||||
},
|
||||
readFile: async (path: string) => {
|
||||
const filename = path.split('/').pop();
|
||||
const content = {
|
||||
'modified.txt': 'modified content\nline 2\nnew line',
|
||||
'staged.txt': 'staged content modified',
|
||||
'new.txt': 'this is a new file',
|
||||
// deleted.txt is not in working dir
|
||||
}[filename || ''];
|
||||
|
||||
if (!content) {
|
||||
throw new Error('File not found');
|
||||
}
|
||||
return content;
|
||||
},
|
||||
} as unknown as JSRuntimeFS;
|
||||
|
||||
const mockOptions: GitSubcommandOptions = {
|
||||
git: mockGit,
|
||||
fs: mockFS,
|
||||
pwd: '/test/repo',
|
||||
};
|
||||
|
||||
describe('GitDiffCommand', () => {
|
||||
let command: GitDiffCommand;
|
||||
|
||||
beforeEach(() => {
|
||||
command = new GitDiffCommand(mockOptions);
|
||||
});
|
||||
|
||||
describe('parseArgs', () => {
|
||||
type ParseArgsResult = {
|
||||
commits: string[];
|
||||
paths: string[];
|
||||
options: { cached: boolean; staged: boolean };
|
||||
};
|
||||
|
||||
it('should parse no arguments correctly', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs([]);
|
||||
expect(result).toEqual({
|
||||
commits: [],
|
||||
paths: [],
|
||||
options: { cached: false, staged: false },
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse --cached option', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['--cached']);
|
||||
expect(result).toEqual({
|
||||
commits: [],
|
||||
paths: [],
|
||||
options: { cached: true, staged: true },
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse commits and paths', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['HEAD~1', 'HEAD', '--', 'file.txt']);
|
||||
expect(result).toEqual({
|
||||
commits: ['HEAD~1', 'HEAD'],
|
||||
paths: ['file.txt'],
|
||||
options: { cached: false, staged: false },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('execute', () => {
|
||||
it('should fail when not in a git repository', async () => {
|
||||
const commandWithoutGit = new GitDiffCommand({
|
||||
...mockOptions,
|
||||
fs: {
|
||||
stat: async () => {
|
||||
throw new Error('File not found');
|
||||
},
|
||||
} as unknown as JSRuntimeFS,
|
||||
});
|
||||
|
||||
const result = await commandWithoutGit.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('fatal: not a git repository');
|
||||
});
|
||||
|
||||
it('should show working directory diff for modified files', async () => {
|
||||
const result = await command.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('diff --git a/modified.txt b/modified.txt');
|
||||
expect(result.stdout).toContain('--- a/modified.txt');
|
||||
expect(result.stdout).toContain('+++ b/modified.txt');
|
||||
expect(result.stdout).toContain('-original content');
|
||||
expect(result.stdout).toContain('+modified content');
|
||||
expect(result.stdout).toContain('+new line');
|
||||
});
|
||||
|
||||
it('should NOT show untracked files in diff', async () => {
|
||||
const result = await command.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
// Untracked files should not appear in git diff output
|
||||
expect(result.stdout).not.toContain('diff --git a/new.txt b/new.txt');
|
||||
expect(result.stdout).not.toContain('new file mode 100644');
|
||||
expect(result.stdout).not.toContain('+this is a new file');
|
||||
});
|
||||
|
||||
it('should show deleted files in diff', async () => {
|
||||
const result = await command.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('diff --git a/deleted.txt b/deleted.txt');
|
||||
expect(result.stdout).toContain('deleted file mode 100644');
|
||||
expect(result.stdout).toContain('--- a/deleted.txt');
|
||||
expect(result.stdout).toContain('+++ /dev/null');
|
||||
expect(result.stdout).toContain('-deleted file content');
|
||||
});
|
||||
|
||||
it('should show staged diff with --cached option', async () => {
|
||||
const result = await command.execute(['--cached']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('diff --git a/staged.txt b/staged.txt');
|
||||
expect(result.stdout).toContain('--- a/staged.txt');
|
||||
expect(result.stdout).toContain('+++ b/staged.txt');
|
||||
});
|
||||
|
||||
it('should show newly added files in staged diff', async () => {
|
||||
// Test with a file that was added to the index (new file staged)
|
||||
const commandWithStagedNew = new GitDiffCommand({
|
||||
...mockOptions,
|
||||
git: {
|
||||
...mockGit,
|
||||
statusMatrix: async () => [
|
||||
['new-staged.txt', 0, 1, 2], // New file added to stage
|
||||
],
|
||||
} as unknown as Git,
|
||||
});
|
||||
|
||||
const result = await commandWithStagedNew.execute(['--cached']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('diff --git a/new-staged.txt b/new-staged.txt');
|
||||
expect(result.stdout).toContain('new file mode 100644');
|
||||
expect(result.stdout).toContain('--- /dev/null');
|
||||
expect(result.stdout).toContain('+++ b/new-staged.txt');
|
||||
});
|
||||
|
||||
it('should return empty output when no changes', async () => {
|
||||
const commandWithNoChanges = new GitDiffCommand({
|
||||
...mockOptions,
|
||||
git: {
|
||||
...mockGit,
|
||||
statusMatrix: async () => [],
|
||||
} as unknown as Git,
|
||||
});
|
||||
|
||||
const result = await commandWithNoChanges.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
});
|
||||
|
||||
it('should filter by path when specified', async () => {
|
||||
const result = await command.execute(['--', 'modified.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('diff --git a/modified.txt b/modified.txt');
|
||||
expect(result.stdout).not.toContain('new.txt');
|
||||
expect(result.stdout).not.toContain('deleted.txt');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -91,10 +91,13 @@ export class GitDiffCommand implements GitSubcommand {
|
||||
|
||||
// Filter for files with working directory changes
|
||||
// Status matrix: [filepath, headStatus, workdirStatus, stageStatus]
|
||||
// 0 = absent, 1 = present, 2 = modified
|
||||
// 0 = absent, 1 = same as previous stage, 2 = different from previous stage
|
||||
const changedFiles = statusMatrix.filter(([filepath, _headStatus, workdirStatus, stageStatus]) => {
|
||||
// Show files that differ between index and working directory
|
||||
const hasWorkingDirChanges = stageStatus !== workdirStatus;
|
||||
// Show files that have working directory changes (differ from index)
|
||||
// Exclude untracked files - git diff only shows changes to tracked files
|
||||
const hasWorkingDirChanges = (stageStatus !== workdirStatus && workdirStatus === 2 && stageStatus !== 0) ||
|
||||
(stageStatus === 2 && workdirStatus === 0) ||
|
||||
(stageStatus === 1 && workdirStatus === 0);
|
||||
|
||||
if (paths.length > 0) {
|
||||
return hasWorkingDirChanges && paths.some(path => filepath.includes(path));
|
||||
@@ -110,79 +113,87 @@ export class GitDiffCommand implements GitSubcommand {
|
||||
|
||||
for (const [filepath, _headStatus, workdirStatus, stageStatus] of changedFiles) {
|
||||
try {
|
||||
// Get staged content (index)
|
||||
let stagedContent = '';
|
||||
if (stageStatus === 1) {
|
||||
// Get staged/index content
|
||||
let indexContent = '';
|
||||
if (stageStatus === 1 || stageStatus === 2) {
|
||||
try {
|
||||
// Try to read from HEAD first as a fallback for staged content
|
||||
// For files in the index, read from HEAD as the baseline
|
||||
// This represents the last committed version for comparison
|
||||
const headBlob = await this.git.readBlob({
|
||||
dir: this.pwd,
|
||||
oid: 'HEAD',
|
||||
filepath,
|
||||
});
|
||||
stagedContent = new TextDecoder().decode(headBlob.blob);
|
||||
indexContent = new TextDecoder().decode(headBlob.blob);
|
||||
} catch {
|
||||
// File might be new
|
||||
stagedContent = '';
|
||||
// File might be new or not in HEAD
|
||||
indexContent = '';
|
||||
}
|
||||
}
|
||||
|
||||
// Get working directory content
|
||||
let workdirContent = '';
|
||||
if (workdirStatus === 1) {
|
||||
if (workdirStatus === 2) {
|
||||
try {
|
||||
workdirContent = await this.fs.readFile(`${this.pwd}/${filepath}`, 'utf8');
|
||||
} catch {
|
||||
// File might be deleted
|
||||
workdirContent = '';
|
||||
}
|
||||
} else if (workdirStatus === 0) {
|
||||
// File is deleted in working directory
|
||||
workdirContent = '';
|
||||
}
|
||||
|
||||
// Skip if contents are identical
|
||||
if (stagedContent === workdirContent) {
|
||||
if (indexContent === workdirContent) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Generate diff header
|
||||
diffLines.push(`diff --git a/${filepath} b/${filepath}`);
|
||||
|
||||
if (stageStatus === 0 && workdirStatus === 1) {
|
||||
// New untracked file
|
||||
diffLines.push('new file mode 100644');
|
||||
diffLines.push(`index 0000000..${this.getShortHash(workdirContent)}`);
|
||||
diffLines.push('--- /dev/null');
|
||||
diffLines.push(`+++ b/${filepath}`);
|
||||
} else if (stageStatus === 1 && workdirStatus === 0) {
|
||||
if (workdirStatus === 0 && (stageStatus === 1 || stageStatus === 2)) {
|
||||
// Deleted file
|
||||
diffLines.push('deleted file mode 100644');
|
||||
diffLines.push(`index ${this.getShortHash(stagedContent)}..0000000`);
|
||||
diffLines.push(`index ${this.getShortHash(indexContent)}..0000000`);
|
||||
diffLines.push(`--- a/${filepath}`);
|
||||
diffLines.push('+++ /dev/null');
|
||||
} else {
|
||||
// Modified file
|
||||
diffLines.push(`index ${this.getShortHash(stagedContent)}..${this.getShortHash(workdirContent)} 100644`);
|
||||
diffLines.push(`index ${this.getShortHash(indexContent)}..${this.getShortHash(workdirContent)} 100644`);
|
||||
diffLines.push(`--- a/${filepath}`);
|
||||
diffLines.push(`+++ b/${filepath}`);
|
||||
}
|
||||
|
||||
// Generate simple unified diff
|
||||
const stagedLines = stagedContent.split('\n');
|
||||
// Generate unified diff
|
||||
const indexLines = indexContent.split('\n');
|
||||
const workdirLines = workdirContent.split('\n');
|
||||
|
||||
// Simple hunk header
|
||||
diffLines.push(`@@ -1,${stagedLines.length} +1,${workdirLines.length} @@`);
|
||||
diffLines.push(`@@ -1,${indexLines.length} +1,${workdirLines.length} @@`);
|
||||
|
||||
// Show all old lines as removed
|
||||
for (const line of stagedLines) {
|
||||
if (line || stagedLines.length > 0) {
|
||||
diffLines.push(`-${line}`);
|
||||
}
|
||||
}
|
||||
// Simple line-by-line diff
|
||||
const maxLines = Math.max(indexLines.length, workdirLines.length);
|
||||
for (let i = 0; i < maxLines; i++) {
|
||||
const oldLine = indexLines[i];
|
||||
const newLine = workdirLines[i];
|
||||
|
||||
// Show all new lines as added
|
||||
for (const line of workdirLines) {
|
||||
if (line || workdirLines.length > 0) {
|
||||
diffLines.push(`+${line}`);
|
||||
if (oldLine !== undefined && newLine !== undefined) {
|
||||
if (oldLine === newLine) {
|
||||
// Unchanged line (show context)
|
||||
diffLines.push(` ${oldLine}`);
|
||||
} else {
|
||||
// Changed line
|
||||
diffLines.push(`-${oldLine}`);
|
||||
diffLines.push(`+${newLine}`);
|
||||
}
|
||||
} else if (oldLine !== undefined) {
|
||||
// Removed line
|
||||
diffLines.push(`-${oldLine}`);
|
||||
} else if (newLine !== undefined) {
|
||||
// Added line
|
||||
diffLines.push(`+${newLine}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -248,7 +259,9 @@ export class GitDiffCommand implements GitSubcommand {
|
||||
|
||||
// Filter for files with staged changes (index differs from HEAD)
|
||||
const stagedFiles = statusMatrix.filter(([filepath, headStatus, _workdirStatus, stageStatus]) => {
|
||||
const hasStagedChanges = headStatus !== stageStatus;
|
||||
const hasStagedChanges = (headStatus === 0 && stageStatus === 2) || // Added to stage
|
||||
(headStatus === 1 && stageStatus === 0) || // Deleted from stage
|
||||
(headStatus === 1 && stageStatus === 2); // Modified in stage
|
||||
|
||||
if (paths.length > 0) {
|
||||
return hasStagedChanges && paths.some(path => filepath.includes(path));
|
||||
@@ -281,7 +294,7 @@ export class GitDiffCommand implements GitSubcommand {
|
||||
|
||||
// Get staged content (approximated by working directory for now)
|
||||
let stagedContent = '';
|
||||
if (stageStatus === 1) {
|
||||
if (stageStatus === 1 || stageStatus === 2) {
|
||||
try {
|
||||
stagedContent = await this.fs.readFile(`${this.pwd}/${filepath}`, 'utf8');
|
||||
} catch {
|
||||
@@ -292,7 +305,7 @@ export class GitDiffCommand implements GitSubcommand {
|
||||
// Generate diff header
|
||||
diffLines.push(`diff --git a/${filepath} b/${filepath}`);
|
||||
|
||||
if (headStatus === 0 && stageStatus === 1) {
|
||||
if (headStatus === 0 && stageStatus === 2) {
|
||||
// New file staged
|
||||
diffLines.push('new file mode 100644');
|
||||
diffLines.push(`index 0000000..${this.getShortHash(stagedContent)}`);
|
||||
@@ -317,14 +330,28 @@ export class GitDiffCommand implements GitSubcommand {
|
||||
|
||||
diffLines.push(`@@ -1,${headLines.length} +1,${stagedLines.length} @@`);
|
||||
|
||||
// Show removed lines
|
||||
for (const line of headLines) {
|
||||
diffLines.push(`-${line}`);
|
||||
}
|
||||
// Simple line-by-line diff
|
||||
const maxLines = Math.max(headLines.length, stagedLines.length);
|
||||
for (let i = 0; i < maxLines; i++) {
|
||||
const oldLine = headLines[i];
|
||||
const newLine = stagedLines[i];
|
||||
|
||||
// Show added lines
|
||||
for (const line of stagedLines) {
|
||||
diffLines.push(`+${line}`);
|
||||
if (oldLine !== undefined && newLine !== undefined) {
|
||||
if (oldLine === newLine) {
|
||||
// Unchanged line (show context)
|
||||
diffLines.push(` ${oldLine}`);
|
||||
} else {
|
||||
// Changed line
|
||||
diffLines.push(`-${oldLine}`);
|
||||
diffLines.push(`+${newLine}`);
|
||||
}
|
||||
} else if (oldLine !== undefined) {
|
||||
// Removed line
|
||||
diffLines.push(`-${oldLine}`);
|
||||
} else if (newLine !== undefined) {
|
||||
// Added line
|
||||
diffLines.push(`+${newLine}`);
|
||||
}
|
||||
}
|
||||
|
||||
diffLines.push('');
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { GitFetchCommand } from './fetch';
|
||||
import type { GitSubcommandOptions } from '../git';
|
||||
import type { Git } from '../../git';
|
||||
import type { JSRuntimeFS } from '../../JSRuntime';
|
||||
|
||||
// Mock implementations
|
||||
const mockGit = {
|
||||
listRemotes: async () => [
|
||||
{ remote: 'origin', url: 'https://github.com/user/repo.git' },
|
||||
{ remote: 'upstream', url: 'https://github.com/upstream/repo.git' }
|
||||
],
|
||||
fetch: async () => {},
|
||||
resolveRef: async () => 'abc123def456',
|
||||
} as unknown as Git;
|
||||
|
||||
const mockFS = {
|
||||
stat: async (path: string) => {
|
||||
if (path.endsWith('/.git')) {
|
||||
return { isDirectory: () => true };
|
||||
}
|
||||
throw new Error('File not found');
|
||||
},
|
||||
} as unknown as JSRuntimeFS;
|
||||
|
||||
const mockOptions: GitSubcommandOptions = {
|
||||
git: mockGit,
|
||||
fs: mockFS,
|
||||
pwd: '/test/repo',
|
||||
};
|
||||
|
||||
describe('GitFetchCommand', () => {
|
||||
let command: GitFetchCommand;
|
||||
|
||||
beforeEach(() => {
|
||||
command = new GitFetchCommand(mockOptions);
|
||||
});
|
||||
|
||||
describe('parseArgs', () => {
|
||||
type ParseArgsResult = {
|
||||
remote: string;
|
||||
refs: string[];
|
||||
options: {
|
||||
all: boolean;
|
||||
tags: boolean;
|
||||
prune: boolean;
|
||||
verbose: boolean;
|
||||
};
|
||||
};
|
||||
|
||||
it('should parse no arguments correctly', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs([]);
|
||||
expect(result).toEqual({
|
||||
remote: 'origin',
|
||||
refs: [],
|
||||
options: {
|
||||
all: false,
|
||||
tags: false,
|
||||
prune: false,
|
||||
verbose: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse remote only', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['upstream']);
|
||||
expect(result).toEqual({
|
||||
remote: 'upstream',
|
||||
refs: [],
|
||||
options: {
|
||||
all: false,
|
||||
tags: false,
|
||||
prune: false,
|
||||
verbose: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse remote and refs', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['origin', 'main', 'develop']);
|
||||
expect(result).toEqual({
|
||||
remote: 'origin',
|
||||
refs: ['main', 'develop'],
|
||||
options: {
|
||||
all: false,
|
||||
tags: false,
|
||||
prune: false,
|
||||
verbose: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse options correctly', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['--all', '--tags', '--prune', '--verbose']);
|
||||
expect(result).toEqual({
|
||||
remote: 'origin',
|
||||
refs: [],
|
||||
options: {
|
||||
all: true,
|
||||
tags: true,
|
||||
prune: true,
|
||||
verbose: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse short options', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['-p', '-v']);
|
||||
expect(result).toEqual({
|
||||
remote: 'origin',
|
||||
refs: [],
|
||||
options: {
|
||||
all: false,
|
||||
tags: false,
|
||||
prune: true,
|
||||
verbose: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse mixed arguments and options', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['upstream', '--verbose', 'main', '--tags']);
|
||||
expect(result).toEqual({
|
||||
remote: 'upstream',
|
||||
refs: ['main'],
|
||||
options: {
|
||||
all: false,
|
||||
tags: true,
|
||||
prune: false,
|
||||
verbose: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('execute', () => {
|
||||
it('should fail when not in a git repository', async () => {
|
||||
const commandWithoutGit = new GitFetchCommand({
|
||||
...mockOptions,
|
||||
fs: {
|
||||
stat: async () => {
|
||||
throw new Error('File not found');
|
||||
},
|
||||
} as unknown as JSRuntimeFS,
|
||||
});
|
||||
|
||||
const result = await commandWithoutGit.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('fatal: not a git repository');
|
||||
});
|
||||
|
||||
it('should fail when remote does not exist', async () => {
|
||||
const result = await command.execute(['nonexistent']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain("fatal: 'nonexistent' does not appear to be a git repository");
|
||||
});
|
||||
|
||||
it('should fetch from default remote successfully', async () => {
|
||||
const result = await command.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('From https://github.com/user/repo.git');
|
||||
expect(result.stdout).toContain('refs/heads/* -> refs/remotes/origin/*');
|
||||
});
|
||||
|
||||
it('should fetch from specific remote successfully', async () => {
|
||||
const result = await command.execute(['upstream']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('From https://github.com/upstream/repo.git');
|
||||
expect(result.stdout).toContain('refs/heads/* -> refs/remotes/upstream/*');
|
||||
});
|
||||
|
||||
it('should fetch specific refs successfully', async () => {
|
||||
const result = await command.execute(['origin', 'main']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('From https://github.com/user/repo.git');
|
||||
expect(result.stdout).toContain('* branch main -> origin/main');
|
||||
});
|
||||
|
||||
it('should fetch multiple specific refs successfully', async () => {
|
||||
const result = await command.execute(['origin', 'main', 'develop']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('From https://github.com/user/repo.git');
|
||||
expect(result.stdout).toContain('* branch main -> origin/main');
|
||||
expect(result.stdout).toContain('* branch develop -> origin/develop');
|
||||
});
|
||||
|
||||
it('should handle authentication errors', async () => {
|
||||
const commandWithAuthError = new GitFetchCommand({
|
||||
...mockOptions,
|
||||
git: {
|
||||
...mockGit,
|
||||
fetch: async () => {
|
||||
throw new Error('authentication failed');
|
||||
},
|
||||
} as unknown as Git,
|
||||
});
|
||||
|
||||
const result = await commandWithAuthError.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('fatal: Authentication failed');
|
||||
});
|
||||
|
||||
it('should handle network errors', async () => {
|
||||
const commandWithNetworkError = new GitFetchCommand({
|
||||
...mockOptions,
|
||||
git: {
|
||||
...mockGit,
|
||||
fetch: async () => {
|
||||
throw new Error('network error');
|
||||
},
|
||||
} as unknown as Git,
|
||||
});
|
||||
|
||||
const result = await commandWithNetworkError.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('fatal: unable to access remote repository');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,173 @@
|
||||
import type { JSRuntimeFS } from "../../JSRuntime";
|
||||
import type { ShellCommandResult } from "../ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "../ShellCommand";
|
||||
import type { GitSubcommand, GitSubcommandOptions } from "../git";
|
||||
import type { Git } from "../../git";
|
||||
|
||||
export class GitFetchCommand implements GitSubcommand {
|
||||
name = 'fetch';
|
||||
description = 'Download objects and refs from another repository';
|
||||
usage = 'git fetch [<remote>] [<refspec>...]';
|
||||
|
||||
private git: Git;
|
||||
private fs: JSRuntimeFS;
|
||||
private pwd: string;
|
||||
|
||||
constructor(options: GitSubcommandOptions) {
|
||||
this.git = options.git;
|
||||
this.fs = options.fs;
|
||||
this.pwd = options.pwd;
|
||||
}
|
||||
|
||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Check if we're in a git repository
|
||||
try {
|
||||
await this.fs.stat(`${this.pwd}/.git`);
|
||||
} catch {
|
||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||
}
|
||||
|
||||
const { remote, refs } = this.parseArgs(args);
|
||||
|
||||
// Get remote URL
|
||||
let remoteUrl: string;
|
||||
try {
|
||||
const remotes = await this.git.listRemotes({
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
const targetRemote = remotes.find(r => r.remote === remote);
|
||||
if (!targetRemote) {
|
||||
return createErrorResult(`fatal: '${remote}' does not appear to be a git repository`);
|
||||
}
|
||||
remoteUrl = targetRemote.url;
|
||||
} catch {
|
||||
return createErrorResult(`fatal: '${remote}' does not appear to be a git repository`);
|
||||
}
|
||||
|
||||
try {
|
||||
// If specific refs are provided, fetch them; otherwise fetch all refs
|
||||
if (refs.length > 0) {
|
||||
// Fetch specific refs
|
||||
for (const ref of refs) {
|
||||
await this.git.fetch({
|
||||
dir: this.pwd,
|
||||
remote: remote,
|
||||
ref: ref,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// Fetch all refs (default behavior)
|
||||
await this.git.fetch({
|
||||
dir: this.pwd,
|
||||
remote: remote,
|
||||
});
|
||||
}
|
||||
|
||||
// Build output message
|
||||
const lines: string[] = [];
|
||||
lines.push(`From ${remoteUrl}`);
|
||||
|
||||
if (refs.length > 0) {
|
||||
// Show specific refs that were fetched
|
||||
for (const ref of refs) {
|
||||
try {
|
||||
await this.git.resolveRef({
|
||||
dir: this.pwd,
|
||||
ref: `refs/remotes/${remote}/${ref}`,
|
||||
});
|
||||
lines.push(` * branch ${ref} -> ${remote}/${ref}`);
|
||||
} catch {
|
||||
// If we can't resolve the ref, it might be a tag or other ref type
|
||||
lines.push(` * [new ref] ${ref} -> ${remote}/${ref}`);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// For fetch without specific refs, we'll show a generic message
|
||||
lines.push(` * [new refs] refs/heads/* -> refs/remotes/${remote}/*`);
|
||||
}
|
||||
|
||||
return createSuccessResult(lines.join('\n') + '\n');
|
||||
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes('authentication')) {
|
||||
return createErrorResult('fatal: Authentication failed. Please configure git credentials.');
|
||||
} else if (error.message.includes('network')) {
|
||||
return createErrorResult('fatal: unable to access remote repository. Please check your network connection.');
|
||||
} else if (error.message.includes('not found')) {
|
||||
return createErrorResult(`fatal: remote ref not found`);
|
||||
}
|
||||
}
|
||||
|
||||
return createErrorResult(`Failed to fetch: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
return createErrorResult(`git fetch: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
|
||||
private parseArgs(args: string[]): {
|
||||
remote: string;
|
||||
refs: string[];
|
||||
options: {
|
||||
all: boolean;
|
||||
tags: boolean;
|
||||
prune: boolean;
|
||||
verbose: boolean;
|
||||
}
|
||||
} {
|
||||
let remote = 'origin'; // Default remote
|
||||
const refs: string[] = [];
|
||||
const options = {
|
||||
all: false,
|
||||
tags: false,
|
||||
prune: false,
|
||||
verbose: false,
|
||||
};
|
||||
|
||||
const nonOptionArgs: string[] = [];
|
||||
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const arg = args[i];
|
||||
|
||||
if (arg.startsWith('-')) {
|
||||
// Handle options
|
||||
switch (arg) {
|
||||
case '--all':
|
||||
options.all = true;
|
||||
break;
|
||||
case '--tags':
|
||||
options.tags = true;
|
||||
break;
|
||||
case '--prune':
|
||||
case '-p':
|
||||
options.prune = true;
|
||||
break;
|
||||
case '--verbose':
|
||||
case '-v':
|
||||
options.verbose = true;
|
||||
break;
|
||||
default:
|
||||
// Ignore unknown options for now
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
nonOptionArgs.push(arg);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse non-option arguments
|
||||
if (nonOptionArgs.length >= 1) {
|
||||
remote = nonOptionArgs[0];
|
||||
}
|
||||
if (nonOptionArgs.length >= 2) {
|
||||
// All remaining args are refs/refspecs
|
||||
refs.push(...nonOptionArgs.slice(1));
|
||||
}
|
||||
|
||||
return { remote, refs, options };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { GitPullCommand } from './pull';
|
||||
import type { GitSubcommandOptions } from '../git';
|
||||
import type { Git } from '../../git';
|
||||
import type { JSRuntimeFS } from '../../JSRuntime';
|
||||
|
||||
// Mock implementations
|
||||
const mockGit = {
|
||||
currentBranch: async () => 'main',
|
||||
listRemotes: async () => [{ remote: 'origin', url: 'https://github.com/user/repo.git' }],
|
||||
statusMatrix: async () => [],
|
||||
fetch: async () => {},
|
||||
resolveRef: async () => 'abc123',
|
||||
merge: async () => {},
|
||||
} as unknown as Git;
|
||||
|
||||
const mockFS = {
|
||||
stat: async () => ({ isDirectory: () => true }),
|
||||
} as unknown as JSRuntimeFS;
|
||||
|
||||
const mockOptions: GitSubcommandOptions = {
|
||||
git: mockGit,
|
||||
fs: mockFS,
|
||||
pwd: '/test/repo',
|
||||
};
|
||||
|
||||
describe('GitPullCommand', () => {
|
||||
let command: GitPullCommand;
|
||||
|
||||
beforeEach(() => {
|
||||
command = new GitPullCommand(mockOptions);
|
||||
});
|
||||
|
||||
describe('parseArgs', () => {
|
||||
it('should parse no arguments correctly', () => {
|
||||
// Access the private method for testing
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => { remote: string; branch?: string } }).parseArgs([]);
|
||||
expect(result).toEqual({
|
||||
remote: 'origin',
|
||||
branch: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse remote only', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => { remote: string; branch?: string } }).parseArgs(['upstream']);
|
||||
expect(result).toEqual({
|
||||
remote: 'upstream',
|
||||
branch: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse remote and branch correctly', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => { remote: string; branch?: string } }).parseArgs(['origin', 'main']);
|
||||
expect(result).toEqual({
|
||||
remote: 'origin',
|
||||
branch: 'main',
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse different remote and branch', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => { remote: string; branch?: string } }).parseArgs(['upstream', 'develop']);
|
||||
expect(result).toEqual({
|
||||
remote: 'upstream',
|
||||
branch: 'develop',
|
||||
});
|
||||
});
|
||||
|
||||
it('should ignore option flags', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => { remote: string; branch?: string } }).parseArgs(['--rebase', 'origin', '--verbose', 'main']);
|
||||
expect(result).toEqual({
|
||||
remote: 'origin',
|
||||
branch: 'main',
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle extra arguments beyond remote and branch', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => { remote: string; branch?: string } }).parseArgs(['origin', 'main', 'extra', 'args']);
|
||||
expect(result).toEqual({
|
||||
remote: 'origin',
|
||||
branch: 'main',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('execute', () => {
|
||||
it('should list modified files when there are uncommitted changes', async () => {
|
||||
// Mock statusMatrix to return some modified files
|
||||
const mockGitWithChanges = {
|
||||
...mockGit,
|
||||
statusMatrix: async () => [
|
||||
['src/index.ts', 1, 2, 1], // Modified file
|
||||
['README.md', 1, 2, 2], // Modified and staged
|
||||
['package.json', 0, 2, 0], // Untracked file
|
||||
],
|
||||
} as unknown as Git;
|
||||
|
||||
// Mock FS to ensure .git directory exists
|
||||
const mockFSWithGit = {
|
||||
stat: async (path: string) => {
|
||||
if (path.endsWith('/.git')) {
|
||||
return { isDirectory: () => true };
|
||||
}
|
||||
throw new Error('File not found');
|
||||
},
|
||||
} as unknown as JSRuntimeFS;
|
||||
|
||||
const commandWithChanges = new GitPullCommand({
|
||||
git: mockGitWithChanges,
|
||||
fs: mockFSWithGit,
|
||||
pwd: '/test/repo',
|
||||
});
|
||||
|
||||
const result = await commandWithChanges.execute(['origin', 'main']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('error: Your local changes to the following files would be overwritten by merge:');
|
||||
expect(result.stderr).toContain('\tsrc/index.ts');
|
||||
expect(result.stderr).toContain('\tREADME.md');
|
||||
expect(result.stderr).toContain('\tpackage.json');
|
||||
expect(result.stderr).toContain('Please commit your changes or stash them before you merge.');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -35,7 +35,7 @@ export class GitPullCommand implements GitSubcommand {
|
||||
let currentBranch: string | null = null;
|
||||
try {
|
||||
currentBranch = await this.git.currentBranch({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
}) || null;
|
||||
if (!targetBranch) {
|
||||
@@ -51,7 +51,7 @@ export class GitPullCommand implements GitSubcommand {
|
||||
let remoteUrl: string;
|
||||
try {
|
||||
const remotes = await this.git.listRemotes({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
@@ -69,12 +69,16 @@ export class GitPullCommand implements GitSubcommand {
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
const hasChanges = statusMatrix.some(([, headStatus, workdirStatus, stageStatus]) => {
|
||||
return headStatus !== workdirStatus || headStatus !== stageStatus;
|
||||
});
|
||||
const modifiedFiles = statusMatrix
|
||||
.filter(([, headStatus, workdirStatus, stageStatus]) => {
|
||||
// Check for any uncommitted changes (modified, staged, or untracked)
|
||||
return headStatus !== workdirStatus || headStatus !== stageStatus;
|
||||
})
|
||||
.map(([filepath]) => filepath);
|
||||
|
||||
if (hasChanges) {
|
||||
return createErrorResult('error: Your local changes to the following files would be overwritten by merge:\nPlease commit your changes or stash them before you merge.');
|
||||
if (modifiedFiles.length > 0) {
|
||||
const fileList = modifiedFiles.map(file => `\t${file}`).join('\n');
|
||||
return createErrorResult(`error: Your local changes to the following files would be overwritten by merge:\n${fileList}\nPlease commit your changes or stash them before you merge.`);
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -90,7 +94,7 @@ export class GitPullCommand implements GitSubcommand {
|
||||
let remoteOid: string;
|
||||
try {
|
||||
remoteOid = await this.git.resolveRef({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
ref: remoteRef,
|
||||
});
|
||||
@@ -102,14 +106,14 @@ export class GitPullCommand implements GitSubcommand {
|
||||
let currentOid: string;
|
||||
try {
|
||||
currentOid = await this.git.resolveRef({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
ref: 'HEAD',
|
||||
});
|
||||
} catch {
|
||||
// Empty repository, just checkout the remote branch
|
||||
await this.git.checkout({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
ref: targetBranch,
|
||||
});
|
||||
@@ -123,7 +127,7 @@ export class GitPullCommand implements GitSubcommand {
|
||||
|
||||
// Perform fast-forward merge (simplified)
|
||||
await this.git.merge({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
ours: currentBranch || 'HEAD',
|
||||
theirs: remoteRef,
|
||||
@@ -157,18 +161,13 @@ export class GitPullCommand implements GitSubcommand {
|
||||
let remote = 'origin'; // Default remote
|
||||
let branch: string | undefined;
|
||||
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const arg = args[i];
|
||||
const nonOptionArgs = args.filter(arg => !arg.startsWith('-'));
|
||||
|
||||
if (!arg.startsWith('-')) {
|
||||
if (remote === 'origin' && !branch) {
|
||||
// First non-option argument is remote
|
||||
remote = arg;
|
||||
} else if (!branch) {
|
||||
// Second non-option argument is branch
|
||||
branch = arg;
|
||||
}
|
||||
}
|
||||
if (nonOptionArgs.length >= 1) {
|
||||
remote = nonOptionArgs[0];
|
||||
}
|
||||
if (nonOptionArgs.length >= 2) {
|
||||
branch = nonOptionArgs[1];
|
||||
}
|
||||
|
||||
return { remote, branch };
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { GitResetCommand } from './reset';
|
||||
import type { GitSubcommandOptions } from '../git';
|
||||
import type { Git } from '../../git';
|
||||
import type { JSRuntimeFS } from '../../JSRuntime';
|
||||
|
||||
// Mock implementations
|
||||
const mockGit = {
|
||||
statusMatrix: async () => [
|
||||
// [filepath, headStatus, workdirStatus, stageStatus]
|
||||
['staged.txt', 1, 1, 2], // Modified in stage
|
||||
['new-staged.txt', 0, 1, 2], // New file staged
|
||||
['modified.txt', 1, 2, 1], // Modified in working dir (not staged)
|
||||
['unchanged.txt', 1, 1, 1], // No changes
|
||||
],
|
||||
resetIndex: async ({ filepath }: { filepath: string }) => {
|
||||
// Mock successful reset
|
||||
return { filepath };
|
||||
},
|
||||
resolveRef: async ({ ref }: { ref: string }) => {
|
||||
const refs = {
|
||||
'HEAD': 'abc123def456',
|
||||
'HEAD~1': 'def456abc123',
|
||||
};
|
||||
if (refs[ref as keyof typeof refs]) {
|
||||
return refs[ref as keyof typeof refs];
|
||||
}
|
||||
throw new Error(`Unknown ref: ${ref}`);
|
||||
},
|
||||
readCommit: async () => ({
|
||||
oid: 'abc123def456',
|
||||
commit: {
|
||||
message: 'Test commit',
|
||||
author: { name: 'Test', email: '[email protected]' },
|
||||
},
|
||||
}),
|
||||
writeRef: async () => {},
|
||||
checkout: async () => {},
|
||||
} as unknown as Git;
|
||||
|
||||
const mockFS = {
|
||||
stat: async (path: string) => {
|
||||
if (path.endsWith('/.git')) {
|
||||
return { isDirectory: () => true };
|
||||
}
|
||||
throw new Error('File not found');
|
||||
},
|
||||
} as unknown as JSRuntimeFS;
|
||||
|
||||
const mockOptions: GitSubcommandOptions = {
|
||||
git: mockGit,
|
||||
fs: mockFS,
|
||||
pwd: '/test/repo',
|
||||
};
|
||||
|
||||
describe('GitResetCommand', () => {
|
||||
let command: GitResetCommand;
|
||||
|
||||
beforeEach(() => {
|
||||
command = new GitResetCommand(mockOptions);
|
||||
});
|
||||
|
||||
describe('parseArgs', () => {
|
||||
type ParseArgsResult = {
|
||||
mode: 'soft' | 'mixed' | 'hard';
|
||||
target: string;
|
||||
files: string[];
|
||||
isFileReset: boolean;
|
||||
};
|
||||
|
||||
it('should parse no arguments as file reset', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs([]);
|
||||
expect(result).toEqual({
|
||||
mode: 'mixed',
|
||||
target: 'HEAD',
|
||||
files: [],
|
||||
isFileReset: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse HEAD as file reset', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['HEAD']);
|
||||
expect(result).toEqual({
|
||||
mode: 'mixed',
|
||||
target: 'HEAD',
|
||||
files: [],
|
||||
isFileReset: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse HEAD with files as file reset', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['HEAD', 'file1.txt', 'file2.txt']);
|
||||
expect(result).toEqual({
|
||||
mode: 'mixed',
|
||||
target: 'HEAD',
|
||||
files: ['file1.txt', 'file2.txt'],
|
||||
isFileReset: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse commit hash as commit reset', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['abc123def']);
|
||||
expect(result).toEqual({
|
||||
mode: 'mixed',
|
||||
target: 'abc123def',
|
||||
files: [],
|
||||
isFileReset: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse mode flags correctly', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['--hard', 'HEAD~1']);
|
||||
expect(result).toEqual({
|
||||
mode: 'hard',
|
||||
target: 'HEAD~1',
|
||||
files: [],
|
||||
isFileReset: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse mixed mode with commit', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['--mixed', 'HEAD~1']);
|
||||
expect(result).toEqual({
|
||||
mode: 'mixed',
|
||||
target: 'HEAD~1',
|
||||
files: [],
|
||||
isFileReset: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('execute', () => {
|
||||
it('should fail when not in a git repository', async () => {
|
||||
const commandWithoutGit = new GitResetCommand({
|
||||
...mockOptions,
|
||||
fs: {
|
||||
stat: async () => {
|
||||
throw new Error('File not found');
|
||||
},
|
||||
} as unknown as JSRuntimeFS,
|
||||
});
|
||||
|
||||
const result = await commandWithoutGit.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('fatal: not a git repository');
|
||||
});
|
||||
|
||||
it('should unstage all files when called without arguments', async () => {
|
||||
const result = await command.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('Unstaged changes after reset:');
|
||||
expect(result.stdout).toContain('M\tstaged.txt');
|
||||
expect(result.stdout).toContain('M\tnew-staged.txt');
|
||||
// Should not include files that aren't staged
|
||||
expect(result.stdout).not.toContain('modified.txt');
|
||||
expect(result.stdout).not.toContain('unchanged.txt');
|
||||
});
|
||||
|
||||
it('should unstage all files when called with HEAD', async () => {
|
||||
const result = await command.execute(['HEAD']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('Unstaged changes after reset:');
|
||||
expect(result.stdout).toContain('M\tstaged.txt');
|
||||
expect(result.stdout).toContain('M\tnew-staged.txt');
|
||||
});
|
||||
|
||||
it('should unstage specific files when called with HEAD and file paths', async () => {
|
||||
const result = await command.execute(['HEAD', 'staged.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('Unstaged changes after reset:');
|
||||
expect(result.stdout).toContain('M\tstaged.txt');
|
||||
expect(result.stdout).not.toContain('new-staged.txt');
|
||||
});
|
||||
|
||||
it('should return empty output when no files are staged', async () => {
|
||||
const commandWithNoStaged = new GitResetCommand({
|
||||
...mockOptions,
|
||||
git: {
|
||||
...mockGit,
|
||||
statusMatrix: async () => [
|
||||
['modified.txt', 1, 2, 1], // Modified in working dir only
|
||||
['unchanged.txt', 1, 1, 1], // No changes
|
||||
],
|
||||
} as unknown as Git,
|
||||
});
|
||||
|
||||
const result = await commandWithNoStaged.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
});
|
||||
|
||||
it('should handle errors when resetting specific files', async () => {
|
||||
const commandWithError = new GitResetCommand({
|
||||
...mockOptions,
|
||||
git: {
|
||||
...mockGit,
|
||||
resetIndex: async ({ filepath }: { filepath: string }) => {
|
||||
if (filepath === 'nonexistent.txt') {
|
||||
throw new Error('File not found');
|
||||
}
|
||||
return { filepath };
|
||||
},
|
||||
} as unknown as Git,
|
||||
});
|
||||
|
||||
const result = await commandWithError.execute(['HEAD', 'nonexistent.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain("error: pathspec 'nonexistent.txt' did not match any file(s) known to git");
|
||||
});
|
||||
|
||||
it('should handle commit reset with hard mode', async () => {
|
||||
const result = await command.execute(['--hard', 'HEAD~1']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('HEAD is now at def456a');
|
||||
});
|
||||
|
||||
it('should handle commit reset with mixed mode', async () => {
|
||||
const result = await command.execute(['--mixed', 'HEAD~1']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('HEAD is now at def456a');
|
||||
});
|
||||
|
||||
it('should return error for soft reset (not implemented)', async () => {
|
||||
const result = await command.execute(['--soft', 'HEAD~1']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('--soft reset is not implemented');
|
||||
});
|
||||
|
||||
it('should handle invalid commit reference', async () => {
|
||||
const result = await command.execute(['abcdef12345']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain("fatal: ambiguous argument 'abcdef12345'");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -29,10 +29,10 @@ export class GitResetCommand implements GitSubcommand {
|
||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||
}
|
||||
|
||||
const { mode, target, files } = this.parseArgs(args);
|
||||
const { mode, target, files, isFileReset } = this.parseArgs(args);
|
||||
|
||||
if (files.length > 0) {
|
||||
// Reset specific files (unstage)
|
||||
if (isFileReset) {
|
||||
// Reset specific files or all files (unstage)
|
||||
return await this.resetFiles(files);
|
||||
} else {
|
||||
// Reset to commit
|
||||
@@ -47,22 +47,27 @@ export class GitResetCommand implements GitSubcommand {
|
||||
private parseArgs(args: string[]): {
|
||||
mode: 'soft' | 'mixed' | 'hard';
|
||||
target: string;
|
||||
files: string[]
|
||||
files: string[];
|
||||
isFileReset: boolean;
|
||||
} {
|
||||
let mode: 'soft' | 'mixed' | 'hard' = 'mixed'; // Default mode
|
||||
let target = 'HEAD'; // Default target
|
||||
const files: string[] = [];
|
||||
let foundTarget = false;
|
||||
let hasMode = false;
|
||||
|
||||
for (const arg of args) {
|
||||
if (arg === '--soft') {
|
||||
mode = 'soft';
|
||||
hasMode = true;
|
||||
} else if (arg === '--mixed') {
|
||||
mode = 'mixed';
|
||||
hasMode = true;
|
||||
} else if (arg === '--hard') {
|
||||
mode = 'hard';
|
||||
hasMode = true;
|
||||
} else if (!arg.startsWith('-')) {
|
||||
if (!foundTarget && (arg === 'HEAD' || arg.match(/^[a-f0-9]{7,40}$/))) {
|
||||
if (!foundTarget && (arg === 'HEAD' || arg.match(/^[a-f0-9]{7,40}$/) || arg.match(/^HEAD[~^]\d*$/))) {
|
||||
target = arg;
|
||||
foundTarget = true;
|
||||
} else {
|
||||
@@ -71,7 +76,17 @@ export class GitResetCommand implements GitSubcommand {
|
||||
}
|
||||
}
|
||||
|
||||
return { mode, target, files };
|
||||
// Determine if this is a file reset operation
|
||||
// git reset without arguments = unstage all files
|
||||
// git reset HEAD = unstage all files
|
||||
// git reset HEAD <files> = unstage specific files
|
||||
// git reset <commit> = reset to commit
|
||||
// git reset --mode <commit> = reset to commit with mode
|
||||
const isFileReset = (args.length === 0) ||
|
||||
(target === 'HEAD' && !hasMode && files.length === 0) ||
|
||||
(files.length > 0);
|
||||
|
||||
return { mode, target, files, isFileReset };
|
||||
}
|
||||
|
||||
private async resetFiles(files: string[]): Promise<ShellCommandResult> {
|
||||
@@ -79,17 +94,53 @@ export class GitResetCommand implements GitSubcommand {
|
||||
const resetFiles: string[] = [];
|
||||
const errors: string[] = [];
|
||||
|
||||
for (const file of files) {
|
||||
if (files.length === 0) {
|
||||
// Reset all staged files (git reset or git reset HEAD)
|
||||
try {
|
||||
// Remove from staging area (reset to HEAD)
|
||||
await this.git.resetIndex({
|
||||
|
||||
// Get the status matrix to find all staged files
|
||||
const statusMatrix = await this.git.statusMatrix({
|
||||
dir: this.pwd,
|
||||
filepath: file,
|
||||
});
|
||||
resetFiles.push(file);
|
||||
} catch {
|
||||
errors.push(`error: pathspec '${file}' did not match any file(s) known to git`);
|
||||
|
||||
// Find files that are staged (differ from HEAD)
|
||||
const stagedFiles = statusMatrix
|
||||
.filter(([, headStatus, , stageStatus]) => {
|
||||
return headStatus !== stageStatus;
|
||||
})
|
||||
.map(([filepath]) => filepath);
|
||||
|
||||
if (stagedFiles.length === 0) {
|
||||
return createSuccessResult('');
|
||||
}
|
||||
|
||||
// Reset each staged file
|
||||
for (const file of stagedFiles) {
|
||||
try {
|
||||
await this.git.resetIndex({
|
||||
dir: this.pwd,
|
||||
filepath: file,
|
||||
});
|
||||
resetFiles.push(file);
|
||||
} catch (error) {
|
||||
errors.push(`error: failed to reset '${file}': ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
return createErrorResult(`Failed to get repository status: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
} else {
|
||||
// Reset specific files
|
||||
for (const file of files) {
|
||||
try {
|
||||
// Remove from staging area (reset to HEAD)
|
||||
await this.git.resetIndex({
|
||||
dir: this.pwd,
|
||||
filepath: file,
|
||||
});
|
||||
resetFiles.push(file);
|
||||
} catch {
|
||||
errors.push(`error: pathspec '${file}' did not match any file(s) known to git`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,7 +165,7 @@ export class GitResetCommand implements GitSubcommand {
|
||||
let targetOid: string;
|
||||
try {
|
||||
targetOid = await this.git.resolveRef({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
ref: target,
|
||||
});
|
||||
@@ -126,7 +177,7 @@ export class GitResetCommand implements GitSubcommand {
|
||||
let currentOid: string;
|
||||
try {
|
||||
currentOid = await this.git.resolveRef({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
ref: 'HEAD',
|
||||
});
|
||||
@@ -152,7 +203,7 @@ export class GitResetCommand implements GitSubcommand {
|
||||
// Reset the index to match the target commit
|
||||
try {
|
||||
await this.git.checkout({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
ref: target,
|
||||
noCheckout: true, // Only update the index, not the working directory
|
||||
@@ -172,14 +223,14 @@ export class GitResetCommand implements GitSubcommand {
|
||||
|
||||
// Get the commit object to ensure it exists
|
||||
await this.git.readCommit({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
oid: targetOid,
|
||||
});
|
||||
|
||||
// Update HEAD to point to the target commit
|
||||
await this.git.writeRef({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
ref: 'HEAD',
|
||||
value: targetOid,
|
||||
@@ -188,7 +239,7 @@ export class GitResetCommand implements GitSubcommand {
|
||||
// Reset the working directory by checking out all files from the target commit
|
||||
// Use force to overwrite any local changes
|
||||
await this.git.checkout({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
ref: targetOid,
|
||||
force: true,
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { GitStatusCommand } from './status';
|
||||
import type { JSRuntimeFS } from '../../JSRuntime';
|
||||
import type { Git } from '../../git';
|
||||
|
||||
// Mock filesystem
|
||||
const createMockFS = (): JSRuntimeFS => ({
|
||||
readFile: vi.fn().mockResolvedValue('mock content'),
|
||||
writeFile: vi.fn().mockResolvedValue(undefined),
|
||||
readdir: vi.fn().mockResolvedValue([]),
|
||||
mkdir: vi.fn().mockResolvedValue(undefined),
|
||||
stat: vi.fn().mockImplementation((path: string) => {
|
||||
if (path.endsWith('/.git')) {
|
||||
return Promise.resolve({
|
||||
isDirectory: () => true,
|
||||
isFile: () => false,
|
||||
size: 0,
|
||||
mtimeMs: Date.now(),
|
||||
});
|
||||
}
|
||||
throw new Error('ENOENT: no such file or directory');
|
||||
}),
|
||||
lstat: vi.fn().mockResolvedValue({
|
||||
isDirectory: () => true,
|
||||
isFile: () => false,
|
||||
size: 0,
|
||||
mtimeMs: Date.now(),
|
||||
}),
|
||||
unlink: vi.fn().mockResolvedValue(undefined),
|
||||
rmdir: vi.fn().mockResolvedValue(undefined),
|
||||
rename: vi.fn().mockResolvedValue(undefined),
|
||||
readlink: vi.fn().mockResolvedValue('mock link'),
|
||||
symlink: vi.fn().mockResolvedValue(undefined),
|
||||
});
|
||||
|
||||
// Mock Git
|
||||
const createMockGit = (): Git => ({
|
||||
statusMatrix: vi.fn(),
|
||||
currentBranch: vi.fn(),
|
||||
stat: vi.fn(),
|
||||
} as unknown as Git);
|
||||
|
||||
describe('GitStatusCommand', () => {
|
||||
let statusCommand: GitStatusCommand;
|
||||
let mockFS: JSRuntimeFS;
|
||||
let mockGit: Git;
|
||||
const testCwd = '/test';
|
||||
|
||||
beforeEach(() => {
|
||||
mockFS = createMockFS();
|
||||
mockGit = createMockGit();
|
||||
statusCommand = new GitStatusCommand({
|
||||
git: mockGit,
|
||||
fs: mockFS,
|
||||
pwd: testCwd,
|
||||
});
|
||||
});
|
||||
|
||||
it('should have correct command properties', () => {
|
||||
expect(statusCommand.name).toBe('status');
|
||||
expect(statusCommand.description).toBe('Show the working tree status');
|
||||
expect(statusCommand.usage).toBe('git status [--porcelain] [--short]');
|
||||
});
|
||||
|
||||
it('should return error when not in a git repository', async () => {
|
||||
// Mock stat to throw error for .git directory
|
||||
vi.mocked(mockFS.stat).mockRejectedValueOnce(new Error('ENOENT'));
|
||||
|
||||
const result = await statusCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('fatal: not a git repository');
|
||||
});
|
||||
|
||||
it('should show clean status when no changes', async () => {
|
||||
// Mock git status matrix with no changes
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||
|
||||
const result = await statusCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('On branch main');
|
||||
expect(result.stdout).toContain('nothing to commit, working tree clean');
|
||||
});
|
||||
|
||||
it('should show untracked files correctly', async () => {
|
||||
// Mock git status matrix with untracked file
|
||||
// [filepath, headStatus, workdirStatus, stageStatus]
|
||||
// Untracked: headStatus=0, stageStatus=0, workdirStatus=2
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['newfile.txt', 0, 2, 0]
|
||||
]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||
|
||||
const result = await statusCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('On branch main');
|
||||
expect(result.stdout).toContain('Untracked files:');
|
||||
expect(result.stdout).toContain('newfile.txt');
|
||||
});
|
||||
|
||||
it('should show staged files correctly', async () => {
|
||||
// Mock git status matrix with staged file
|
||||
// Staged new file: headStatus=0, stageStatus=2, workdirStatus=2
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['newfile.txt', 0, 2, 2]
|
||||
]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||
|
||||
const result = await statusCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('On branch main');
|
||||
expect(result.stdout).toContain('Changes to be committed:');
|
||||
expect(result.stdout).toContain('new file: newfile.txt');
|
||||
});
|
||||
|
||||
it('should show modified files correctly', async () => {
|
||||
// Mock git status matrix with modified file
|
||||
// Modified file: headStatus=1, stageStatus=1, workdirStatus=2
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['existing.txt', 1, 2, 1]
|
||||
]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||
|
||||
const result = await statusCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('On branch main');
|
||||
expect(result.stdout).toContain('Changes not staged for commit:');
|
||||
expect(result.stdout).toContain('modified: existing.txt');
|
||||
});
|
||||
|
||||
it('should show deleted files correctly', async () => {
|
||||
// Mock git status matrix with deleted file
|
||||
// Deleted file: headStatus=1, stageStatus=1, workdirStatus=0
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['deleted.txt', 1, 0, 1]
|
||||
]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||
|
||||
const result = await statusCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('On branch main');
|
||||
expect(result.stdout).toContain('Changes not staged for commit:');
|
||||
expect(result.stdout).toContain('deleted: deleted.txt');
|
||||
});
|
||||
|
||||
it('should format porcelain output correctly', async () => {
|
||||
// Mock git status matrix with various changes
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['untracked.txt', 0, 2, 0], // Untracked
|
||||
['staged.txt', 0, 2, 2], // Staged new file
|
||||
['modified.txt', 1, 2, 1], // Modified
|
||||
['deleted.txt', 1, 0, 1], // Deleted
|
||||
]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||
|
||||
const result = await statusCommand.execute(['--porcelain']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('?? untracked.txt');
|
||||
expect(result.stdout).toContain('A staged.txt');
|
||||
expect(result.stdout).toContain(' M modified.txt');
|
||||
expect(result.stdout).toContain(' D deleted.txt');
|
||||
});
|
||||
|
||||
it('should handle short format', async () => {
|
||||
// Mock git status matrix with changes
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['untracked.txt', 0, 2, 0], // Untracked
|
||||
]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||
|
||||
const result = await statusCommand.execute(['--short']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('?? untracked.txt');
|
||||
});
|
||||
|
||||
it('should handle complex status matrix correctly', async () => {
|
||||
// Mock git status matrix with a complex scenario
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
||||
['file1.txt', 1, 2, 2], // Modified and staged
|
||||
['file2.txt', 0, 2, 0], // Untracked
|
||||
['file3.txt', 1, 0, 0], // Deleted (staged)
|
||||
['file4.txt', 1, 2, 1], // Modified (not staged)
|
||||
]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('feature-branch');
|
||||
|
||||
const result = await statusCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('On branch feature-branch');
|
||||
expect(result.stdout).toContain('Changes to be committed:');
|
||||
expect(result.stdout).toContain('modified: file1.txt');
|
||||
expect(result.stdout).toContain('deleted: file3.txt');
|
||||
expect(result.stdout).toContain('Untracked files:');
|
||||
expect(result.stdout).toContain('file2.txt');
|
||||
expect(result.stdout).toContain('Changes not staged for commit:');
|
||||
expect(result.stdout).toContain('modified: file4.txt');
|
||||
});
|
||||
|
||||
it('should handle detached HEAD state', async () => {
|
||||
// Mock git status matrix with no current branch
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue(undefined);
|
||||
|
||||
const result = await statusCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('HEAD detached at unknown');
|
||||
expect(result.stdout).toContain('nothing to commit, working tree clean');
|
||||
});
|
||||
});
|
||||
@@ -39,7 +39,6 @@ export class GitStatusCommand implements GitSubcommand {
|
||||
let currentBranch: string | null = null;
|
||||
try {
|
||||
currentBranch = await this.git.currentBranch({
|
||||
|
||||
dir: this.pwd,
|
||||
}) || null;
|
||||
} catch {
|
||||
@@ -78,22 +77,26 @@ export class GitStatusCommand implements GitSubcommand {
|
||||
let indexStatus = ' ';
|
||||
let workingStatus = ' ';
|
||||
|
||||
// Determine index status (staged changes)
|
||||
if (headStatus === 0 && stageStatus === 1) {
|
||||
indexStatus = 'A'; // Added
|
||||
// Determine index status (staged changes - comparing HEAD to stage)
|
||||
if (headStatus === 0 && stageStatus === 2) {
|
||||
indexStatus = 'A'; // Added to stage
|
||||
} else if (headStatus === 1 && stageStatus === 0) {
|
||||
indexStatus = 'D'; // Deleted
|
||||
} else if (headStatus === 1 && stageStatus === 1 && headStatus !== stageStatus) {
|
||||
indexStatus = 'M'; // Modified
|
||||
indexStatus = 'D'; // Deleted from stage
|
||||
} else if (headStatus === 1 && stageStatus === 2) {
|
||||
indexStatus = 'M'; // Modified in stage
|
||||
}
|
||||
|
||||
// Determine working directory status
|
||||
if (headStatus === 0 && stageStatus === 0 && workdirStatus === 1) {
|
||||
workingStatus = '?'; // Untracked
|
||||
// Determine working directory status (comparing stage to working dir)
|
||||
if (headStatus === 0 && stageStatus === 0 && workdirStatus === 2) {
|
||||
// Untracked files show as ?? in porcelain format
|
||||
indexStatus = '?';
|
||||
workingStatus = '?';
|
||||
} else if (stageStatus === 2 && workdirStatus === 0) {
|
||||
workingStatus = 'D'; // Deleted in working dir
|
||||
} else if (stageStatus === 1 && workdirStatus === 0) {
|
||||
workingStatus = 'D'; // Deleted
|
||||
} else if (stageStatus !== workdirStatus) {
|
||||
workingStatus = 'M'; // Modified
|
||||
workingStatus = 'D'; // Deleted in working dir (was same as HEAD)
|
||||
} else if (stageStatus !== workdirStatus && workdirStatus === 2) {
|
||||
workingStatus = 'M'; // Modified in working dir
|
||||
}
|
||||
|
||||
// Only show files with changes
|
||||
@@ -112,7 +115,7 @@ export class GitStatusCommand implements GitSubcommand {
|
||||
if (currentBranch) {
|
||||
lines.push(`On branch ${currentBranch}`);
|
||||
} else {
|
||||
lines.push('On branch main');
|
||||
lines.push('HEAD detached at unknown');
|
||||
}
|
||||
|
||||
// Categorize changes
|
||||
@@ -122,24 +125,26 @@ export class GitStatusCommand implements GitSubcommand {
|
||||
const deleted: string[] = [];
|
||||
|
||||
for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) {
|
||||
// Staged changes (index differs from HEAD)
|
||||
if (headStatus === 0 && stageStatus === 1) {
|
||||
// Staged changes (stage differs from HEAD)
|
||||
if (headStatus === 0 && stageStatus === 2) {
|
||||
staged.push(`\tnew file: ${filepath}`);
|
||||
} else if (headStatus === 1 && stageStatus === 0) {
|
||||
staged.push(`\tdeleted: ${filepath}`);
|
||||
} else if (headStatus !== stageStatus && headStatus === 1 && stageStatus === 1) {
|
||||
} else if (headStatus === 1 && stageStatus === 2) {
|
||||
staged.push(`\tmodified: ${filepath}`);
|
||||
}
|
||||
|
||||
// Working directory changes (working dir differs from index)
|
||||
if (stageStatus === 1 && workdirStatus === 0) {
|
||||
// Working directory changes (working dir differs from stage)
|
||||
if (stageStatus === 2 && workdirStatus === 0) {
|
||||
deleted.push(`\tdeleted: ${filepath}`);
|
||||
} else if (stageStatus !== workdirStatus && stageStatus === 1 && workdirStatus === 1) {
|
||||
} else if (stageStatus === 1 && workdirStatus === 0) {
|
||||
deleted.push(`\tdeleted: ${filepath}`);
|
||||
} else if (stageStatus !== workdirStatus && workdirStatus === 2) {
|
||||
modified.push(`\tmodified: ${filepath}`);
|
||||
}
|
||||
|
||||
// Untracked files
|
||||
if (headStatus === 0 && stageStatus === 0 && workdirStatus === 1) {
|
||||
// Untracked files (not in HEAD, not in stage, but in working dir)
|
||||
if (headStatus === 0 && stageStatus === 0 && workdirStatus === 2) {
|
||||
untracked.push(`\t${filepath}`);
|
||||
}
|
||||
}
|
||||
@@ -148,7 +153,7 @@ export class GitStatusCommand implements GitSubcommand {
|
||||
if (staged.length > 0) {
|
||||
lines.push('');
|
||||
lines.push('Changes to be committed:');
|
||||
lines.push(' (use "git reset HEAD <file>..." to unstage)');
|
||||
lines.push(' (use "git restore --staged <file>..." to unstage)');
|
||||
lines.push('');
|
||||
lines.push(...staged);
|
||||
}
|
||||
@@ -158,7 +163,7 @@ export class GitStatusCommand implements GitSubcommand {
|
||||
lines.push('');
|
||||
lines.push('Changes not staged for commit:');
|
||||
lines.push(' (use "git add <file>..." to update what will be committed)');
|
||||
lines.push(' (use "git checkout -- <file>..." to discard changes in working directory)');
|
||||
lines.push(' (use "git restore <file>..." to discard changes in working directory)');
|
||||
lines.push('');
|
||||
lines.push(...modified);
|
||||
lines.push(...deleted);
|
||||
|
||||
@@ -19,6 +19,7 @@ export { MkdirCommand } from './mkdir';
|
||||
export { MvCommand } from './mv';
|
||||
export { PwdCommand } from './pwd';
|
||||
export { RmCommand } from './rm';
|
||||
export { SedCommand } from './sed';
|
||||
export { SortCommand } from './sort';
|
||||
export { TailCommand } from './tail';
|
||||
export { TouchCommand } from './touch';
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { SedCommand } from './sed';
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
|
||||
// Mock filesystem
|
||||
const mockFS: JSRuntimeFS = {
|
||||
readFile: ((path: string, encoding?: string) => {
|
||||
const files: Record<string, string> = {
|
||||
'/test/hello.txt': 'hello world\nfoo bar\nbaz qux\n',
|
||||
'/test/numbers.txt': '1\n2\n3\n4\n5\n',
|
||||
'/test/mixed.txt': 'apple\nbanana\ncherry\napple pie\n',
|
||||
};
|
||||
|
||||
if (path in files) {
|
||||
if (encoding === 'utf8' || (encoding && encoding !== undefined)) {
|
||||
return Promise.resolve(files[path]);
|
||||
} else {
|
||||
// No encoding specified, return Uint8Array
|
||||
return Promise.resolve(new TextEncoder().encode(files[path]));
|
||||
}
|
||||
}
|
||||
return Promise.reject(new Error('ENOENT: no such file or directory'));
|
||||
}) as JSRuntimeFS['readFile'],
|
||||
|
||||
writeFile: async (_path: string, _data: string | Uint8Array, _encoding?: string) => {
|
||||
// Mock write operation
|
||||
},
|
||||
|
||||
stat: async (_path: string) => ({
|
||||
isFile: () => true,
|
||||
isDirectory: () => false,
|
||||
size: 100,
|
||||
mtimeMs: Date.now(),
|
||||
}),
|
||||
|
||||
lstat: async (_path: string) => ({
|
||||
isFile: () => true,
|
||||
isDirectory: () => false,
|
||||
size: 100,
|
||||
mtimeMs: Date.now(),
|
||||
}),
|
||||
|
||||
readdir: (async (_path: string, _options?: { withFileTypes?: boolean }) => {
|
||||
if (_options?.withFileTypes) {
|
||||
return [];
|
||||
}
|
||||
return [];
|
||||
}) as JSRuntimeFS['readdir'],
|
||||
mkdir: async () => {},
|
||||
rmdir: async () => {},
|
||||
unlink: async () => {},
|
||||
rename: async () => {},
|
||||
readlink: async () => '',
|
||||
symlink: async () => {},
|
||||
};
|
||||
|
||||
describe('SedCommand', () => {
|
||||
let sedCommand: SedCommand;
|
||||
|
||||
beforeEach(() => {
|
||||
sedCommand = new SedCommand(mockFS);
|
||||
});
|
||||
|
||||
describe('basic functionality', () => {
|
||||
it('should have correct name and description', () => {
|
||||
expect(sedCommand.name).toBe('sed');
|
||||
expect(sedCommand.description).toBe('Stream editor for filtering and transforming text');
|
||||
});
|
||||
|
||||
it('should return error when no script provided', async () => {
|
||||
const result = await sedCommand.execute([], '/test');
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('missing script');
|
||||
});
|
||||
});
|
||||
|
||||
describe('substitute command', () => {
|
||||
it('should substitute text with s command', async () => {
|
||||
const input = 'hello world\nfoo bar\n';
|
||||
const result = await sedCommand.execute(['s/hello/hi/'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('hi world\nfoo bar\n');
|
||||
});
|
||||
|
||||
it('should substitute globally with g flag', async () => {
|
||||
const input = 'hello hello world\n';
|
||||
const result = await sedCommand.execute(['s/hello/hi/g'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('hi hi world\n');
|
||||
});
|
||||
|
||||
it('should substitute case-insensitively with i flag', async () => {
|
||||
const input = 'Hello HELLO world\n';
|
||||
const result = await sedCommand.execute(['s/hello/hi/gi'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('hi hi world\n');
|
||||
});
|
||||
|
||||
it('should substitute with special characters', async () => {
|
||||
const input = 'test.txt\n';
|
||||
const result = await sedCommand.execute(['s/\\.txt/.bak/'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('test.bak\n');
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete command', () => {
|
||||
it('should delete all lines with d command', async () => {
|
||||
const input = 'line1\nline2\nline3\n';
|
||||
const result = await sedCommand.execute(['d'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('\n');
|
||||
});
|
||||
|
||||
it('should delete specific line with line number', async () => {
|
||||
const input = 'line1\nline2\nline3\n';
|
||||
const result = await sedCommand.execute(['2d'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('line1\nline3\n');
|
||||
});
|
||||
|
||||
it('should delete lines matching pattern', async () => {
|
||||
const input = 'keep this\ndelete this line\nkeep this too\n';
|
||||
const result = await sedCommand.execute(['/delete/d'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('keep this\nkeep this too\n');
|
||||
});
|
||||
});
|
||||
|
||||
describe('print command', () => {
|
||||
it('should print all lines normally without -n', async () => {
|
||||
const input = 'line1\nline2\n';
|
||||
const result = await sedCommand.execute(['p'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('line1\nline1\nline2\nline2\n'); // Each line printed twice (normal + p command)
|
||||
});
|
||||
|
||||
it('should print only specified lines with -n', async () => {
|
||||
const input = 'line1\nline2\nline3\n';
|
||||
const result = await sedCommand.execute(['-n', '2p'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('quit command', () => {
|
||||
it('should quit after processing specified line', async () => {
|
||||
const input = 'line1\nline2\nline3\nline4\n';
|
||||
const result = await sedCommand.execute(['2q'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('line1\nline2\n');
|
||||
});
|
||||
});
|
||||
|
||||
describe('append, insert, and change commands', () => {
|
||||
it('should append text after line', async () => {
|
||||
const input = 'line1\nline2\n';
|
||||
const result = await sedCommand.execute(['1a\\appended text'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('line1\nappended text\nline2\n');
|
||||
});
|
||||
|
||||
it('should insert text before line', async () => {
|
||||
const input = 'line1\nline2\n';
|
||||
const result = await sedCommand.execute(['2i\\inserted text'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('line1\ninserted text\nline2\n');
|
||||
});
|
||||
|
||||
it('should change line', async () => {
|
||||
const input = 'line1\nline2\nline3\n';
|
||||
const result = await sedCommand.execute(['2c\\changed text'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('line1\nchanged text\nline3\n');
|
||||
});
|
||||
});
|
||||
|
||||
describe('file operations', () => {
|
||||
it('should process file content', async () => {
|
||||
const result = await sedCommand.execute(['s/hello/hi/'], '/test', undefined);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
});
|
||||
|
||||
it('should handle file not found error', async () => {
|
||||
const result = await sedCommand.execute(['s/hello/hi/', 'nonexistent.txt'], '/test');
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('No such file or directory');
|
||||
});
|
||||
|
||||
it('should reject absolute paths', async () => {
|
||||
const result = await sedCommand.execute(['s/hello/hi/', '/absolute/path.txt'], '/test');
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('absolute paths are not supported');
|
||||
});
|
||||
});
|
||||
|
||||
describe('option parsing', () => {
|
||||
it('should parse -n option', async () => {
|
||||
const input = 'line1\nline2\n';
|
||||
const result = await sedCommand.execute(['-n', 'p'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
});
|
||||
|
||||
it('should parse -e option', async () => {
|
||||
const input = 'hello world\n';
|
||||
const result = await sedCommand.execute(['-e', 's/hello/hi/'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('hi world\n');
|
||||
});
|
||||
|
||||
it('should parse combined options', async () => {
|
||||
const input = 'line1\nline2\n';
|
||||
const result = await sedCommand.execute(['-ne', 'p'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('multiple scripts', () => {
|
||||
it('should process multiple scripts in order', async () => {
|
||||
const input = 'hello world\n';
|
||||
const result = await sedCommand.execute(['-e', 's/hello/hi/', '-e', 's/world/universe/'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('hi universe\n');
|
||||
});
|
||||
});
|
||||
|
||||
describe('edge cases', () => {
|
||||
it('should handle empty input', async () => {
|
||||
const result = await sedCommand.execute(['s/hello/hi/'], '/test', '');
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
});
|
||||
|
||||
it('should handle invalid regex patterns gracefully', async () => {
|
||||
const input = 'hello world\n';
|
||||
const result = await sedCommand.execute(['s/[/hi/'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('hello world\n'); // Should return original
|
||||
});
|
||||
|
||||
it('should handle invalid script format', async () => {
|
||||
const input = 'hello world\n';
|
||||
const result = await sedCommand.execute(['invalid_script'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('Invalid sed script');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,375 @@
|
||||
import { join } from "path-browserify";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "./ShellCommand";
|
||||
|
||||
/**
|
||||
* Implementation of the 'sed' command
|
||||
* Stream editor for filtering and transforming text
|
||||
*/
|
||||
export class SedCommand implements ShellCommand {
|
||||
name = 'sed';
|
||||
description = 'Stream editor for filtering and transforming text';
|
||||
usage = 'sed [-i] [-n] [-e script] [script] [file...]';
|
||||
|
||||
private fs: JSRuntimeFS;
|
||||
|
||||
constructor(fs: JSRuntimeFS) {
|
||||
this.fs = fs;
|
||||
}
|
||||
|
||||
async execute(args: string[], cwd: string, input?: string): Promise<ShellCommandResult> {
|
||||
if (args.length === 0) {
|
||||
return createErrorResult(`${this.name}: missing script\nUsage: ${this.usage}`);
|
||||
}
|
||||
|
||||
try {
|
||||
const { options, scripts, files } = this.parseArgs(args);
|
||||
|
||||
if (scripts.length === 0) {
|
||||
return createErrorResult(`${this.name}: missing script\nUsage: ${this.usage}`);
|
||||
}
|
||||
|
||||
let content = '';
|
||||
|
||||
// If input is provided (from pipe), use that input
|
||||
if (input !== undefined) {
|
||||
content = input;
|
||||
} else if (files.length === 0) {
|
||||
// Read from stdin (not implemented in this context, return empty)
|
||||
return createSuccessResult('');
|
||||
} else {
|
||||
// Read all files
|
||||
for (const file of files) {
|
||||
try {
|
||||
// Handle absolute paths
|
||||
if (file.startsWith('/') || file.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(file)) {
|
||||
return createErrorResult(`${this.name}: absolute paths are not supported: ${file}`);
|
||||
}
|
||||
|
||||
const absolutePath = join(cwd, file);
|
||||
const stats = await this.fs.stat(absolutePath);
|
||||
|
||||
if (stats.isDirectory()) {
|
||||
return createErrorResult(`${this.name}: ${file}: Is a directory`);
|
||||
}
|
||||
|
||||
const fileContent = await this.fs.readFile(absolutePath, 'utf8');
|
||||
content += fileContent;
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes('ENOENT') || error.message.includes('not found')) {
|
||||
return createErrorResult(`${this.name}: ${file}: No such file or directory`);
|
||||
} else if (error.message.includes('EACCES') || error.message.includes('permission')) {
|
||||
return createErrorResult(`${this.name}: ${file}: Permission denied`);
|
||||
} else {
|
||||
return createErrorResult(`${this.name}: ${file}: ${error.message}`);
|
||||
}
|
||||
} else {
|
||||
return createErrorResult(`${this.name}: ${file}: Unknown error`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Process content with sed scripts
|
||||
let result = content;
|
||||
for (const script of scripts) {
|
||||
result = await this.processScript(script, result, options);
|
||||
}
|
||||
|
||||
// Handle in-place editing
|
||||
if (options.inPlace && files.length > 0) {
|
||||
for (const file of files) {
|
||||
const absolutePath = join(cwd, file);
|
||||
await this.fs.writeFile(absolutePath, result, 'utf8');
|
||||
}
|
||||
return createSuccessResult('');
|
||||
}
|
||||
|
||||
// Handle quiet mode
|
||||
if (options.quiet) {
|
||||
// In quiet mode, only explicitly printed lines are output
|
||||
// For now, we'll return empty unless there are 'p' commands
|
||||
return createSuccessResult('');
|
||||
}
|
||||
|
||||
return createSuccessResult(result);
|
||||
|
||||
} catch (error) {
|
||||
return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async processScript(script: string, content: string, options: { quiet: boolean; inPlace: boolean }): Promise<string> {
|
||||
// Track if original content ended with newline
|
||||
const originalEndsWithNewline = content.endsWith('\n');
|
||||
|
||||
// Split lines but handle the trailing newline properly
|
||||
let lines = content.split('\n');
|
||||
if (originalEndsWithNewline && lines[lines.length - 1] === '') {
|
||||
lines = lines.slice(0, -1); // Remove the empty line at the end
|
||||
}
|
||||
|
||||
const resultLines: string[] = [];
|
||||
|
||||
// Parse the sed script
|
||||
const command = this.parseScript(script);
|
||||
|
||||
if (!command) {
|
||||
throw new Error(`Invalid sed script: ${script}`);
|
||||
}
|
||||
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
let processedLine = line;
|
||||
let shouldPrint = !options.quiet;
|
||||
|
||||
switch (command.type) {
|
||||
case 's': {// Substitute
|
||||
const substituted = this.substitute(line, command.pattern!, command.replacement!, command.flags!);
|
||||
processedLine = substituted;
|
||||
break;
|
||||
}
|
||||
|
||||
case 'd': // Delete
|
||||
if (this.matchesAddress(i + 1, line, command.address ?? null)) {
|
||||
shouldPrint = false;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'p': // Print
|
||||
if (this.matchesAddress(i + 1, line, command.address ?? null)) {
|
||||
resultLines.push(processedLine);
|
||||
if (options.quiet) {
|
||||
shouldPrint = false;
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'q': // Quit
|
||||
if (this.matchesAddress(i + 1, line, command.address ?? null)) {
|
||||
resultLines.push(processedLine);
|
||||
return this.formatOutput(resultLines, originalEndsWithNewline);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'a': // Append
|
||||
if (this.matchesAddress(i + 1, line, command.address ?? null)) {
|
||||
resultLines.push(processedLine);
|
||||
resultLines.push(command.text || '');
|
||||
shouldPrint = false;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'i': // Insert
|
||||
if (this.matchesAddress(i + 1, line, command.address ?? null)) {
|
||||
resultLines.push(command.text || '');
|
||||
resultLines.push(processedLine);
|
||||
shouldPrint = false;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'c': // Change
|
||||
if (this.matchesAddress(i + 1, line, command.address ?? null)) {
|
||||
resultLines.push(command.text || '');
|
||||
shouldPrint = false;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
if (shouldPrint) {
|
||||
resultLines.push(processedLine);
|
||||
}
|
||||
}
|
||||
|
||||
return this.formatOutput(resultLines, originalEndsWithNewline);
|
||||
}
|
||||
|
||||
private formatOutput(lines: string[], originalEndsWithNewline: boolean): string {
|
||||
if (lines.length === 0) {
|
||||
return originalEndsWithNewline ? '\n' : '';
|
||||
}
|
||||
|
||||
const result = lines.join('\n');
|
||||
|
||||
// Only add trailing newline if original content had one
|
||||
return originalEndsWithNewline ? result + '\n' : result;
|
||||
}
|
||||
|
||||
private parseScript(script: string): SedCommandSpec | null {
|
||||
// Handle substitute command: s/pattern/replacement/flags
|
||||
const substituteMatch = script.match(/^(?:(\d+|\$|\/.*?\/)?)?s\/(.*)\/(.*)\/([gimx]*)$/);
|
||||
if (substituteMatch) {
|
||||
return {
|
||||
type: 's',
|
||||
address: substituteMatch[1] || null,
|
||||
pattern: substituteMatch[2],
|
||||
replacement: substituteMatch[3],
|
||||
flags: substituteMatch[4]
|
||||
};
|
||||
}
|
||||
|
||||
// Handle delete command: d or address d
|
||||
const deleteMatch = script.match(/^(?:(\d+|\$|\/.*?\/)?)?d$/);
|
||||
if (deleteMatch) {
|
||||
return {
|
||||
type: 'd',
|
||||
address: deleteMatch[1] || null
|
||||
};
|
||||
}
|
||||
|
||||
// Handle print command: p or address p
|
||||
const printMatch = script.match(/^(?:(\d+|\$|\/.*?\/)?)?p$/);
|
||||
if (printMatch) {
|
||||
return {
|
||||
type: 'p',
|
||||
address: printMatch[1] || null
|
||||
};
|
||||
}
|
||||
|
||||
// Handle quit command: q or address q
|
||||
const quitMatch = script.match(/^(?:(\d+|\$|\/.*?\/)?)?q$/);
|
||||
if (quitMatch) {
|
||||
return {
|
||||
type: 'q',
|
||||
address: quitMatch[1] || null
|
||||
};
|
||||
}
|
||||
|
||||
// Handle append command: a\text or address a\text
|
||||
const appendMatch = script.match(/^(?:(\d+|\$|\/.*?\/)?)?a\\(.*)$/);
|
||||
if (appendMatch) {
|
||||
return {
|
||||
type: 'a',
|
||||
address: appendMatch[1] || null,
|
||||
text: appendMatch[2]
|
||||
};
|
||||
}
|
||||
|
||||
// Handle insert command: i\text or address i\text
|
||||
const insertMatch = script.match(/^(?:(\d+|\$|\/.*?\/)?)?i\\(.*)$/);
|
||||
if (insertMatch) {
|
||||
return {
|
||||
type: 'i',
|
||||
address: insertMatch[1] || null,
|
||||
text: insertMatch[2]
|
||||
};
|
||||
}
|
||||
|
||||
// Handle change command: c\text or address c\text
|
||||
const changeMatch = script.match(/^(?:(\d+|\$|\/.*?\/)?)?c\\(.*)$/);
|
||||
if (changeMatch) {
|
||||
return {
|
||||
type: 'c',
|
||||
address: changeMatch[1] || null,
|
||||
text: changeMatch[2]
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private substitute(line: string, pattern: string, replacement: string, flags: string): string {
|
||||
try {
|
||||
const regexFlags = flags.includes('g') ? 'g' : '';
|
||||
const caseInsensitive = flags.includes('i');
|
||||
|
||||
const regex = new RegExp(pattern, regexFlags + (caseInsensitive ? 'i' : ''));
|
||||
return line.replace(regex, replacement);
|
||||
} catch {
|
||||
// If regex is invalid, return original line
|
||||
return line;
|
||||
}
|
||||
}
|
||||
|
||||
private matchesAddress(lineNumber: number, line: string, address: string | null): boolean {
|
||||
if (!address) {
|
||||
return true; // No address means match all lines
|
||||
}
|
||||
|
||||
// Line number address
|
||||
if (/^\d+$/.test(address)) {
|
||||
return lineNumber === parseInt(address);
|
||||
}
|
||||
|
||||
// Last line address
|
||||
if (address === '$') {
|
||||
// This is tricky to implement without knowing total lines
|
||||
// For now, we'll assume it doesn't match
|
||||
return false;
|
||||
}
|
||||
|
||||
// Pattern address /pattern/
|
||||
const patternMatch = address.match(/^\/(.*)\/$/);
|
||||
if (patternMatch) {
|
||||
try {
|
||||
const regex = new RegExp(patternMatch[1]);
|
||||
return regex.test(line);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private parseArgs(args: string[]): {
|
||||
options: { quiet: boolean; inPlace: boolean };
|
||||
scripts: string[];
|
||||
files: string[]
|
||||
} {
|
||||
const options = { quiet: false, inPlace: false };
|
||||
const scripts: string[] = [];
|
||||
const files: string[] = [];
|
||||
let i = 0;
|
||||
let expectingScript = false;
|
||||
|
||||
while (i < args.length) {
|
||||
const arg = args[i];
|
||||
|
||||
if (arg === '-n') {
|
||||
options.quiet = true;
|
||||
} else if (arg === '-i') {
|
||||
options.inPlace = true;
|
||||
} else if (arg === '-e') {
|
||||
expectingScript = true;
|
||||
} else if (arg.startsWith('-') && arg !== '-') {
|
||||
// Parse combined options
|
||||
for (let j = 1; j < arg.length; j++) {
|
||||
const char = arg[j];
|
||||
switch (char) {
|
||||
case 'n':
|
||||
options.quiet = true;
|
||||
break;
|
||||
case 'i':
|
||||
options.inPlace = true;
|
||||
break;
|
||||
case 'e':
|
||||
expectingScript = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else if (expectingScript || (scripts.length === 0 && !arg.startsWith('-'))) {
|
||||
scripts.push(arg);
|
||||
expectingScript = false;
|
||||
} else {
|
||||
files.push(arg);
|
||||
}
|
||||
|
||||
i++;
|
||||
}
|
||||
|
||||
return { options, scripts, files };
|
||||
}
|
||||
}
|
||||
|
||||
interface SedCommandSpec {
|
||||
type: 's' | 'd' | 'p' | 'q' | 'a' | 'i' | 'c';
|
||||
address?: string | null;
|
||||
pattern?: string;
|
||||
replacement?: string;
|
||||
flags?: string;
|
||||
text?: string;
|
||||
}
|
||||
@@ -61,7 +61,7 @@ describe('configUtils', () => {
|
||||
apiKey: 'sk-test123',
|
||||
},
|
||||
],
|
||||
recentlyUsedModels: ['gpt-4', 'gpt-3.5-turbo'],
|
||||
recentlyUsedModels: ['openai/gpt-4', 'openai/gpt-3.5-turbo'],
|
||||
};
|
||||
|
||||
describe('readAISettings', () => {
|
||||
@@ -97,26 +97,6 @@ describe('configUtils', () => {
|
||||
recentlyUsedModels: [],
|
||||
});
|
||||
});
|
||||
|
||||
it('should migrate from localStorage if VFS file does not exist', async () => {
|
||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found'));
|
||||
vi.mocked(mockFS.stat).mockRejectedValue(new Error('Directory not found'));
|
||||
vi.mocked(mockFS.mkdir).mockResolvedValue(undefined);
|
||||
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
|
||||
|
||||
mockLocalStorage.getItem.mockReturnValue(JSON.stringify(sampleAISettings));
|
||||
|
||||
const result = await readAISettings(mockFS);
|
||||
|
||||
expect(result).toEqual(sampleAISettings);
|
||||
expect(mockLocalStorage.getItem).toHaveBeenCalledWith('ai-settings');
|
||||
expect(mockLocalStorage.removeItem).toHaveBeenCalledWith('ai-settings');
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||
'/config/ai.json',
|
||||
JSON.stringify(sampleAISettings, null, 2),
|
||||
'utf8'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('writeAISettings', () => {
|
||||
@@ -188,26 +168,6 @@ describe('configUtils', () => {
|
||||
corsProxy: 'https://proxy.shakespeare.diy/?url={href}',
|
||||
});
|
||||
});
|
||||
|
||||
it('should migrate from localStorage if VFS file does not exist', async () => {
|
||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found'));
|
||||
vi.mocked(mockFS.stat).mockRejectedValue(new Error('Directory not found'));
|
||||
vi.mocked(mockFS.mkdir).mockResolvedValue(undefined);
|
||||
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
|
||||
|
||||
mockLocalStorage.getItem.mockReturnValue(JSON.stringify(sampleGitSettings));
|
||||
|
||||
const result = await readGitSettings(mockFS);
|
||||
|
||||
expect(result).toEqual(sampleGitSettings);
|
||||
expect(mockLocalStorage.getItem).toHaveBeenCalledWith('git-settings');
|
||||
expect(mockLocalStorage.removeItem).toHaveBeenCalledWith('git-settings');
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||
'/config/git.json',
|
||||
JSON.stringify(sampleGitSettings, null, 2),
|
||||
'utf8'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('writeGitSettings', () => {
|
||||
|
||||
+39
-130
@@ -1,11 +1,40 @@
|
||||
import z from 'zod';
|
||||
import { filteredArray } from '@/lib/schema';
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
import type { AISettings, AIProvider } from '@/contexts/AISettingsContext';
|
||||
import type { AIProvider, AISettings } from '@/contexts/AISettingsContext';
|
||||
import type { GitSettings } from '@/contexts/GitSettingsContext';
|
||||
|
||||
const CONFIG_DIR = '/config';
|
||||
const AI_CONFIG_PATH = `${CONFIG_DIR}/ai.json`;
|
||||
const GIT_CONFIG_PATH = `${CONFIG_DIR}/git.json`;
|
||||
|
||||
const aiProviderSchema: z.ZodType<AIProvider> = z.object({
|
||||
id: z.string(),
|
||||
baseURL: z.string().url(),
|
||||
apiKey: z.string().optional(),
|
||||
nostr: z.boolean().optional(),
|
||||
});
|
||||
|
||||
const providerModelSchema = z.string().regex(
|
||||
/^[^/]+\/.+$/,
|
||||
'Must be in format provider/model (e.g., "openai/gpt-4o")',
|
||||
);
|
||||
|
||||
const aiSettingsSchema = z.object({
|
||||
providers: filteredArray(aiProviderSchema),
|
||||
recentlyUsedModels: filteredArray(providerModelSchema),
|
||||
});
|
||||
|
||||
const gitCredentialSchema = z.object({
|
||||
username: z.string(),
|
||||
password: z.string(),
|
||||
});
|
||||
|
||||
const gitSettingsSchema = z.object({
|
||||
credentials: z.record(z.string(), gitCredentialSchema),
|
||||
corsProxy: z.string().url().catch('https://proxy.shakespeare.diy/?url={href}')
|
||||
});
|
||||
|
||||
/**
|
||||
* Ensures the config directory exists
|
||||
*/
|
||||
@@ -17,49 +46,6 @@ async function ensureConfigDir(fs: JSRuntimeFS): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Migrate AI settings from localStorage to VFS (internal function)
|
||||
*/
|
||||
async function migrateAISettingsFromLocalStorage(fs: JSRuntimeFS): Promise<AISettings | null> {
|
||||
// If not in VFS, try to migrate from localStorage
|
||||
const stored = localStorage.getItem('ai-settings');
|
||||
if (stored) {
|
||||
try {
|
||||
const parsed = JSON.parse(stored);
|
||||
if (parsed && typeof parsed === 'object' && 'providers' in parsed) {
|
||||
// Handle migration from old map format to new array format
|
||||
let providers;
|
||||
if (Array.isArray(parsed.providers)) {
|
||||
providers = parsed.providers;
|
||||
} else if (parsed.providers && typeof parsed.providers === 'object') {
|
||||
// Convert map to array
|
||||
providers = Object.entries(parsed.providers).map(([id, connection]) => ({
|
||||
id,
|
||||
...(connection as Omit<AIProvider, 'id'>),
|
||||
}));
|
||||
} else {
|
||||
providers = [];
|
||||
}
|
||||
|
||||
const settings: AISettings = {
|
||||
providers,
|
||||
recentlyUsedModels: parsed.recentlyUsedModels || [],
|
||||
};
|
||||
|
||||
// Write to VFS and remove from localStorage
|
||||
await writeAISettings(fs, settings);
|
||||
localStorage.removeItem('ai-settings');
|
||||
|
||||
return settings;
|
||||
}
|
||||
} catch {
|
||||
// If parsing fails, return null
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read AI settings from VFS (with automatic migration from localStorage)
|
||||
*/
|
||||
@@ -69,50 +55,16 @@ export async function readAISettings(fs: JSRuntimeFS): Promise<AISettings> {
|
||||
recentlyUsedModels: [],
|
||||
};
|
||||
|
||||
// Try to read from VFS first
|
||||
try {
|
||||
const content = await fs.readFile(AI_CONFIG_PATH, 'utf8');
|
||||
const parsed = JSON.parse(content);
|
||||
|
||||
if (parsed && typeof parsed === 'object' && 'providers' in parsed) {
|
||||
// Handle migration from old map format to new array format
|
||||
let providers;
|
||||
if (Array.isArray(parsed.providers)) {
|
||||
providers = parsed.providers;
|
||||
} else if (parsed.providers && typeof parsed.providers === 'object') {
|
||||
// Convert map to array
|
||||
providers = Object.entries(parsed.providers).map(([id, connection]) => ({
|
||||
id,
|
||||
...(connection as Omit<AIProvider, 'id'>),
|
||||
}));
|
||||
|
||||
// Write back the migrated format
|
||||
const migratedSettings: AISettings = {
|
||||
providers,
|
||||
recentlyUsedModels: parsed.recentlyUsedModels || [],
|
||||
};
|
||||
await writeAISettings(fs, migratedSettings);
|
||||
return migratedSettings;
|
||||
} else {
|
||||
providers = [];
|
||||
}
|
||||
|
||||
return {
|
||||
providers,
|
||||
recentlyUsedModels: parsed.recentlyUsedModels || [],
|
||||
};
|
||||
const data = JSON.parse(content);
|
||||
return aiSettingsSchema.parse(data);
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
console.error('AI settings parsing error:', error.errors);
|
||||
}
|
||||
} catch {
|
||||
// File doesn't exist or is invalid, try migration
|
||||
return defaultSettings;
|
||||
}
|
||||
|
||||
// If not in VFS, try to migrate from localStorage
|
||||
const migratedSettings = await migrateAISettingsFromLocalStorage(fs);
|
||||
if (migratedSettings) {
|
||||
return migratedSettings;
|
||||
}
|
||||
|
||||
return defaultSettings;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -123,35 +75,6 @@ export async function writeAISettings(fs: JSRuntimeFS, settings: AISettings): Pr
|
||||
await fs.writeFile(AI_CONFIG_PATH, JSON.stringify(settings, null, 2), 'utf8');
|
||||
}
|
||||
|
||||
/**
|
||||
* Migrate Git settings from localStorage to VFS (internal function)
|
||||
*/
|
||||
async function migrateGitSettingsFromLocalStorage(fs: JSRuntimeFS): Promise<GitSettings | null> {
|
||||
// If not in VFS, try to migrate from localStorage
|
||||
const stored = localStorage.getItem('git-settings');
|
||||
if (stored) {
|
||||
try {
|
||||
const parsed = JSON.parse(stored);
|
||||
if (parsed && typeof parsed === 'object' && 'credentials' in parsed) {
|
||||
const settings: GitSettings = {
|
||||
credentials: parsed.credentials || {},
|
||||
corsProxy: parsed.corsProxy || 'https://proxy.shakespeare.diy/?url={href}',
|
||||
};
|
||||
|
||||
// Write to VFS and remove from localStorage
|
||||
await writeGitSettings(fs, settings);
|
||||
localStorage.removeItem('git-settings');
|
||||
|
||||
return settings;
|
||||
}
|
||||
} catch {
|
||||
// If parsing fails, return null
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read Git settings from VFS (with automatic migration from localStorage)
|
||||
*/
|
||||
@@ -164,25 +87,11 @@ export async function readGitSettings(fs: JSRuntimeFS): Promise<GitSettings> {
|
||||
// Try to read from VFS first
|
||||
try {
|
||||
const content = await fs.readFile(GIT_CONFIG_PATH, 'utf8');
|
||||
const parsed = JSON.parse(content);
|
||||
|
||||
if (parsed && typeof parsed === 'object' && 'credentials' in parsed) {
|
||||
return {
|
||||
credentials: parsed.credentials || {},
|
||||
corsProxy: parsed.corsProxy || 'https://proxy.shakespeare.diy/?url={href}',
|
||||
};
|
||||
}
|
||||
const data = JSON.parse(content);
|
||||
return gitSettingsSchema.parse(data);
|
||||
} catch {
|
||||
// File doesn't exist or is invalid, try migration
|
||||
return defaultSettings;
|
||||
}
|
||||
|
||||
// If not in VFS, try to migrate from localStorage
|
||||
const migratedSettings = await migrateGitSettingsFromLocalStorage(fs);
|
||||
if (migratedSettings) {
|
||||
return migratedSettings;
|
||||
}
|
||||
|
||||
return defaultSettings;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+74
-14
@@ -908,16 +908,16 @@ export class Git {
|
||||
'#d': [nostrURI.d],
|
||||
};
|
||||
|
||||
const gitRelays = new Set<string>([
|
||||
'wss://git.shakespeare.diy/',
|
||||
// Always prioritize git.shakespeare.diy
|
||||
const shakespeareRelayUrl = 'wss://git.shakespeare.diy/';
|
||||
const otherGitRelays = [
|
||||
'wss://relay.ngit.dev/',
|
||||
'wss://gitnostr.com/',
|
||||
'wss://relay.nostr.band/', // General purpose relay as fallback
|
||||
]);
|
||||
];
|
||||
|
||||
let events: NostrEvent[] = [];
|
||||
|
||||
// Try the specified relay first, then fall back to known Git relays
|
||||
// Try the specified relay first if provided
|
||||
if (nostrURI.relay) {
|
||||
try {
|
||||
events = await this.nostr.relay(nostrURI.relay).query([filter], { signal: AbortSignal.timeout(1000) });
|
||||
@@ -925,11 +925,30 @@ export class Git {
|
||||
console.error(`Error querying relay ${nostrURI.relay}: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
// If no events from specified relay, try git.shakespeare.diy first
|
||||
if (!events.length) {
|
||||
try {
|
||||
events = await this.nostr.group([...gitRelays]).query([filter], { signal: AbortSignal.timeout(5000) });
|
||||
console.log(`Trying git.shakespeare.diy first...`);
|
||||
events = await this.nostr.relay(shakespeareRelayUrl).query([filter], { signal: AbortSignal.timeout(3000) });
|
||||
if (events.length > 0) {
|
||||
console.log(`✓ Found events on ${shakespeareRelayUrl}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Error querying group relays: ${error}`);
|
||||
console.error(`Error querying ${shakespeareRelayUrl}: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
// If still no events, try other git relays
|
||||
if (!events.length) {
|
||||
try {
|
||||
console.log(`Trying other git relays: ${otherGitRelays.join(', ')}`);
|
||||
events = await this.nostr.group(otherGitRelays).query([filter], { signal: AbortSignal.timeout(5000) });
|
||||
if (events.length > 0) {
|
||||
console.log(`✓ Found events on fallback relays`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Error querying fallback relays: ${error}`);
|
||||
}
|
||||
}
|
||||
if (!events.length) {
|
||||
@@ -1313,6 +1332,7 @@ export class Git {
|
||||
dir: options.dir,
|
||||
ref: `refs/heads/${currentBranch}`,
|
||||
value: upstreamCommit,
|
||||
force: true,
|
||||
});
|
||||
|
||||
// Update the working directory
|
||||
@@ -1390,14 +1410,24 @@ export class Git {
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure git.shakespeare.diy is always included and prioritized
|
||||
const shakespeareRelay = 'wss://git.shakespeare.diy/';
|
||||
|
||||
// Remove git.shakespeare.diy from relayUrls if it exists (to avoid duplicates)
|
||||
const filteredRelayUrls = relayUrls.filter(url => url !== shakespeareRelay);
|
||||
|
||||
// Always prioritize git.shakespeare.diy by putting it first
|
||||
relayUrls.unshift(shakespeareRelay);
|
||||
|
||||
// If no relays specified in announcement, use default git-focused relays
|
||||
if (relayUrls.length === 0) {
|
||||
if (filteredRelayUrls.length === 0 && relayUrls.length === 1) {
|
||||
relayUrls.push(
|
||||
'wss://git.shakespeare.diy/',
|
||||
'wss://relay.ngit.dev/',
|
||||
'wss://gitnostr.com/',
|
||||
'wss://relay.nostr.band/'
|
||||
);
|
||||
} else {
|
||||
// Add back the other relays after git.shakespeare.diy
|
||||
relayUrls.push(...filteredRelayUrls);
|
||||
}
|
||||
|
||||
// Get current repository state
|
||||
@@ -1418,12 +1448,42 @@ export class Git {
|
||||
// Publish the state event to Nostr relays
|
||||
console.log(`Publishing repository state to ${relayUrls.length} relays`);
|
||||
|
||||
// Always publish to git.shakespeare.diy first
|
||||
const shakespeareRelayUrl = 'wss://git.shakespeare.diy/';
|
||||
const otherRelays = relayUrls.filter(url => url !== shakespeareRelayUrl);
|
||||
|
||||
try {
|
||||
await this.nostr.group(relayUrls).event(stateEvent);
|
||||
console.log('✓ Repository state published to Nostr successfully');
|
||||
// Publish to git.shakespeare.diy first
|
||||
console.log(`Publishing to ${shakespeareRelayUrl} first...`);
|
||||
await this.nostr.relay(shakespeareRelayUrl).event(stateEvent);
|
||||
console.log(`✓ Repository state published to ${shakespeareRelayUrl} successfully`);
|
||||
|
||||
// Then publish to other relays
|
||||
if (otherRelays.length > 0) {
|
||||
console.log(`Publishing to ${otherRelays.length} additional relays...`);
|
||||
try {
|
||||
await this.nostr.group(otherRelays).event(stateEvent);
|
||||
console.log('✓ Repository state published to additional relays successfully');
|
||||
} catch (error) {
|
||||
console.warn('Failed to publish repository state to some additional relays:', error);
|
||||
// Continue even if publishing to additional relays fails
|
||||
}
|
||||
}
|
||||
|
||||
console.log('✓ Nostr push completed successfully');
|
||||
} catch (error) {
|
||||
console.warn('Failed to publish repository state to some relays:', error);
|
||||
// Continue with Git push even if Nostr publishing partially fails
|
||||
console.error('Failed to publish repository state to git.shakespeare.diy:', error);
|
||||
// If git.shakespeare.diy fails, still try to publish to other relays as fallback
|
||||
if (otherRelays.length > 0) {
|
||||
console.log(`Attempting to publish to ${otherRelays.length} fallback relays...`);
|
||||
try {
|
||||
await this.nostr.group(otherRelays).event(stateEvent);
|
||||
console.log('✓ Repository state published to fallback relays successfully');
|
||||
} catch (fallbackError) {
|
||||
console.warn('Failed to publish repository state to fallback relays:', fallbackError);
|
||||
}
|
||||
}
|
||||
// Don't throw here - continue with Git push even if Nostr publishing fails
|
||||
}
|
||||
|
||||
// Push to each clone URL
|
||||
|
||||
+78
-24
@@ -81,9 +81,6 @@ const resources = {
|
||||
dataSettingsDescription: 'Export files and manage local data',
|
||||
emailUpdates: 'Email Updates',
|
||||
emailUpdatesDescription: 'Subscribe to Shakespeare updates and resources',
|
||||
emailUpdatesDescriptionLong: 'Stay updated with the latest Shakespeare features, tutorials, and resources.',
|
||||
aboutShakespeareSettings: 'About Shakespeare',
|
||||
aboutShakespeareSettingsDescription: 'Information about Shakespeare',
|
||||
|
||||
// Project Sidebar
|
||||
newProject: 'New Project',
|
||||
@@ -186,6 +183,8 @@ const resources = {
|
||||
authentication: 'Authentication',
|
||||
addCustomProviderButton: 'Add Custom Provider',
|
||||
providerExists: 'Provider with this name already exists',
|
||||
agreeToTermsOfService: 'I agree to {{providerName}}’s',
|
||||
termsOfService: 'Terms of Service',
|
||||
custom: 'Custom',
|
||||
connecting: 'Connecting...',
|
||||
connectToGitHub: 'Connect to GitHub',
|
||||
@@ -207,7 +206,6 @@ const resources = {
|
||||
aboutShakespeare: 'About Shakespeare',
|
||||
aboutShakespeareDescription: 'Information about Shakespeare',
|
||||
sourceCode: 'Source Code',
|
||||
viewOnGitLab: 'View on GitLab',
|
||||
description: 'Description',
|
||||
license: 'License',
|
||||
loadingLicense: 'Loading license...',
|
||||
@@ -242,6 +240,17 @@ const resources = {
|
||||
dataClearedSuccessfully: 'Data cleared successfully',
|
||||
dataClearedDescription: 'All local data has been removed. Redirecting to homepage...',
|
||||
failedToClearData: 'Failed to clear data',
|
||||
persistData: 'Persist Data',
|
||||
persistDataDescription: 'Request persistent storage to prevent data loss when browser storage is low. This helps protect your projects and settings.',
|
||||
persistentStorageGranted: 'Persistent storage granted',
|
||||
persistentStorageGrantedDescription: 'Your browser will now protect your data from automatic cleanup.',
|
||||
persistentStorageAlreadyGranted: 'Persistent storage already granted',
|
||||
persistentStorageAlreadyGrantedDescription: 'Your data is already protected from automatic cleanup.',
|
||||
persistentStorageDenied: 'Persistent storage request denied',
|
||||
persistentStorageDeniedDescription: 'Your browser declined the request. Data may still be cleared automatically when storage is low.',
|
||||
persistentStorageNotSupported: 'Persistent storage not supported',
|
||||
persistentStorageNotSupportedDescription: 'Your browser does not support persistent storage requests.',
|
||||
failedToRequestPersistentStorage: 'Failed to request persistent storage',
|
||||
|
||||
// 404 Page
|
||||
pageNotFound: 'Oops! Page not found',
|
||||
@@ -383,9 +392,6 @@ const resources = {
|
||||
dataSettingsDescription: 'Exporte arquivos e gerencie dados locais',
|
||||
emailUpdates: 'Atualizações por Email',
|
||||
emailUpdatesDescription: 'Inscreva-se para receber atualizações e recursos do Shakespeare',
|
||||
emailUpdatesDescriptionLong: 'Mantenha-se atualizado com os recursos mais recentes do Shakespeare, tutoriais e recursos. Enviamos apenas atualizações ocasionais e você pode cancelar a inscrição a qualquer momento.',
|
||||
aboutShakespeareSettings: 'Sobre o Shakespeare',
|
||||
aboutShakespeareSettingsDescription: 'Informações sobre o Shakespeare',
|
||||
|
||||
// Project Sidebar
|
||||
newProject: 'Novo Projeto',
|
||||
@@ -488,6 +494,8 @@ const resources = {
|
||||
authentication: 'Autenticação',
|
||||
addCustomProviderButton: 'Adicionar Provedor Personalizado',
|
||||
providerExists: 'Provedor com este nome já existe',
|
||||
agreeToTermsOfService: 'Concordo com {{providerName}}',
|
||||
termsOfService: 'Termos de Serviço',
|
||||
custom: 'Personalizado',
|
||||
connecting: 'Conectando...',
|
||||
connectToGitHub: 'Conectar ao GitHub',
|
||||
@@ -534,12 +542,22 @@ const resources = {
|
||||
dataClearedSuccessfully: 'Dados limpos com sucesso',
|
||||
dataClearedDescription: 'Todos os dados locais foram removidos. Redirecionando para a página inicial...',
|
||||
failedToClearData: 'Falha ao limpar dados',
|
||||
persistData: 'Persistir Dados',
|
||||
persistDataDescription: 'Solicitar armazenamento persistente para evitar perda de dados quando o armazenamento do navegador estiver baixo. Isso ajuda a proteger seus projetos e configurações.',
|
||||
persistentStorageGranted: 'Armazenamento persistente concedido',
|
||||
persistentStorageGrantedDescription: 'Seu navegador agora protegerá seus dados da limpeza automática.',
|
||||
persistentStorageAlreadyGranted: 'Armazenamento persistente já concedido',
|
||||
persistentStorageAlreadyGrantedDescription: 'Seus dados já estão protegidos da limpeza automática.',
|
||||
persistentStorageDenied: 'Solicitação de armazenamento persistente negada',
|
||||
persistentStorageDeniedDescription: 'Seu navegador recusou a solicitação. Os dados ainda podem ser limpos automaticamente quando o armazenamento estiver baixo.',
|
||||
persistentStorageNotSupported: 'Armazenamento persistente não suportado',
|
||||
persistentStorageNotSupportedDescription: 'Seu navegador não suporta solicitações de armazenamento persistente.',
|
||||
failedToRequestPersistentStorage: 'Falha ao solicitar armazenamento persistente',
|
||||
|
||||
// About Settings
|
||||
aboutShakespeare: 'Sobre o Shakespeare',
|
||||
aboutShakespeareDescription: 'Informações sobre o Shakespeare.',
|
||||
sourceCode: 'Código-fonte',
|
||||
viewOnGitLab: 'Ver no GitLab',
|
||||
description: 'Descrição',
|
||||
license: 'Licença',
|
||||
loadingLicense: 'Carregando licença...',
|
||||
@@ -685,9 +703,6 @@ const resources = {
|
||||
dataSettingsDescription: '导出文件和管理本地数据',
|
||||
emailUpdates: '邮件更新',
|
||||
emailUpdatesDescription: '订阅Shakespeare更新和资源',
|
||||
emailUpdatesDescriptionLong: '及时了解最新的Shakespeare功能、教程和资源。我们只会偶尔发送更新,您可以随时取消订阅。',
|
||||
aboutShakespeareSettings: '关于Shakespeare',
|
||||
aboutShakespeareSettingsDescription: '关于Shakespeare的信息',
|
||||
|
||||
// Project Sidebar
|
||||
newProject: '新项目',
|
||||
@@ -790,6 +805,8 @@ const resources = {
|
||||
authentication: '身份验证',
|
||||
addCustomProviderButton: '添加自定义提供商',
|
||||
providerExists: '此名称的提供商已存在',
|
||||
agreeToTermsOfService: '我同意{{providerName}}',
|
||||
termsOfService: '服务条款',
|
||||
custom: '自定义',
|
||||
connecting: '连接中...',
|
||||
connectToGitHub: '连接到GitHub',
|
||||
@@ -836,12 +853,22 @@ const resources = {
|
||||
dataClearedSuccessfully: '数据清除成功',
|
||||
dataClearedDescription: '所有本地数据已删除。正在重定向到主页...',
|
||||
failedToClearData: '清除数据失败',
|
||||
persistData: '持久化数据',
|
||||
persistDataDescription: '请求持久存储以防止浏览器存储不足时数据丢失。这有助于保护您的项目和设置。',
|
||||
persistentStorageGranted: '已授予持久存储',
|
||||
persistentStorageGrantedDescription: '您的浏览器现在将保护您的数据免受自动清理。',
|
||||
persistentStorageAlreadyGranted: '已授予持久存储',
|
||||
persistentStorageAlreadyGrantedDescription: '您的数据已受到保护,不会被自动清理。',
|
||||
persistentStorageDenied: '持久存储请求被拒绝',
|
||||
persistentStorageDeniedDescription: '您的浏览器拒绝了请求。当存储不足时,数据仍可能被自动清理。',
|
||||
persistentStorageNotSupported: '不支持持久存储',
|
||||
persistentStorageNotSupportedDescription: '您的浏览器不支持持久存储请求。',
|
||||
failedToRequestPersistentStorage: '请求持久存储失败',
|
||||
|
||||
// About Settings
|
||||
aboutShakespeare: '关于Shakespeare',
|
||||
aboutShakespeareDescription: '关于Shakespeare的信息。',
|
||||
sourceCode: '源代码',
|
||||
viewOnGitLab: '在GitLab上查看',
|
||||
description: '描述',
|
||||
license: '许可证',
|
||||
loadingLicense: '加载许可证中...',
|
||||
@@ -987,9 +1014,6 @@ const resources = {
|
||||
dataSettingsDescription: 'Fitar da fayiloli da sarrafa bayanan gida',
|
||||
emailUpdates: 'Sabuntawar Imel',
|
||||
emailUpdatesDescription: 'Yi rajista don karbar sabuntawar Shakespeare da albarkatu',
|
||||
emailUpdatesDescriptionLong: 'Kasance da sabuntawa game da sabbin fasalolin Shakespeare, koyarwa, da albarkatu. Muna aika sabuntawa lokaci-lokaci kawai kuma kuna iya dakatar da rajista koyaushe.',
|
||||
aboutShakespeareSettings: 'Game da Shakespeare',
|
||||
aboutShakespeareSettingsDescription: 'Bayani game da Shakespeare',
|
||||
|
||||
// Project Sidebar
|
||||
newProject: 'Sabon Aikin',
|
||||
@@ -1092,6 +1116,8 @@ const resources = {
|
||||
authentication: 'Tabbatarwa',
|
||||
addCustomProviderButton: 'Ƙara Mai Samarwa na Musamman',
|
||||
providerExists: 'Mai samarwa da wannan suna ya riga ya wanzu',
|
||||
agreeToTermsOfService: 'Na yarda da {{providerName}}',
|
||||
termsOfService: 'Sharuɗɗan Sabis',
|
||||
custom: 'Na Musamman',
|
||||
connecting: 'Ana haɗawa...',
|
||||
connectToGitHub: 'Haɗu da GitHub',
|
||||
@@ -1138,12 +1164,22 @@ const resources = {
|
||||
dataClearedSuccessfully: 'An share bayanai cikin nasara',
|
||||
dataClearedDescription: 'An cire duk bayanan gida. Ana turawa zuwa shafin gida...',
|
||||
failedToClearData: 'Ya gaza share bayanai',
|
||||
persistData: 'Kiyaye Bayanai',
|
||||
persistDataDescription: 'Nemi ajiyar bayanai ta dindindin don hana asarar bayanai lokacin da ajiyar burauzar ta ragu. Wannan yana taimakawa wajen kare ayyukan ku da saitunan.',
|
||||
persistentStorageGranted: 'An ba da ajiyar ta dindindin',
|
||||
persistentStorageGrantedDescription: 'Burauzar ku yanzu za ta kare bayananku daga share mai sarrafa kansa.',
|
||||
persistentStorageAlreadyGranted: 'An riga an ba da ajiyar ta dindindin',
|
||||
persistentStorageAlreadyGrantedDescription: 'An riga an kare bayananku daga share mai sarrafa kansa.',
|
||||
persistentStorageDenied: 'An ki neman ajiyar ta dindindin',
|
||||
persistentStorageDeniedDescription: 'Burauzar ku ta ki bukatar. Ana iya share bayanai ta atomatik lokacin da ajiya ta ragu.',
|
||||
persistentStorageNotSupported: 'Ba a goyan bayan ajiyar ta dindindin ba',
|
||||
persistentStorageNotSupportedDescription: 'Burauzar ku ba ta goyan bayan bukatun ajiyar ta dindindin ba.',
|
||||
failedToRequestPersistentStorage: 'Ya gaza neman ajiyar ta dindindin',
|
||||
|
||||
// About Settings
|
||||
aboutShakespeare: 'Game da Shakespeare',
|
||||
aboutShakespeareDescription: 'Bayani game da Shakespeare.',
|
||||
sourceCode: 'Lambar Tushe',
|
||||
viewOnGitLab: 'Duba akan GitLab',
|
||||
description: 'Bayanin',
|
||||
license: 'Lasisi',
|
||||
loadingLicense: 'Ana lodin lasisi...',
|
||||
@@ -1289,9 +1325,6 @@ const resources = {
|
||||
dataSettingsDescription: 'Gbe awọn faili jade ati ṣakoso data agbegbe',
|
||||
emailUpdates: 'Awọn Imudojuiwọn Imeeli',
|
||||
emailUpdatesDescription: 'Forukọsilẹ fun awọn imudojuiwọn Shakespeare ati awọn ohun elo',
|
||||
emailUpdatesDescriptionLong: 'Wa pẹlu imudojuiwọn pẹlu awọn ẹya Shakespeare tuntun, awọn ikẹkọ, ati awọn ohun elo. A nfi awọn imudojuiwọn lọọrọọ nikan ranṣẹ ati pe o le da forukọsilẹ duro nigbakugba.',
|
||||
aboutShakespeareSettings: 'Nipa Shakespeare',
|
||||
aboutShakespeareSettingsDescription: 'Alaye nipa Shakespeare',
|
||||
|
||||
// Project Sidebar
|
||||
newProject: 'Iṣẹ akanṣe Tuntun',
|
||||
@@ -1394,6 +1427,8 @@ const resources = {
|
||||
authentication: 'Ijẹrisi',
|
||||
addCustomProviderButton: 'Fi Olupese Aṣa kun',
|
||||
providerExists: 'Olupese pẹlu orukọ yii ti wa tẹlẹ',
|
||||
agreeToTermsOfService: 'Mo gba {{providerName}}',
|
||||
termsOfService: 'Awọn Ofin Iṣẹ',
|
||||
custom: 'Aṣa',
|
||||
connecting: 'N so...',
|
||||
connectToGitHub: 'So si GitHub',
|
||||
@@ -1440,12 +1475,22 @@ const resources = {
|
||||
dataClearedSuccessfully: 'Data ti nu ni aṣeyọri',
|
||||
dataClearedDescription: 'Gbogbo data agbegbe ti yọ kuro. N ṣe atunṣe si oju-iwe ile...',
|
||||
failedToClearData: 'O kuna lati nu data',
|
||||
persistData: 'Fi Data Pamọ',
|
||||
persistDataDescription: 'Beere ibi ipamọ ti o wa nigbagbogbo lati yago fun isonu data nigbati ibi ipamọ aṣawakiri ba kere. Eyi ṣe iranlọwọ lati daabobo awọn iṣẹ akanṣe ati awọn eto rẹ.',
|
||||
persistentStorageGranted: 'Ibi ipamọ ti o wa nigbagbogbo ti funni',
|
||||
persistentStorageGrantedDescription: 'Aṣawakiri rẹ yoo daabobo data rẹ lati imukuro adaṣe.',
|
||||
persistentStorageAlreadyGranted: 'Ibi ipamọ ti o wa nigbagbogbo ti funni tẹlẹ',
|
||||
persistentStorageAlreadyGrantedDescription: 'Data rẹ ti wa ni aabo lati imukuro adaṣe.',
|
||||
persistentStorageDenied: 'Ibeere ibi ipamọ ti o wa nigbagbogbo ti kọ',
|
||||
persistentStorageDeniedDescription: 'Aṣawakiri rẹ ti kọ ibeere naa. Data le tun jẹ imukuro adaṣe nigbati ibi ipamọ ba kere.',
|
||||
persistentStorageNotSupported: 'Ibi ipamọ ti o wa nigbagbogbo ko ni atilẹyin',
|
||||
persistentStorageNotSupportedDescription: 'Aṣawakiri rẹ ko ni atilẹyin awọn ibeere ibi ipamọ ti o wa nigbagbogbo.',
|
||||
failedToRequestPersistentStorage: 'O kuna lati beere ibi ipamọ ti o wa nigbagbogbo',
|
||||
|
||||
// About Settings
|
||||
aboutShakespeare: 'Nipa Shakespeare',
|
||||
aboutShakespeareDescription: 'Alaye nipa Shakespeare.',
|
||||
sourceCode: 'Koodu Orisun',
|
||||
viewOnGitLab: 'Wo lori GitLab',
|
||||
description: 'Apejuwe',
|
||||
license: 'Iwe-aṣẹ',
|
||||
loadingLicense: 'N gbe iwe-aṣẹ...',
|
||||
@@ -1586,9 +1631,6 @@ const resources = {
|
||||
dataSettingsDescription: 'Bupụta faịlụ na jikwaa data mpaghara',
|
||||
emailUpdates: 'Nmelite Email',
|
||||
emailUpdatesDescription: 'Debanye aha maka nmelite Shakespeare na akụrụngwa',
|
||||
emailUpdatesDescriptionLong: 'Nọrọ na-emelite na atụmatụ Shakespeare ọhụrụ, nkuzi, na akụrụngwa. Anyị na-eziga naanị nmelite mgbe ụfọdụ ma ị nwere ike ịkwụsị ndebanye aha mgbe ọ bụla.',
|
||||
aboutShakespeareSettings: 'Gbasara Shakespeare',
|
||||
aboutShakespeareSettingsDescription: 'Ozi gbasara Shakespeare',
|
||||
|
||||
// Project Sidebar
|
||||
newProject: 'Ọrụ Ọhụrụ',
|
||||
@@ -1691,6 +1733,8 @@ const resources = {
|
||||
authentication: 'Nkwenye',
|
||||
addCustomProviderButton: 'Tinye Onye Na-enye Omenala',
|
||||
providerExists: 'Onye na-enye nwere aha a adịlarị',
|
||||
agreeToTermsOfService: 'Ekwenyere m na {{providerName}}',
|
||||
termsOfService: 'Usoro Ọrụ',
|
||||
custom: 'Omenala',
|
||||
connecting: 'Na-ejikọ...',
|
||||
connectToGitHub: 'Jikọọ na GitHub',
|
||||
@@ -1737,12 +1781,22 @@ const resources = {
|
||||
dataClearedSuccessfully: 'Ehichapụrụ data nke ọma',
|
||||
dataClearedDescription: 'Ewepụrụ data mpaghara niile. Na-atụgharị gaa na ibe ụlọ...',
|
||||
failedToClearData: 'O dara ihichapụ data',
|
||||
persistData: 'Chekwaa Data Ogologo Oge',
|
||||
persistDataDescription: 'Rịọ nchekwa na-adịgide adịgide iji gbochie mfu data mgbe nchekwa browser dị ala. Nke a na-enyere aka ichebe ọrụ gị na ntọala.',
|
||||
persistentStorageGranted: 'Enyere nchekwa na-adịgide adịgide',
|
||||
persistentStorageGrantedDescription: 'Browser gị ga-echebe data gị ugbu a site na nhicha akpaaka.',
|
||||
persistentStorageAlreadyGranted: 'Enyerela nchekwa na-adịgide adịgide',
|
||||
persistentStorageAlreadyGrantedDescription: 'Echebeela data gị site na nhicha akpaaka.',
|
||||
persistentStorageDenied: 'Ajụrụ arịrịọ nchekwa na-adịgide adịgide',
|
||||
persistentStorageDeniedDescription: 'Browser gị jụrụ arịrịọ ahụ. Enwere ike ihichapụ data akpaaka mgbe nchekwa dị ala.',
|
||||
persistentStorageNotSupported: 'Akwadoghị nchekwa na-adịgide adịgide',
|
||||
persistentStorageNotSupportedDescription: 'Browser gị akwadoghị arịrịọ nchekwa na-adịgide adịgide.',
|
||||
failedToRequestPersistentStorage: 'O dara ịrịọ nchekwa na-adịgide adịgide',
|
||||
|
||||
// About Settings
|
||||
aboutShakespeare: 'Gbasara Shakespeare',
|
||||
aboutShakespeareDescription: 'Ozi gbasara Shakespeare.',
|
||||
sourceCode: 'Koodu Isi',
|
||||
viewOnGitLab: 'Lee na GitLab',
|
||||
description: 'Nkọwa',
|
||||
license: 'Ikike',
|
||||
loadingLicense: 'Na-ebu ikike...',
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* Utility functions for managing persistent storage in the browser
|
||||
*/
|
||||
|
||||
/**
|
||||
* Checks if persistent storage is supported by the browser
|
||||
*/
|
||||
export function isPersistentStorageSupported(): boolean {
|
||||
return 'storage' in navigator && 'persist' in navigator.storage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if persistent storage is already granted
|
||||
*/
|
||||
export async function isPersistentStorageGranted(): Promise<boolean> {
|
||||
if (!isPersistentStorageSupported()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
return await navigator.storage.persisted();
|
||||
} catch (error) {
|
||||
console.warn('Failed to check persistent storage status:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Requests persistent storage from the browser
|
||||
* Returns true if granted, false if denied or not supported
|
||||
*/
|
||||
export async function requestPersistentStorage(): Promise<boolean> {
|
||||
if (!isPersistentStorageSupported()) {
|
||||
console.warn('Persistent storage is not supported in this browser');
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
// Check if already granted
|
||||
const alreadyGranted = await isPersistentStorageGranted();
|
||||
if (alreadyGranted) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Request persistent storage
|
||||
const granted = await navigator.storage.persist();
|
||||
return granted;
|
||||
} catch (error) {
|
||||
console.warn('Failed to request persistent storage:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Automatically requests persistent storage if not already granted
|
||||
* This is intended to be called silently after project creation/cloning
|
||||
* Returns true if persistent storage is available (either already granted or newly granted)
|
||||
*/
|
||||
export async function ensurePersistentStorage(): Promise<boolean> {
|
||||
try {
|
||||
// Check if already granted
|
||||
const alreadyGranted = await isPersistentStorageGranted();
|
||||
if (alreadyGranted) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Only request if supported
|
||||
if (!isPersistentStorageSupported()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Silently request persistent storage
|
||||
const granted = await requestPersistentStorage();
|
||||
|
||||
if (granted) {
|
||||
console.log('Persistent storage granted automatically');
|
||||
} else {
|
||||
console.log('Persistent storage request denied or failed');
|
||||
}
|
||||
|
||||
return granted;
|
||||
} catch (error) {
|
||||
console.warn('Failed to ensure persistent storage:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets current storage usage information
|
||||
*/
|
||||
export async function getStorageInfo(): Promise<{
|
||||
quota: number;
|
||||
usage: number;
|
||||
usageDetails?: Record<string, number>;
|
||||
} | null> {
|
||||
if (!('storage' in navigator)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const estimate = await navigator.storage.estimate();
|
||||
return {
|
||||
quota: estimate.quota || 0,
|
||||
usage: estimate.usage || 0,
|
||||
usageDetails: (estimate as StorageEstimate & { usageDetails?: Record<string, number> }).usageDetails,
|
||||
};
|
||||
} catch (error) {
|
||||
console.warn('Failed to get storage information:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import z from 'zod';
|
||||
import { filteredArray } from './schema';
|
||||
|
||||
describe('filteredArray', () => {
|
||||
it('filters out invalid items and keeps valid ones', () => {
|
||||
const numberSchema = z.number();
|
||||
const schema = filteredArray(numberSchema);
|
||||
|
||||
const input = [1, 'invalid', 2, null, 3, undefined, 4];
|
||||
const result = schema.parse(input);
|
||||
|
||||
expect(result).toEqual([1, 2, 3, 4]);
|
||||
});
|
||||
|
||||
it('returns empty array when all items are invalid', () => {
|
||||
const numberSchema = z.number();
|
||||
const schema = filteredArray(numberSchema);
|
||||
|
||||
const input = ['string', null, undefined, {}, []];
|
||||
const result = schema.parse(input);
|
||||
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it('returns all items when all are valid', () => {
|
||||
const stringSchema = z.string();
|
||||
const schema = filteredArray(stringSchema);
|
||||
|
||||
const input = ['hello', 'world', 'test'];
|
||||
const result = schema.parse(input);
|
||||
|
||||
expect(result).toEqual(['hello', 'world', 'test']);
|
||||
});
|
||||
|
||||
it('works with complex object schemas', () => {
|
||||
const userSchema = z.object({
|
||||
id: z.number(),
|
||||
name: z.string(),
|
||||
email: z.string().email(),
|
||||
});
|
||||
const schema = filteredArray(userSchema);
|
||||
|
||||
const input = [
|
||||
{ id: 1, name: 'John', email: '[email protected]' },
|
||||
{ id: 'invalid', name: 'Jane', email: '[email protected]' }, // invalid id
|
||||
{ id: 2, name: 'Bob', email: 'invalid-email' }, // invalid email
|
||||
{ id: 3, name: 'Alice', email: '[email protected]' },
|
||||
'not an object',
|
||||
null,
|
||||
];
|
||||
|
||||
const result = schema.parse(input);
|
||||
|
||||
expect(result).toEqual([
|
||||
{ id: 1, name: 'John', email: '[email protected]' },
|
||||
{ id: 3, name: 'Alice', email: '[email protected]' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('handles empty array input', () => {
|
||||
const numberSchema = z.number();
|
||||
const schema = filteredArray(numberSchema);
|
||||
|
||||
const result = schema.parse([]);
|
||||
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it('catches non-array input and returns empty array', () => {
|
||||
const numberSchema = z.number();
|
||||
const schema = filteredArray(numberSchema);
|
||||
|
||||
const result1 = schema.parse('not an array');
|
||||
const result2 = schema.parse(null);
|
||||
const result3 = schema.parse(undefined);
|
||||
const result4 = schema.parse(123);
|
||||
|
||||
expect(result1).toEqual([]);
|
||||
expect(result2).toEqual([]);
|
||||
expect(result3).toEqual([]);
|
||||
expect(result4).toEqual([]);
|
||||
});
|
||||
|
||||
it('works with union schemas', () => {
|
||||
const unionSchema = z.union([z.string(), z.number()]);
|
||||
const schema = filteredArray(unionSchema);
|
||||
|
||||
const input = ['hello', 42, true, 'world', null, 99, {}];
|
||||
const result = schema.parse(input);
|
||||
|
||||
expect(result).toEqual(['hello', 42, 'world', 99]);
|
||||
});
|
||||
|
||||
it('preserves transformed values from schema', () => {
|
||||
const transformSchema = z.string().transform((str) => str.toUpperCase());
|
||||
const schema = filteredArray(transformSchema);
|
||||
|
||||
const input = ['hello', 123, 'world', null, 'test'];
|
||||
const result = schema.parse(input);
|
||||
|
||||
expect(result).toEqual(['HELLO', 'WORLD', 'TEST']);
|
||||
});
|
||||
|
||||
it('works with optional fields in object schemas', () => {
|
||||
const optionalSchema = z.object({
|
||||
required: z.string(),
|
||||
optional: z.string().optional(),
|
||||
});
|
||||
const schema = filteredArray(optionalSchema);
|
||||
|
||||
const input = [
|
||||
{ required: 'test1' },
|
||||
{ required: 'test2', optional: 'value' },
|
||||
{ optional: 'value' }, // missing required field
|
||||
{ required: 'test3', optional: undefined },
|
||||
];
|
||||
|
||||
const result = schema.parse(input);
|
||||
|
||||
expect(result).toEqual([
|
||||
{ required: 'test1' },
|
||||
{ required: 'test2', optional: 'value' },
|
||||
{ required: 'test3', optional: undefined },
|
||||
]);
|
||||
});
|
||||
|
||||
it('handles nested arrays', () => {
|
||||
const nestedSchema = z.object({
|
||||
name: z.string(),
|
||||
tags: z.string().array(),
|
||||
});
|
||||
const schema = filteredArray(nestedSchema);
|
||||
|
||||
const input = [
|
||||
{ name: 'item1', tags: ['tag1', 'tag2'] },
|
||||
{ name: 'item2', tags: 'not an array' }, // invalid tags
|
||||
{ name: 'item3', tags: [] },
|
||||
'invalid item',
|
||||
];
|
||||
|
||||
const result = schema.parse(input);
|
||||
|
||||
expect(result).toEqual([
|
||||
{ name: 'item1', tags: ['tag1', 'tag2'] },
|
||||
{ name: 'item3', tags: [] },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
import z from "zod";
|
||||
|
||||
/** Validates individual items in an array, dropping any that aren't valid. */
|
||||
export function filteredArray<T extends z.ZodTypeAny>(schema: T) {
|
||||
return z.any().array().catch([])
|
||||
.transform((arr) => (
|
||||
arr.map((item) => {
|
||||
const parsed = schema.safeParse(item);
|
||||
return parsed.success ? parsed.data : undefined;
|
||||
}).filter((item): item is z.infer<T> => Boolean(item))
|
||||
));
|
||||
}
|
||||
+32
-1
@@ -99,6 +99,36 @@ Users interact with Shakespeare by:
|
||||
5. **Project Management**: Organizing and accessing multiple projects from the homepage
|
||||
6. **Deploying Projects**: Publishing their creations to public URLs (requires Nostr login)
|
||||
|
||||
## Virtual Filesystem Structure
|
||||
|
||||
Shakespeare operates on a browser-based virtual filesystem (VFS) that persists all data in IndexedDB. Understanding this structure helps you navigate and work with projects effectively:
|
||||
|
||||
\`\`\`
|
||||
/
|
||||
├── projects/
|
||||
│ ├── {projectId1}/ # Individual project directory
|
||||
│ │ ├── package.json
|
||||
│ │ ├── src/
|
||||
│ │ ├── public/
|
||||
│ │ └── ... # Project files
|
||||
│ ├── {projectId2}/ # Another project
|
||||
│ │ └── ...
|
||||
│ └── ... # More projects
|
||||
├── config/ # Configuration files
|
||||
│ ├── ai.json # AI provider settings and API keys
|
||||
│ └── git.json # Git credentials and repository settings
|
||||
└── tmp/ # Temporary files and scratch space
|
||||
└── ... # Various temporary files and directories
|
||||
\`\`\`
|
||||
|
||||
### Key VFS Features
|
||||
|
||||
- **Project Isolation**: Each project has its own directory namespace at \`/projects/{projectId}/\`
|
||||
- **Cross-Project Access**: You can view other projects by exploring the \`/projects/\` directory
|
||||
- **Persistent Storage**: All files are stored in the browser's IndexedDB across sessions
|
||||
- **Full POSIX Operations**: Support for read, write, mkdir, rm, and other filesystem operations
|
||||
- **Git Integration**: Projects can be initialized as Git repositories for version control
|
||||
|
||||
## Your Role
|
||||
|
||||
As the AI assistant in Shakespeare, you help users by:
|
||||
@@ -108,8 +138,9 @@ As the AI assistant in Shakespeare, you help users by:
|
||||
- Providing suggestions and best practices
|
||||
- Troubleshooting issues and implementing fixes
|
||||
- Building complete, functional Nostr websites and applications
|
||||
- Learning from existing projects in the VFS to provide better solutions
|
||||
|
||||
The user expects you to handle all technical implementation while they focus on describing their vision and requirements.`;
|
||||
The user expects you to handle all technical implementation while they focus on describing their vision and requirements. You can leverage the knowledge from other projects in the VFS to build better, more sophisticated applications.`;
|
||||
|
||||
// Add available tools to the system prompt
|
||||
const toolNames = tools
|
||||
|
||||
@@ -195,6 +195,25 @@ describe('NpmAddPackageTool', () => {
|
||||
}
|
||||
};
|
||||
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(packageJson, null, 2));
|
||||
|
||||
const result = await tool.execute({ name: 'lodash' });
|
||||
|
||||
// Should not fetch from registry when no version specified and package already installed
|
||||
expect(mockFetch).not.toHaveBeenCalled();
|
||||
expect(mockFS.writeFile).not.toHaveBeenCalled();
|
||||
expect(result).toContain('ℹ️ Package lodash is already installed in dependencies with version ^4.17.21.');
|
||||
});
|
||||
|
||||
it('should handle package already installed with specific version', async () => {
|
||||
const packageJson = {
|
||||
name: 'test-project',
|
||||
version: '1.0.0',
|
||||
dependencies: {
|
||||
'lodash': '^4.17.21'
|
||||
}
|
||||
};
|
||||
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(packageJson, null, 2));
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
@@ -208,10 +227,10 @@ describe('NpmAddPackageTool', () => {
|
||||
})
|
||||
});
|
||||
|
||||
const result = await tool.execute({ name: 'lodash' });
|
||||
const result = await tool.execute({ name: 'lodash', version: '4.17.21' });
|
||||
|
||||
expect(mockFS.writeFile).not.toHaveBeenCalled();
|
||||
expect(result).toContain('ℹ️ Package [email protected] is already installed');
|
||||
expect(result).toContain('ℹ️ Package [email protected] is already installed in dependencies.');
|
||||
});
|
||||
|
||||
it('should handle missing package.json', async () => {
|
||||
|
||||
@@ -88,6 +88,16 @@ export class NpmAddPackageTool implements Tool<NpmAddPackageParams> {
|
||||
throw new Error(`❌ Invalid package.json format. Could not parse JSON.`);
|
||||
}
|
||||
|
||||
// Check if package already exists
|
||||
const dependencyKey = dev ? 'devDependencies' : 'dependencies';
|
||||
const otherKey = dev ? 'dependencies' : 'devDependencies';
|
||||
|
||||
// If no version is specified and package is already installed, it's a no-op
|
||||
if (!version && packageJson[dependencyKey]?.[name]) {
|
||||
const currentVersion = packageJson[dependencyKey][name];
|
||||
return `ℹ️ Package ${name} is already installed in ${dependencyKey} with version ${currentVersion}.`;
|
||||
}
|
||||
|
||||
// Determine version to use and fetch package metadata
|
||||
let targetVersion = version;
|
||||
let packageMetadata: NpmRegistryResponse;
|
||||
@@ -107,10 +117,7 @@ export class NpmAddPackageTool implements Tool<NpmAddPackageParams> {
|
||||
}
|
||||
}
|
||||
|
||||
// Check if package already exists
|
||||
const dependencyKey = dev ? 'devDependencies' : 'dependencies';
|
||||
const otherKey = dev ? 'dependencies' : 'devDependencies';
|
||||
|
||||
// Check if package already exists with the specific version
|
||||
if (packageJson[dependencyKey]?.[name]) {
|
||||
const currentVersion = packageJson[dependencyKey][name];
|
||||
if (currentVersion === `^${targetVersion}`) {
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import {
|
||||
ReadConsoleMessagesTool,
|
||||
addConsoleMessage,
|
||||
clearConsoleMessages,
|
||||
ProjectPreviewConsoleError,
|
||||
addErrorListener,
|
||||
removeErrorListener
|
||||
} from './ReadConsoleMessagesTool';
|
||||
|
||||
describe('ReadConsoleMessagesTool', () => {
|
||||
beforeEach(() => {
|
||||
clearConsoleMessages();
|
||||
// Add test messages
|
||||
addConsoleMessage('log', 'App started');
|
||||
addConsoleMessage('warn', 'Deprecated API used');
|
||||
addConsoleMessage('error', 'Network request failed');
|
||||
addConsoleMessage('info', 'User logged in');
|
||||
});
|
||||
|
||||
it('should return all messages by default', async () => {
|
||||
const tool = new ReadConsoleMessagesTool();
|
||||
const result = await tool.execute({});
|
||||
|
||||
expect(result).toContain('Found 4 console messages');
|
||||
expect(result).toContain('[LOG] App started');
|
||||
expect(result).toContain('[WARN] Deprecated API used');
|
||||
expect(result).toContain('[ERROR] Network request failed');
|
||||
expect(result).toContain('[INFO] User logged in');
|
||||
});
|
||||
|
||||
it('should filter messages by level', async () => {
|
||||
const tool = new ReadConsoleMessagesTool();
|
||||
const result = await tool.execute({ filter: 'error' });
|
||||
|
||||
expect(result).toContain('Found 1 console message (level: error)');
|
||||
expect(result).toContain('[ERROR] Network request failed');
|
||||
expect(result).not.toContain('[LOG] App started');
|
||||
});
|
||||
|
||||
it('should limit number of messages', async () => {
|
||||
const tool = new ReadConsoleMessagesTool();
|
||||
const result = await tool.execute({ limit: 2 });
|
||||
|
||||
expect(result).toContain('Found 2 console messages');
|
||||
// Should get the last 2 messages
|
||||
expect(result).toContain('[ERROR] Network request failed');
|
||||
expect(result).toContain('[INFO] User logged in');
|
||||
expect(result).not.toContain('[LOG] App started');
|
||||
});
|
||||
|
||||
it('should handle no messages found', async () => {
|
||||
clearConsoleMessages();
|
||||
const tool = new ReadConsoleMessagesTool();
|
||||
const result = await tool.execute({});
|
||||
|
||||
expect(result).toBe('No console messages found.');
|
||||
});
|
||||
|
||||
it('should handle no messages found with filter', async () => {
|
||||
const tool = new ReadConsoleMessagesTool();
|
||||
const result = await tool.execute({ filter: 'debug' });
|
||||
|
||||
expect(result).toBe('No console messages found for level: debug.');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ProjectPreviewConsoleError', () => {
|
||||
it('should create error with console logs', () => {
|
||||
const logs = [
|
||||
{ level: 'error' as const, message: 'Test error' }
|
||||
];
|
||||
const error = new ProjectPreviewConsoleError('Test message', logs);
|
||||
|
||||
expect(error.message).toBe('Test message');
|
||||
expect(error.name).toBe('ProjectPreviewConsoleError');
|
||||
expect(error.logs).toEqual(logs);
|
||||
expect(error instanceof Error).toBe(true);
|
||||
expect(error instanceof ProjectPreviewConsoleError).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Console Error Listeners', () => {
|
||||
beforeEach(() => {
|
||||
clearConsoleMessages();
|
||||
});
|
||||
|
||||
it('should trigger error listener when console error is added', async () => {
|
||||
const errorListener = vi.fn();
|
||||
addErrorListener(errorListener);
|
||||
|
||||
// Add an error message
|
||||
addConsoleMessage('error', 'Test error message');
|
||||
|
||||
// Wait a bit for the listener to be called
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
|
||||
expect(errorListener).toHaveBeenCalledTimes(1);
|
||||
expect(errorListener).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
message: 'Console error detected: Test error message',
|
||||
logs: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
level: 'error',
|
||||
message: 'Test error message'
|
||||
})
|
||||
])
|
||||
})
|
||||
);
|
||||
|
||||
removeErrorListener(errorListener);
|
||||
});
|
||||
|
||||
it('should not trigger error listener for non-error messages', async () => {
|
||||
const errorListener = vi.fn();
|
||||
addErrorListener(errorListener);
|
||||
|
||||
// Add non-error messages
|
||||
addConsoleMessage('log', 'Test log message');
|
||||
addConsoleMessage('warn', 'Test warning message');
|
||||
addConsoleMessage('info', 'Test info message');
|
||||
|
||||
// Wait a bit
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
|
||||
expect(errorListener).not.toHaveBeenCalled();
|
||||
|
||||
removeErrorListener(errorListener);
|
||||
});
|
||||
|
||||
it('should remove error listener correctly', async () => {
|
||||
const errorListener = vi.fn();
|
||||
addErrorListener(errorListener);
|
||||
removeErrorListener(errorListener);
|
||||
|
||||
// Add an error message
|
||||
addConsoleMessage('error', 'Test error message');
|
||||
|
||||
// Wait a bit
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
|
||||
expect(errorListener).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should handle listener errors gracefully', async () => {
|
||||
const faultyListener = vi.fn(() => {
|
||||
throw new Error('Listener error');
|
||||
});
|
||||
const workingListener = vi.fn();
|
||||
|
||||
addErrorListener(faultyListener);
|
||||
addErrorListener(workingListener);
|
||||
|
||||
// Should not throw despite faulty listener
|
||||
expect(() => {
|
||||
addConsoleMessage('error', 'Test error message');
|
||||
}).not.toThrow();
|
||||
|
||||
// Wait a bit
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
|
||||
expect(faultyListener).toHaveBeenCalled();
|
||||
expect(workingListener).toHaveBeenCalled();
|
||||
|
||||
removeErrorListener(faultyListener);
|
||||
removeErrorListener(workingListener);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
import { Tool } from './Tool';
|
||||
|
||||
export interface ConsoleMessage {
|
||||
level: 'log' | 'warn' | 'error' | 'info' | 'debug';
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface ReadConsoleMessagesParams {
|
||||
filter?: 'error' | 'warn' | 'info' | 'debug' | 'log' | 'all';
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Custom error class for project preview console errors
|
||||
*/
|
||||
export class ProjectPreviewConsoleError extends Error {
|
||||
public readonly logs: ConsoleMessage[];
|
||||
|
||||
constructor(message: string, logs: ConsoleMessage[]) {
|
||||
super(message);
|
||||
this.name = 'ProjectPreviewConsoleError';
|
||||
this.logs = logs;
|
||||
}
|
||||
}
|
||||
|
||||
// Simple global console messages storage
|
||||
const consoleMessages: ConsoleMessage[] = [];
|
||||
const errorListeners: Array<(error: ProjectPreviewConsoleError) => void> = [];
|
||||
|
||||
export const addConsoleMessage = (level: ConsoleMessage['level'], message: string) => {
|
||||
const consoleMessage: ConsoleMessage = {
|
||||
level,
|
||||
message,
|
||||
};
|
||||
|
||||
consoleMessages.push(consoleMessage);
|
||||
|
||||
// If this is an error, notify listeners
|
||||
if (level === 'error') {
|
||||
const error = new ProjectPreviewConsoleError(
|
||||
`Console error detected: ${message}`,
|
||||
consoleMessages.filter(msg => msg.level === 'error')
|
||||
);
|
||||
|
||||
errorListeners.forEach(listener => {
|
||||
try {
|
||||
listener(error);
|
||||
} catch (err) {
|
||||
console.warn('Error listener failed:', err);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const getConsoleMessages = (): ConsoleMessage[] => {
|
||||
return [...consoleMessages];
|
||||
};
|
||||
|
||||
export const addErrorListener = (listener: (error: ProjectPreviewConsoleError) => void) => {
|
||||
errorListeners.push(listener);
|
||||
};
|
||||
|
||||
export const removeErrorListener = (listener: (error: ProjectPreviewConsoleError) => void) => {
|
||||
const index = errorListeners.indexOf(listener);
|
||||
if (index > -1) {
|
||||
errorListeners.splice(index, 1);
|
||||
}
|
||||
};
|
||||
|
||||
export const clearConsoleMessages = () => {
|
||||
consoleMessages.length = 0;
|
||||
};
|
||||
|
||||
export class ReadConsoleMessagesTool implements Tool<ReadConsoleMessagesParams> {
|
||||
async execute(params: ReadConsoleMessagesParams): Promise<string> {
|
||||
const { filter = 'all', limit } = params;
|
||||
|
||||
// Filter and limit messages in one chain
|
||||
const filteredMessages = getConsoleMessages()
|
||||
.filter(msg => filter === 'all' || msg.level === filter)
|
||||
.slice(limit && limit > 0 ? -limit : 0);
|
||||
|
||||
if (filteredMessages.length === 0) {
|
||||
return `No console messages found${filter !== 'all' ? ` for level: ${filter}` : ''}.`;
|
||||
}
|
||||
|
||||
const formattedMessages = filteredMessages
|
||||
.map(msg => `[${msg.level.toUpperCase()}] ${msg.message}`)
|
||||
.join('\n');
|
||||
|
||||
const plural = filteredMessages.length !== 1 ? 's' : '';
|
||||
const levelInfo = filter !== 'all' ? ` (level: ${filter})` : '';
|
||||
|
||||
return `Found ${filteredMessages.length} console message${plural}${levelInfo}:\n\n${formattedMessages}`;
|
||||
}
|
||||
|
||||
description = 'Read console messages from the project preview. Can filter by level and limit results.';
|
||||
}
|
||||
@@ -44,7 +44,7 @@ describe('ShellTool', () => {
|
||||
});
|
||||
|
||||
it('should have correct tool properties', () => {
|
||||
expect(shellTool.description).toBe('Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl, unzip, hexdump. Supports compound commands with &&, ||, ;, and | operators');
|
||||
expect(shellTool.description).toBe('Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, sed, diff, which, whoami, date, env, clear, git, curl, unzip, hexdump. Supports compound commands with &&, ||, ;, and | operators, and output redirection with > and >> operators');
|
||||
expect(shellTool.inputSchema).toBeDefined();
|
||||
});
|
||||
|
||||
@@ -177,6 +177,57 @@ describe('ShellTool', () => {
|
||||
expect(shellTool.getCurrentWorkingDirectory()).toBe('/test/dir/subdir');
|
||||
});
|
||||
|
||||
describe('output redirection', () => {
|
||||
it('should redirect output to file with > operator', async () => {
|
||||
const result = await shellTool.execute({ command: 'echo "hello world" > test.txt' });
|
||||
|
||||
expect(result).toBe('(no output)');
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith('/test/dir/test.txt', 'hello world\n', 'utf8');
|
||||
});
|
||||
|
||||
it('should append output to file with >> operator', async () => {
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue('existing content\n');
|
||||
|
||||
const result = await shellTool.execute({ command: 'echo "new line" >> test.txt' });
|
||||
|
||||
expect(result).toBe('(no output)');
|
||||
expect(mockFS.readFile).toHaveBeenCalledWith('/test/dir/test.txt', 'utf8');
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith('/test/dir/test.txt', 'existing content\nnew line\n', 'utf8');
|
||||
});
|
||||
|
||||
it('should create new file with >> operator if file does not exist', async () => {
|
||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('ENOENT: no such file or directory'));
|
||||
|
||||
const result = await shellTool.execute({ command: 'echo "first line" >> newfile.txt' });
|
||||
|
||||
expect(result).toBe('(no output)');
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith('/test/dir/newfile.txt', 'first line\n', 'utf8');
|
||||
});
|
||||
|
||||
it('should handle quoted filenames in redirection', async () => {
|
||||
const result = await shellTool.execute({ command: 'echo test > "file with spaces.txt"' });
|
||||
|
||||
expect(result).toBe('(no output)');
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith('/test/dir/file with spaces.txt', 'test\n', 'utf8');
|
||||
});
|
||||
|
||||
it('should handle absolute paths in redirection', async () => {
|
||||
const result = await shellTool.execute({ command: 'echo test > /tmp/absolute.txt' });
|
||||
|
||||
expect(result).toBe('(no output)');
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith('/tmp/absolute.txt', 'test\n', 'utf8');
|
||||
});
|
||||
|
||||
it('should handle redirection errors gracefully', async () => {
|
||||
vi.mocked(mockFS.writeFile).mockRejectedValue(new Error('Permission denied'));
|
||||
|
||||
const result = await shellTool.execute({ command: 'echo test > /readonly/file.txt' });
|
||||
|
||||
expect(result).toContain('Redirection error: Permission denied');
|
||||
expect(result).toContain('Exit code: 1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('compound commands', () => {
|
||||
it('should execute commands with && operator (success case)', async () => {
|
||||
const result = await shellTool.execute({ command: 'pwd && echo hello' });
|
||||
|
||||
+103
-10
@@ -24,6 +24,7 @@ import {
|
||||
MvCommand,
|
||||
PwdCommand,
|
||||
RmCommand,
|
||||
SedCommand,
|
||||
SortCommand,
|
||||
TailCommand,
|
||||
TouchCommand,
|
||||
@@ -48,11 +49,11 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
private git: Git;
|
||||
private commands: Map<string, ShellCommand>;
|
||||
|
||||
readonly description = "Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl, unzip, hexdump. Supports compound commands with &&, ||, ;, and | operators";
|
||||
readonly description = "Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, sed, diff, which, whoami, date, env, clear, git, curl, unzip, hexdump. Supports compound commands with &&, ||, ;, and | operators, and output redirection with > and >> operators";
|
||||
|
||||
readonly inputSchema = z.object({
|
||||
command: z.string().describe(
|
||||
'Shell command to execute, e.g. "cat file.txt", "ls -la", "cd src", "pwd", "sort file.txt", "diff file1 file2", "git status", "git add .", "git commit -m \'message\'", "curl -X GET https://api.example.com", "curl -H \'Content-Type: application/json\' -d \'{"key":"value"}\' https://api.example.com". Supports compound commands with &&, ||, ;, and | operators, e.g. "pwd && ls -la", "cat file.txt | grep pattern", "git add . && git commit -m \'update\'"'
|
||||
'Shell command to execute, e.g. "cat file.txt", "ls -la", "cd src", "pwd", "sort file.txt", "diff file1 file2", "git status", "git add .", "git commit -m \'message\'", "curl -X GET https://api.example.com", "curl -H \'Content-Type: application/json\' -d \'{"key":"value"}\' https://api.example.com". Supports compound commands with &&, ||, ;, and | operators, e.g. "pwd && ls -la", "cat file.txt | grep pattern", "git add . && git commit -m \'update\'". Also supports output redirection with > and >> operators, e.g. "echo hello > file.txt", "ls >> output.log"'
|
||||
),
|
||||
});
|
||||
|
||||
@@ -83,6 +84,7 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
this.registerCommand(new MvCommand(fs));
|
||||
this.registerCommand(new PwdCommand());
|
||||
this.registerCommand(new RmCommand(fs));
|
||||
this.registerCommand(new SedCommand(fs));
|
||||
this.registerCommand(new SortCommand(fs));
|
||||
this.registerCommand(new TailCommand(fs));
|
||||
this.registerCommand(new TouchCommand(fs));
|
||||
@@ -104,17 +106,61 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a command string into command name and arguments
|
||||
* Parse a command string into command name, arguments, and redirection info
|
||||
*/
|
||||
private parseCommand(commandStr: string): { name: string; args: string[] } {
|
||||
// Simple parsing - split by spaces, respecting quoted strings
|
||||
const parts: string[] = [];
|
||||
let current = '';
|
||||
private parseCommand(commandStr: string): { name: string; args: string[]; redirectType?: '>' | '>>'; redirectFile?: string } {
|
||||
// First, check for redirection operators
|
||||
let redirectType: '>' | '>>' | undefined;
|
||||
let redirectFile: string | undefined;
|
||||
let actualCommand = commandStr;
|
||||
|
||||
// Look for redirection operators (outside of quotes)
|
||||
let inQuotes = false;
|
||||
let quoteChar = '';
|
||||
|
||||
for (let i = 0; i < commandStr.length; i++) {
|
||||
const char = commandStr[i];
|
||||
const nextChar = commandStr[i + 1];
|
||||
|
||||
if (!inQuotes && (char === '"' || char === "'")) {
|
||||
inQuotes = true;
|
||||
quoteChar = char;
|
||||
} else if (inQuotes && char === quoteChar) {
|
||||
inQuotes = false;
|
||||
quoteChar = '';
|
||||
} else if (!inQuotes) {
|
||||
if (char === '>' && nextChar === '>') {
|
||||
// >> append redirection
|
||||
redirectType = '>>';
|
||||
actualCommand = commandStr.substring(0, i).trim();
|
||||
redirectFile = commandStr.substring(i + 2).trim();
|
||||
break;
|
||||
} else if (char === '>' && nextChar !== '>') {
|
||||
// > overwrite redirection
|
||||
redirectType = '>';
|
||||
actualCommand = commandStr.substring(0, i).trim();
|
||||
redirectFile = commandStr.substring(i + 1).trim();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Remove quotes from redirect file if present
|
||||
if (redirectFile) {
|
||||
if ((redirectFile.startsWith('"') && redirectFile.endsWith('"')) ||
|
||||
(redirectFile.startsWith("'") && redirectFile.endsWith("'"))) {
|
||||
redirectFile = redirectFile.slice(1, -1);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse the actual command part
|
||||
const parts: string[] = [];
|
||||
let current = '';
|
||||
inQuotes = false;
|
||||
quoteChar = '';
|
||||
|
||||
for (let i = 0; i < actualCommand.length; i++) {
|
||||
const char = actualCommand[i];
|
||||
|
||||
if (!inQuotes && (char === '"' || char === "'")) {
|
||||
inQuotes = true;
|
||||
@@ -137,7 +183,7 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
}
|
||||
|
||||
const [name = '', ...args] = parts;
|
||||
return { name, args };
|
||||
return { name, args, redirectType, redirectFile };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -163,7 +209,7 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
quoteChar = '';
|
||||
current += char;
|
||||
} else if (!inQuotes) {
|
||||
// Check for compound operators
|
||||
// Check for compound operators (but not redirection operators)
|
||||
if (char === '&' && nextChar === '&') {
|
||||
// && operator
|
||||
if (current.trim()) {
|
||||
@@ -212,7 +258,7 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
* Execute a single command and return the result
|
||||
*/
|
||||
private async executeSingleCommand(commandStr: string, input?: string): Promise<{ stdout: string; stderr: string; exitCode: number; newCwd?: string }> {
|
||||
const { name, args: cmdArgs } = this.parseCommand(commandStr);
|
||||
const { name, args: cmdArgs, redirectType, redirectFile } = this.parseCommand(commandStr);
|
||||
|
||||
if (!name) {
|
||||
return { stdout: '', stderr: 'Error: No command specified', exitCode: 1 };
|
||||
@@ -233,6 +279,27 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
// Execute the command
|
||||
const result = await command.execute(cmdArgs, this.cwd, input);
|
||||
|
||||
// Handle redirection if specified
|
||||
if (redirectType && redirectFile) {
|
||||
try {
|
||||
await this.handleRedirection(result.stdout, redirectType, redirectFile);
|
||||
// For redirection, we don't output to stdout
|
||||
return {
|
||||
stdout: '',
|
||||
stderr: result.stderr || '',
|
||||
exitCode: result.exitCode,
|
||||
newCwd: result.newCwd,
|
||||
};
|
||||
} catch (redirectError) {
|
||||
return {
|
||||
stdout: '',
|
||||
stderr: `Redirection error: ${redirectError instanceof Error ? redirectError.message : 'Unknown error'}`,
|
||||
exitCode: 1,
|
||||
newCwd: result.newCwd,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: result.stdout || '',
|
||||
stderr: result.stderr || '',
|
||||
@@ -303,6 +370,32 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
return output || '(no output)';
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle output redirection to a file
|
||||
*/
|
||||
private async handleRedirection(output: string, redirectType: '>' | '>>', redirectFile: string): Promise<void> {
|
||||
// Resolve the file path relative to current working directory
|
||||
const filePath = redirectFile.startsWith('/') ? redirectFile : `${this.cwd}/${redirectFile}`;
|
||||
|
||||
if (redirectType === '>') {
|
||||
// Overwrite the file
|
||||
await this.fs.writeFile(filePath, output, 'utf8');
|
||||
} else if (redirectType === '>>') {
|
||||
// Append to the file
|
||||
try {
|
||||
const existingContent = await this.fs.readFile(filePath, 'utf8');
|
||||
await this.fs.writeFile(filePath, existingContent + output, 'utf8');
|
||||
} catch (error) {
|
||||
// If file doesn't exist, create it
|
||||
if (error instanceof Error && error.message.includes('ENOENT')) {
|
||||
await this.fs.writeFile(filePath, output, 'utf8');
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute compound commands with operators (&&, ||, ;, |)
|
||||
*/
|
||||
|
||||
@@ -9,15 +9,29 @@ class MockFS implements JSRuntimeFS {
|
||||
|
||||
constructor() {
|
||||
// Set up a basic project structure
|
||||
this.dirs.add('/projects');
|
||||
this.dirs.add('/projects/project1');
|
||||
this.dirs.add('/projects/project1/src');
|
||||
this.dirs.add('/projects/project1/.git');
|
||||
this.dirs.add('/projects/project2');
|
||||
this.dirs.add('/projects/project2/src');
|
||||
this.dirs.add('/project');
|
||||
this.dirs.add('/project/.git');
|
||||
this.dirs.add('/project/src');
|
||||
this.dirs.add('/project/node_modules');
|
||||
this.dirs.add('/tmp');
|
||||
|
||||
this.files.set('/projects/project1/package.json', '{"name": "project1"}');
|
||||
this.files.set('/projects/project1/src/index.ts', 'console.log("project1");');
|
||||
this.files.set('/projects/project1/.git/config', '[core]\nrepositoryformatversion = 0');
|
||||
this.files.set('/projects/project1/.git/HEAD', 'ref: refs/heads/main');
|
||||
this.files.set('/projects/project2/package.json', '{"name": "project2"}');
|
||||
this.files.set('/projects/project2/src/main.ts', 'console.log("project2");');
|
||||
this.files.set('/project/package.json', '{"name": "test"}');
|
||||
this.files.set('/project/src/index.ts', 'console.log("hello");');
|
||||
this.files.set('/project/.gitignore', 'node_modules\n.git\n');
|
||||
this.files.set('/project/.git/config', '[core]\nrepositoryformatversion = 0');
|
||||
this.files.set('/project/.git/HEAD', 'ref: refs/heads/main');
|
||||
this.files.set('/tmp/uploaded-file.txt', 'This is an uploaded file');
|
||||
|
||||
// Add binary files for testing
|
||||
@@ -65,12 +79,14 @@ class MockFS implements JSRuntimeFS {
|
||||
async readdir(path: string, options: { withFileTypes: true }): Promise<DirectoryEntry[]>;
|
||||
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]>;
|
||||
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]> {
|
||||
// Normalize path by removing trailing slash
|
||||
const normalizedPath = path.replace(/\/$/, '') || '/';
|
||||
const entries: string[] = [];
|
||||
|
||||
// Find all files and directories that are direct children of this path
|
||||
for (const filePath of this.files.keys()) {
|
||||
if (filePath.startsWith(path + '/')) {
|
||||
const relativePath = filePath.slice(path.length + 1);
|
||||
if (filePath.startsWith(normalizedPath + '/')) {
|
||||
const relativePath = filePath.slice(normalizedPath.length + 1);
|
||||
const parts = relativePath.split('/');
|
||||
if (parts.length === 1) {
|
||||
entries.push(parts[0]);
|
||||
@@ -79,8 +95,8 @@ class MockFS implements JSRuntimeFS {
|
||||
}
|
||||
|
||||
for (const dirPath of this.dirs) {
|
||||
if (dirPath.startsWith(path + '/')) {
|
||||
const relativePath = dirPath.slice(path.length + 1);
|
||||
if (dirPath.startsWith(normalizedPath + '/')) {
|
||||
const relativePath = dirPath.slice(normalizedPath.length + 1);
|
||||
const parts = relativePath.split('/');
|
||||
if (parts.length === 1) {
|
||||
entries.push(parts[0]);
|
||||
@@ -91,8 +107,8 @@ class MockFS implements JSRuntimeFS {
|
||||
if (options?.withFileTypes) {
|
||||
return entries.map(name => ({
|
||||
name,
|
||||
isDirectory: () => this.dirs.has(`${path}/${name}`),
|
||||
isFile: () => this.files.has(`${path}/${name}`)
|
||||
isDirectory: () => this.dirs.has(`${normalizedPath}/${name}`),
|
||||
isFile: () => this.files.has(`${normalizedPath}/${name}`)
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -109,7 +125,10 @@ class MockFS implements JSRuntimeFS {
|
||||
size?: number;
|
||||
mtimeMs?: number;
|
||||
}> {
|
||||
if (this.dirs.has(path)) {
|
||||
// Normalize path by removing trailing slash for directories
|
||||
const normalizedPath = path.replace(/\/$/, '') || '/';
|
||||
|
||||
if (this.dirs.has(normalizedPath)) {
|
||||
return {
|
||||
isDirectory: () => true,
|
||||
isFile: () => false,
|
||||
@@ -118,11 +137,11 @@ class MockFS implements JSRuntimeFS {
|
||||
};
|
||||
}
|
||||
|
||||
if (this.files.has(path)) {
|
||||
if (this.files.has(normalizedPath)) {
|
||||
return {
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
size: this.files.get(path)!.length,
|
||||
size: this.files.get(normalizedPath)!.length,
|
||||
mtimeMs: Date.now()
|
||||
};
|
||||
}
|
||||
@@ -167,14 +186,13 @@ describe('TextEditorViewTool', () => {
|
||||
tool = new TextEditorViewTool(mockFS, '/project');
|
||||
});
|
||||
|
||||
it('should handle viewing current directory without ignore library errors', async () => {
|
||||
it('should handle viewing current directory', async () => {
|
||||
const result = await tool.execute({ path: '.' });
|
||||
|
||||
expect(result).toContain('src/');
|
||||
expect(result).toContain('package.json');
|
||||
// .git should be filtered out by gitignore, but .gitignore should be present
|
||||
expect(result).toContain('.gitignore');
|
||||
expect(result).not.toContain('.git/'); // Check for .git directory specifically
|
||||
expect(result).toContain('.git/'); // .git directory should now be visible
|
||||
});
|
||||
|
||||
it('should handle viewing subdirectory', async () => {
|
||||
@@ -242,4 +260,73 @@ describe('TextEditorViewTool', () => {
|
||||
expect(result).toContain('[Binary file: JPG file');
|
||||
expect(result).toContain('This appears to be a binary file and cannot be displayed as text.');
|
||||
});
|
||||
|
||||
it('should show only project directories when viewing /projects', async () => {
|
||||
const result = await tool.execute({ path: '/projects' });
|
||||
|
||||
// Should show the project directories
|
||||
expect(result).toContain('project1/');
|
||||
expect(result).toContain('project2/');
|
||||
|
||||
// Should NOT show the contents of the project directories (depth 1 only)
|
||||
expect(result).not.toContain('package.json');
|
||||
expect(result).not.toContain('src/');
|
||||
expect(result).not.toContain('index.ts');
|
||||
expect(result).not.toContain('main.ts');
|
||||
});
|
||||
|
||||
it('should show only project directories when viewing /projects/', async () => {
|
||||
const result = await tool.execute({ path: '/projects/' });
|
||||
|
||||
// Should show the project directories
|
||||
expect(result).toContain('project1/');
|
||||
expect(result).toContain('project2/');
|
||||
|
||||
// Should NOT show the contents of the project directories (depth 1 only)
|
||||
expect(result).not.toContain('package.json');
|
||||
expect(result).not.toContain('src/');
|
||||
expect(result).not.toContain('index.ts');
|
||||
expect(result).not.toContain('main.ts');
|
||||
});
|
||||
|
||||
it('should show .git directory but not traverse its contents when viewing project root', async () => {
|
||||
const result = await tool.execute({ path: '/project' });
|
||||
|
||||
// Should show the .git directory
|
||||
expect(result).toContain('.git/');
|
||||
|
||||
// Should show "..." under .git instead of its contents
|
||||
expect(result).toContain('...');
|
||||
|
||||
// Should NOT show .git file contents
|
||||
expect(result).not.toContain('config');
|
||||
expect(result).not.toContain('HEAD');
|
||||
expect(result).not.toContain('repositoryformatversion');
|
||||
|
||||
// Should still show other directory contents normally
|
||||
expect(result).toContain('src/');
|
||||
expect(result).toContain('package.json');
|
||||
});
|
||||
|
||||
it('should show .git contents when explicitly viewing .git directory', async () => {
|
||||
const result = await tool.execute({ path: '/project/.git' });
|
||||
|
||||
// Should show the .git file contents when explicitly requested
|
||||
expect(result).toContain('config');
|
||||
expect(result).toContain('HEAD');
|
||||
|
||||
// Should NOT show "..." when explicitly viewing .git
|
||||
expect(result).not.toContain('...');
|
||||
});
|
||||
|
||||
it('should show .git contents when explicitly viewing .git with relative path', async () => {
|
||||
const result = await tool.execute({ path: '.git' });
|
||||
|
||||
// Should show the .git file contents when explicitly requested
|
||||
expect(result).toContain('config');
|
||||
expect(result).toContain('HEAD');
|
||||
|
||||
// Should NOT show "..." when explicitly viewing .git
|
||||
expect(result).not.toContain('...');
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,4 @@
|
||||
import { join } from "path-browserify";
|
||||
import ignore from "ignore";
|
||||
import { z } from "zod";
|
||||
|
||||
import type { Tool } from "./Tool";
|
||||
@@ -53,9 +52,19 @@ export class TextEditorViewTool implements Tool<TextEditorViewParams> {
|
||||
const stats = await this.fs.stat(absolutePath);
|
||||
|
||||
if (stats.isDirectory()) {
|
||||
// Special handling for /projects directory - only show project directories, not their contents
|
||||
const normalizedPath = absolutePath.replace(/\/$/, ''); // Remove trailing slash
|
||||
if (normalizedPath === '/projects') {
|
||||
const tree = await this.generateDirectoryTree(absolutePath, "", 1); // Only show immediate children
|
||||
return tree;
|
||||
}
|
||||
|
||||
// Check if we're starting from a .git directory
|
||||
const isGitRoot = absolutePath.endsWith('/.git') || absolutePath === '.git';
|
||||
|
||||
// If it's a directory, generate a tree-like listing
|
||||
// Note: start_line and end_line are ignored for directories
|
||||
const tree = await this.generateDirectoryTree(absolutePath);
|
||||
const tree = await this.generateDirectoryTree(absolutePath, "", 3, 0, isGitRoot);
|
||||
return tree;
|
||||
}
|
||||
|
||||
@@ -111,30 +120,17 @@ export class TextEditorViewTool implements Tool<TextEditorViewParams> {
|
||||
prefix: string = "",
|
||||
maxDepth: number = 3,
|
||||
currentDepth: number = 0,
|
||||
ignoreFilter?: (path: string) => boolean,
|
||||
isGitRoot: boolean = false,
|
||||
): Promise<string> {
|
||||
if (currentDepth >= maxDepth) {
|
||||
return prefix + "...\n";
|
||||
}
|
||||
|
||||
// Create ignore filter on first call (root level)
|
||||
if (!ignoreFilter) {
|
||||
ignoreFilter = await this.createIgnoreFilter();
|
||||
}
|
||||
|
||||
try {
|
||||
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
|
||||
|
||||
// Filter entries using gitignore patterns
|
||||
const filteredEntries = entries.filter((entry) => {
|
||||
// Calculate relative path from the project root (cwd)
|
||||
const fullEntryPath = join(dirPath, entry.name);
|
||||
const entryPath = this.makeRelativeToCwd(fullEntryPath);
|
||||
return ignoreFilter!(entryPath);
|
||||
});
|
||||
|
||||
// Sort entries: directories first, then files, both alphabetically
|
||||
filteredEntries.sort((a, b) => {
|
||||
entries.sort((a, b) => {
|
||||
if (a.isDirectory() && !b.isDirectory()) return -1;
|
||||
if (!a.isDirectory() && b.isDirectory()) return 1;
|
||||
return a.name.localeCompare(b.name);
|
||||
@@ -142,22 +138,28 @@ export class TextEditorViewTool implements Tool<TextEditorViewParams> {
|
||||
|
||||
let result = "";
|
||||
|
||||
for (let i = 0; i < filteredEntries.length; i++) {
|
||||
const entry = filteredEntries[i]!;
|
||||
const isLastEntry = i === filteredEntries.length - 1;
|
||||
for (let i = 0; i < entries.length; i++) {
|
||||
const entry = entries[i]!
|
||||
const isLastEntry = i === entries.length - 1;
|
||||
const connector = isLastEntry ? "└── " : "├── ";
|
||||
const nextPrefix = prefix + (isLastEntry ? " " : "│ ");
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
result += prefix + connector + entry.name + "/\n";
|
||||
const subPath = join(dirPath, entry.name);
|
||||
result += await this.generateDirectoryTree(
|
||||
subPath,
|
||||
nextPrefix,
|
||||
maxDepth,
|
||||
currentDepth + 1,
|
||||
ignoreFilter,
|
||||
);
|
||||
|
||||
// Special handling for .git directories - don't traverse unless we started from .git
|
||||
if (entry.name === '.git' && !isGitRoot) {
|
||||
result += nextPrefix + "...\n";
|
||||
} else {
|
||||
const subPath = join(dirPath, entry.name);
|
||||
result += await this.generateDirectoryTree(
|
||||
subPath,
|
||||
nextPrefix,
|
||||
maxDepth,
|
||||
currentDepth + 1,
|
||||
isGitRoot,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
result += prefix + connector + entry.name + "\n";
|
||||
}
|
||||
@@ -169,55 +171,7 @@ export class TextEditorViewTool implements Tool<TextEditorViewParams> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an ignore filter based on .gitignore files
|
||||
*/
|
||||
private async createIgnoreFilter(): Promise<(path: string) => boolean> {
|
||||
const ig = ignore();
|
||||
|
||||
// Always ignore .git directory
|
||||
ig.add(".git");
|
||||
|
||||
try {
|
||||
// Try to read .gitignore file
|
||||
const gitignoreContent = await this.fs.readFile(".gitignore", "utf8");
|
||||
ig.add(gitignoreContent);
|
||||
} catch {
|
||||
// If there's an error reading .gitignore, just proceed without it
|
||||
}
|
||||
|
||||
return (path: string) => !ig.ignores(path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert an absolute path to a relative path from the current working directory
|
||||
*/
|
||||
private makeRelativeToCwd(absolutePath: string): string {
|
||||
// Handle relative paths that start with "./"
|
||||
if (absolutePath.startsWith('./')) {
|
||||
return absolutePath.slice(2); // Remove "./" prefix
|
||||
}
|
||||
|
||||
// Handle the current directory case
|
||||
if (absolutePath === '.') {
|
||||
return '.';
|
||||
}
|
||||
|
||||
// If the path starts with the cwd, remove the cwd prefix
|
||||
if (absolutePath.startsWith(this.cwd)) {
|
||||
let relativePath = absolutePath.slice(this.cwd.length);
|
||||
// Remove leading slash if present
|
||||
if (relativePath.startsWith('/')) {
|
||||
relativePath = relativePath.slice(1);
|
||||
}
|
||||
// Return '.' for empty path (current directory)
|
||||
return relativePath || '.';
|
||||
}
|
||||
|
||||
// If it doesn't start with cwd, just return the path as-is
|
||||
// This handles cases where we might have relative paths already
|
||||
return absolutePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a file is likely to be binary based on file extension and content sampling
|
||||
|
||||
+73
-83
@@ -24,6 +24,7 @@ import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { PasswordInput } from '@/components/ui/password-input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
|
||||
import { CreditsBadge } from '@/components/CreditsBadge';
|
||||
import { CreditsDialog } from '@/components/CreditsDialog';
|
||||
@@ -33,65 +34,7 @@ import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNavigate, Link } from 'react-router-dom';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
interface PresetProvider {
|
||||
id: string;
|
||||
name: string;
|
||||
baseURL: string;
|
||||
apiKeysURL?: string;
|
||||
nostr?: boolean;
|
||||
}
|
||||
|
||||
const PRESET_PROVIDERS: PresetProvider[] = [
|
||||
{
|
||||
id: "shakespeare",
|
||||
name: "Shakespeare AI",
|
||||
baseURL: "https://ai.shakespeare.diy/v1",
|
||||
nostr: true,
|
||||
},
|
||||
{
|
||||
id: "openrouter",
|
||||
name: "OpenRouter",
|
||||
baseURL: "https://openrouter.ai/api/v1",
|
||||
apiKeysURL: "https://openrouter.ai/settings/keys",
|
||||
},
|
||||
{
|
||||
id: "ppq",
|
||||
name: "PayPerQ",
|
||||
baseURL: "https://api.ppq.ai",
|
||||
apiKeysURL: "https://ppq.ai/api-docs",
|
||||
},
|
||||
{
|
||||
id: "routstr",
|
||||
name: "Routstr",
|
||||
baseURL: "https://api.routstr.com/v1",
|
||||
apiKeysURL: "https://chat.routstr.com/",
|
||||
},
|
||||
{
|
||||
id: "zai",
|
||||
name: "Z.ai",
|
||||
baseURL: "https://api.z.ai/api/paas/v4",
|
||||
apiKeysURL: "https://z.ai/manage-apikey/apikey-list",
|
||||
},
|
||||
{
|
||||
id: "openai",
|
||||
name: "OpenAI",
|
||||
baseURL: "https://api.openai.com/v1",
|
||||
apiKeysURL: "https://platform.openai.com/api-keys",
|
||||
},
|
||||
{
|
||||
id: "anthropic",
|
||||
name: "Anthropic",
|
||||
baseURL: "https://api.anthropic.com/v1",
|
||||
apiKeysURL: "https://console.anthropic.com/settings/keys",
|
||||
},
|
||||
{
|
||||
id: "xai",
|
||||
name: "xAI",
|
||||
baseURL: "https://api.x.ai/v1",
|
||||
apiKeysURL: "https://console.x.ai",
|
||||
},
|
||||
];
|
||||
import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets';
|
||||
|
||||
interface SortableProviderItemProps {
|
||||
provider: AIProvider;
|
||||
@@ -219,6 +162,7 @@ export function AISettings() {
|
||||
const [customApiKey, setCustomApiKey] = useState('');
|
||||
const [customAuthMethod, setCustomAuthMethod] = useState<'api-key' | 'nostr'>('api-key');
|
||||
const [presetApiKeys, setPresetApiKeys] = useState<Record<string, string>>({});
|
||||
const [presetTermsAgreements, setPresetTermsAgreements] = useState<Record<string, boolean>>({});
|
||||
const [activeCreditsDialog, setActiveCreditsDialog] = useState<string | null>(null);
|
||||
|
||||
const sensors = useSensors(
|
||||
@@ -231,6 +175,9 @@ export function AISettings() {
|
||||
const handleAddPresetProvider = (preset: PresetProvider) => {
|
||||
const apiKey = presetApiKeys[preset.id] as string | undefined;
|
||||
|
||||
// Check if user agreed to terms
|
||||
if (!presetTermsAgreements[preset.id]) return;
|
||||
|
||||
const newProvider: AIProvider = {
|
||||
id: preset.id,
|
||||
baseURL: preset.baseURL,
|
||||
@@ -246,11 +193,15 @@ export function AISettings() {
|
||||
// Auto-save: Add provider immediately to persistent storage
|
||||
setProvider(newProvider);
|
||||
|
||||
// Clear the API key input for this preset
|
||||
// Clear the API key input and terms agreement for this preset
|
||||
setPresetApiKeys(prev => ({
|
||||
...prev,
|
||||
[preset.id]: '',
|
||||
}));
|
||||
setPresetTermsAgreements(prev => ({
|
||||
...prev,
|
||||
[preset.id]: false,
|
||||
}));
|
||||
};
|
||||
|
||||
const handleAddCustomProvider = () => {
|
||||
@@ -305,7 +256,7 @@ export function AISettings() {
|
||||
};
|
||||
|
||||
const configuredProviderIds = settings.providers.map(p => p.id);
|
||||
const availablePresets = PRESET_PROVIDERS.filter(preset => !configuredProviderIds.includes(preset.id));
|
||||
const availablePresets = AI_PROVIDER_PRESETS.filter(preset => !configuredProviderIds.includes(preset.id));
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6">
|
||||
@@ -360,7 +311,7 @@ export function AISettings() {
|
||||
>
|
||||
<Accordion type="multiple" className="w-full space-y-2">
|
||||
{settings.providers.map((provider) => {
|
||||
const preset = PRESET_PROVIDERS.find(p => p.id === provider.id);
|
||||
const preset = AI_PROVIDER_PRESETS.find(p => p.id === provider.id);
|
||||
|
||||
return (
|
||||
<SortableProviderItem
|
||||
@@ -420,30 +371,69 @@ export function AISettings() {
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex gap-2">
|
||||
{!preset.nostr && (
|
||||
<PasswordInput
|
||||
placeholder={preset.id === "routstr" ? t('enterCashuToken') : t('enterApiKey')}
|
||||
className="flex-1"
|
||||
value={presetApiKeys[preset.id] || ''}
|
||||
onChange={(e) => setPresetApiKeys(prev => ({
|
||||
<div className="space-y-2">
|
||||
<div className="flex gap-2">
|
||||
{!preset.nostr && (
|
||||
<PasswordInput
|
||||
placeholder={preset.id === "routstr" ? t('enterCashuToken') : t('enterApiKey')}
|
||||
className="flex-1"
|
||||
value={presetApiKeys[preset.id] || ''}
|
||||
onChange={(e) => setPresetApiKeys(prev => ({
|
||||
...prev,
|
||||
[preset.id]: e.target.value,
|
||||
}))}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' &&
|
||||
presetApiKeys[preset.id]?.trim() &&
|
||||
presetTermsAgreements[preset.id]) {
|
||||
handleAddPresetProvider(preset);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<Button
|
||||
onClick={() => handleAddPresetProvider(preset)}
|
||||
disabled={
|
||||
!presetTermsAgreements[preset.id] ||
|
||||
(!!preset.apiKeysURL && !presetApiKeys[preset.id]?.trim())
|
||||
}
|
||||
className={preset.nostr ? "w-full" : "h-10 px-4 ml-auto"}
|
||||
>
|
||||
{t('add')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Terms of Service Agreement */}
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Checkbox
|
||||
id={`agree-terms-${preset.id}`}
|
||||
checked={presetTermsAgreements[preset.id] || false}
|
||||
onCheckedChange={(checked) => setPresetTermsAgreements(prev => ({
|
||||
...prev,
|
||||
[preset.id]: e.target.value,
|
||||
[preset.id]: checked === true,
|
||||
}))}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim()) {
|
||||
handleAddPresetProvider(preset);
|
||||
}
|
||||
}}
|
||||
className="size-3 [&_svg]:size-3"
|
||||
/>
|
||||
)}
|
||||
<Button
|
||||
onClick={() => handleAddPresetProvider(preset)}
|
||||
disabled={!!preset.apiKeysURL && !presetApiKeys[preset.id]?.trim()}
|
||||
className={preset.nostr ? "w-full" : "h-10 px-4 ml-auto"}
|
||||
>
|
||||
{t('add')}
|
||||
</Button>
|
||||
<label
|
||||
htmlFor={`agree-terms-${preset.id}`}
|
||||
className="text-xs text-muted-foreground leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
|
||||
>
|
||||
{t('agreeToTermsOfService', { providerName: preset.name })}{' '}
|
||||
{preset.tosURL ? (
|
||||
<a
|
||||
href={preset.tosURL}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-muted-foreground underline hover:text-foreground hover:no-underline"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{t('termsOfService')}
|
||||
</a>
|
||||
) : (
|
||||
t('termsOfService')
|
||||
)}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { AboutSettings } from './AboutSettings';
|
||||
|
||||
// Mock fetch
|
||||
global.fetch = vi.fn();
|
||||
|
||||
describe('AboutSettings', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders about settings page with project information', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<AboutSettings />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('About Shakespeare')).toBeInTheDocument();
|
||||
expect(screen.getByText(/Information about Shakespeare/)).toBeInTheDocument();
|
||||
expect(screen.getByText('Source Code')).toBeInTheDocument();
|
||||
expect(screen.getByText('View on GitLab')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('fetches and displays license text', async () => {
|
||||
const mockLicense = 'MIT License\n\nCopyright (c) 2024 Shakespeare';
|
||||
const mockFetch = global.fetch as ReturnType<typeof vi.fn>;
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
text: () => Promise.resolve(mockLicense),
|
||||
} as Response);
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<AboutSettings />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Initially shows loading
|
||||
expect(screen.getByText('Loading license...')).toBeInTheDocument();
|
||||
|
||||
// Wait for license to load
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/MIT License/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/Copyright \(c\) 2024 Shakespeare/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Verify fetch was called with correct URL
|
||||
expect(global.fetch).toHaveBeenCalledWith('/LICENSE.txt');
|
||||
});
|
||||
|
||||
it('shows error when license fetch fails', async () => {
|
||||
const mockFetch = global.fetch as ReturnType<typeof vi.fn>;
|
||||
mockFetch.mockRejectedValueOnce(new Error('Network error'));
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<AboutSettings />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Wait for error to appear
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/Failed to load license/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
+53
-63
@@ -1,12 +1,12 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Info, ExternalLink, Loader2, AlertTriangle, ArrowLeft } from 'lucide-react';
|
||||
import { Info, ExternalLink, Loader2, AlertTriangle, ArrowLeft, Code } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { EmailSubscription } from '@/components/EmailSubscription';
|
||||
|
||||
export function AboutSettings() {
|
||||
const { t } = useTranslation();
|
||||
@@ -22,7 +22,7 @@ export function AboutSettings() {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
const response = await fetch('/LICENSE.txt');
|
||||
const response = await fetch('/LICENSE.html');
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch license: ${response.status} ${response.statusText}`);
|
||||
@@ -78,66 +78,56 @@ export function AboutSettings() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-4">
|
||||
{/* Project Information */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Info className="h-5 w-5" />
|
||||
{t('sourceCode')}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div>
|
||||
<Button
|
||||
variant="outline"
|
||||
asChild
|
||||
className="w-full sm:w-auto"
|
||||
>
|
||||
<a
|
||||
href="https://gitlab.com/soapbox-pub/act2"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
{t('viewOnGitLab')}
|
||||
</a>
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<div className="space-y-6 max-w-xl">
|
||||
{/* Email Updates */}
|
||||
<EmailSubscription />
|
||||
|
||||
{/* License */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Info className="h-5 w-5" />
|
||||
{t('license')}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isLoading ? (
|
||||
<div className="flex items-center gap-2 text-muted-foreground py-4">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
<span className="text-sm">{t('loadingLicense')}</span>
|
||||
</div>
|
||||
) : error ? (
|
||||
<Alert variant="destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
{t('failedToLoadLicense')}: {error}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
) : license ? (
|
||||
<ScrollArea className="h-96 w-full rounded-md border p-4">
|
||||
<pre className="text-xs font-mono whitespace-pre-wrap break-words">
|
||||
{license}
|
||||
</pre>
|
||||
</ScrollArea>
|
||||
) : null}
|
||||
</CardContent>
|
||||
</Card>
|
||||
<div className="space-y-3">
|
||||
{/* Project Information */}
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full h-12 flex items-center gap-2 justify-start text-base"
|
||||
asChild
|
||||
>
|
||||
<a href="https://gitlab.com/soapbox-pub/shakespeare" target="_blank">
|
||||
<Code className="!size-5" />
|
||||
{t('sourceCode')}
|
||||
<ExternalLink className="ml-auto" />
|
||||
</a>
|
||||
</Button>
|
||||
|
||||
{/* License */}
|
||||
<Accordion type="single" collapsible className="w-full">
|
||||
<AccordionItem value="license-text" className="border rounded-lg">
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<div className="flex items-center gap-2">
|
||||
<Info className="h-5 w-5" />
|
||||
{t('license')}
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
{isLoading ? (
|
||||
<div className="flex items-center gap-2 text-muted-foreground py-4">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
<span className="text-sm">{t('loadingLicense')}</span>
|
||||
</div>
|
||||
) : error ? (
|
||||
<Alert variant="destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
{t('failedToLoadLicense')}: {error}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
) : license ? (
|
||||
<div
|
||||
className="prose text-sm dark:prose-invert mx-auto"
|
||||
dangerouslySetInnerHTML={{ __html: license }}
|
||||
/>
|
||||
) : null}
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
+51
-2
@@ -4,11 +4,12 @@ import { useTranslation } from 'react-i18next';
|
||||
import { AppLayout } from '@/components/AppLayout';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { GitBranch, Loader2, AlertCircle } from 'lucide-react';
|
||||
import { GitBranch, Loader2, AlertCircle, FileArchive, MoreHorizontal } from 'lucide-react';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
|
||||
import { ZipImportDialog } from '@/components/ZipImportDialog';
|
||||
import { useSeoMeta } from '@unhead/react';
|
||||
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from '@/components/ui/dropdown-menu';
|
||||
|
||||
export default function Clone() {
|
||||
const { t } = useTranslation();
|
||||
@@ -20,6 +21,7 @@ export default function Clone() {
|
||||
const projectsManager = useProjectsManager();
|
||||
const { toast } = useToast();
|
||||
const autoCloneInitiatedRef = useRef(false);
|
||||
const [isZipDialogOpen, setIsZipDialogOpen] = useState(false);
|
||||
|
||||
useSeoMeta({
|
||||
title: `${t('importRepository')} - Shakespeare`,
|
||||
@@ -171,6 +173,25 @@ export default function Clone() {
|
||||
}
|
||||
}, [handleClone, searchParams]);
|
||||
|
||||
const handleImportZip = async (file: File, overwrite = false, projectId?: string) => {
|
||||
try {
|
||||
// Import project from zip file
|
||||
const project = await projectsManager.importProjectFromZip(file, projectId, overwrite);
|
||||
|
||||
// Show success toast
|
||||
toast({
|
||||
title: overwrite ? "Project Overwritten Successfully" : "Project Imported Successfully",
|
||||
description: `"${project.name}" has been ${overwrite ? 'overwritten' : 'imported'} and is ready to use.`,
|
||||
});
|
||||
|
||||
// Navigate to the imported project
|
||||
navigate(`/project/${project.id}`);
|
||||
} catch (error) {
|
||||
console.error('Failed to import project:', error);
|
||||
throw error; // Re-throw to let the dialog handle the error display
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<AppLayout title={t('importRepository')}>
|
||||
<div className="max-w-2xl mx-auto">
|
||||
@@ -226,7 +247,35 @@ export default function Clone() {
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Import ZIP File Link */}
|
||||
<div className="mt-8 text-center">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="text-muted-foreground hover:text-primary hover:bg-transparent">
|
||||
<MoreHorizontal className="h-5 w-5" />
|
||||
<span className="sr-only">More options</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="center">
|
||||
<DropdownMenuItem
|
||||
className="flex items-center gap-2 w-full"
|
||||
onClick={() => setIsZipDialogOpen(true)}
|
||||
>
|
||||
<FileArchive className="h-4 w-4" />
|
||||
Import ZIP File
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ZIP Import Dialog */}
|
||||
<ZipImportDialog
|
||||
onImport={handleImportZip}
|
||||
open={isZipDialogOpen}
|
||||
onOpenChange={setIsZipDialogOpen}
|
||||
/>
|
||||
</AppLayout>
|
||||
);
|
||||
}
|
||||
@@ -17,6 +17,9 @@ describe('DataSettings', () => {
|
||||
// Check for description
|
||||
expect(screen.getByText('Export files and manage local data.')).toBeInTheDocument();
|
||||
|
||||
// Check for Persist Data section
|
||||
expect(screen.getByText('Persist Data')).toBeInTheDocument();
|
||||
|
||||
// Check for Export Files section
|
||||
expect(screen.getByText('Export Files')).toBeInTheDocument();
|
||||
expect(screen.getByText('Export All Files')).toBeInTheDocument();
|
||||
@@ -26,13 +29,17 @@ describe('DataSettings', () => {
|
||||
expect(screen.getByRole('button', { name: /clear all data/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows export and clear buttons', () => {
|
||||
it('shows persist data toggle, export and clear buttons', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<DataSettings />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Persist storage toggle should be visible
|
||||
const persistToggle = screen.getByRole('switch');
|
||||
expect(persistToggle).toBeInTheDocument();
|
||||
|
||||
// Export button should be visible
|
||||
const exportButton = screen.getByRole('button', { name: /export all files/i });
|
||||
expect(exportButton).toBeInTheDocument();
|
||||
|
||||
+103
-12
@@ -1,14 +1,21 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Download, Trash2, AlertTriangle, Loader2, Database, Info, ArrowLeft } from 'lucide-react';
|
||||
import { Download, Trash2, AlertTriangle, Loader2, Database, Info, ArrowLeft, Shield } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
|
||||
import { Progress } from '@/components/ui/progress';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import {
|
||||
isPersistentStorageSupported,
|
||||
isPersistentStorageGranted,
|
||||
requestPersistentStorage,
|
||||
getStorageInfo
|
||||
} from '@/lib/persistentStorage';
|
||||
import JSZip from 'jszip';
|
||||
|
||||
interface StorageUsageDetails {
|
||||
@@ -28,8 +35,10 @@ export function DataSettings() {
|
||||
const { t } = useTranslation();
|
||||
const [isExporting, setIsExporting] = useState(false);
|
||||
const [isClearing, setIsClearing] = useState(false);
|
||||
const [isRequestingPersistent, setIsRequestingPersistent] = useState(false);
|
||||
const [storageInfo, setStorageInfo] = useState<StorageInfo | null>(null);
|
||||
const [storageError, setStorageError] = useState<string | null>(null);
|
||||
const [isPersistent, setIsPersistent] = useState<boolean | null>(null);
|
||||
const { toast } = useToast();
|
||||
const { fs } = useFS();
|
||||
const navigate = useNavigate();
|
||||
@@ -44,27 +53,29 @@ export function DataSettings() {
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
|
||||
};
|
||||
|
||||
// Load storage information
|
||||
// Load storage information and persistent status
|
||||
useEffect(() => {
|
||||
const loadStorageInfo = async () => {
|
||||
try {
|
||||
// Check if StorageManager API is available
|
||||
if (!('storage' in navigator)) {
|
||||
if (!isPersistentStorageSupported()) {
|
||||
setStorageError('StorageManager API is not available in this browser');
|
||||
return;
|
||||
}
|
||||
|
||||
// Get storage estimate
|
||||
const estimate = await navigator.storage.estimate();
|
||||
const info = await getStorageInfo();
|
||||
if (info) {
|
||||
setStorageInfo({
|
||||
quota: info.quota,
|
||||
usage: info.usage,
|
||||
usageDetails: info.usageDetails as StorageUsageDetails,
|
||||
});
|
||||
}
|
||||
|
||||
// Extract usage details safely
|
||||
const usageDetails: StorageUsageDetails | undefined = (estimate as StorageEstimate & { usageDetails?: StorageUsageDetails }).usageDetails;
|
||||
|
||||
setStorageInfo({
|
||||
quota: estimate.quota || 0,
|
||||
usage: estimate.usage || 0,
|
||||
usageDetails,
|
||||
});
|
||||
// Check if storage is persistent
|
||||
const persistent = await isPersistentStorageGranted();
|
||||
setIsPersistent(persistent);
|
||||
} catch (error) {
|
||||
console.error('Failed to get storage information:', error);
|
||||
setStorageError(error instanceof Error ? error.message : 'Failed to get storage information');
|
||||
@@ -149,6 +160,63 @@ export function DataSettings() {
|
||||
}
|
||||
};
|
||||
|
||||
const handlePersistentStorageToggle = async (checked: boolean) => {
|
||||
// If trying to turn off, we can't actually do that - just ignore
|
||||
if (!checked) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsRequestingPersistent(true);
|
||||
try {
|
||||
// Check if persist method is available
|
||||
if (!isPersistentStorageSupported()) {
|
||||
toast({
|
||||
title: t('persistentStorageNotSupported'),
|
||||
description: t('persistentStorageNotSupportedDescription'),
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if already persistent
|
||||
const alreadyPersistent = await isPersistentStorageGranted();
|
||||
if (alreadyPersistent) {
|
||||
setIsPersistent(true);
|
||||
toast({
|
||||
title: t('persistentStorageAlreadyGranted'),
|
||||
description: t('persistentStorageAlreadyGrantedDescription'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Request persistent storage
|
||||
const granted = await requestPersistentStorage();
|
||||
|
||||
if (granted) {
|
||||
setIsPersistent(true);
|
||||
toast({
|
||||
title: t('persistentStorageGranted'),
|
||||
description: t('persistentStorageGrantedDescription'),
|
||||
});
|
||||
} else {
|
||||
toast({
|
||||
title: t('persistentStorageDenied'),
|
||||
description: t('persistentStorageDeniedDescription'),
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to request persistent storage:', error);
|
||||
toast({
|
||||
title: t('failedToRequestPersistentStorage'),
|
||||
description: error instanceof Error ? error.message : t('error'),
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsRequestingPersistent(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleClearAllData = async () => {
|
||||
setIsClearing(true);
|
||||
try {
|
||||
@@ -268,6 +336,29 @@ export function DataSettings() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Persist Data */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Shield className="h-5 w-5" />
|
||||
{t('persistData')}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{t('persistDataDescription')}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-center justify-start">
|
||||
<Switch
|
||||
id="persistent-storage"
|
||||
checked={isPersistent === true}
|
||||
onCheckedChange={handlePersistentStorageToggle}
|
||||
disabled={isRequestingPersistent || isPersistent === null}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Export Files */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
|
||||
@@ -1,301 +0,0 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { ArrowLeft, Mail, CheckCircle } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
export function EmailSettings() {
|
||||
const { t } = useTranslation();
|
||||
const isMobile = useIsMobile();
|
||||
const navigate = useNavigate();
|
||||
const { user } = useCurrentUser();
|
||||
const { toast } = useToast();
|
||||
|
||||
const [email, setEmail] = useState('');
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [isSubmitted, setIsSubmitted] = useState(false);
|
||||
|
||||
// Check localStorage on component mount
|
||||
useEffect(() => {
|
||||
const hasSubscribed = localStorage.getItem('shakespeare-email-subscribed');
|
||||
if (hasSubscribed === 'true') {
|
||||
setIsSubmitted(true);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!email.trim()) {
|
||||
toast({
|
||||
title: "Email required",
|
||||
description: "Please enter your email address",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Basic email validation
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(email)) {
|
||||
toast({
|
||||
title: "Invalid email",
|
||||
description: "Please enter a valid email address",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSubmitting(true);
|
||||
|
||||
try {
|
||||
// Prepare form data
|
||||
const formData = new FormData();
|
||||
formData.append('email', email.trim());
|
||||
formData.append('tag_id', '8982396');
|
||||
|
||||
// Include npub if user is signed in
|
||||
if (user?.pubkey) {
|
||||
const npub = nip19.npubEncode(user.pubkey);
|
||||
formData.append('npub', npub);
|
||||
}
|
||||
|
||||
// Submit to Mailchimp using the same setup as soapbox2
|
||||
const form = document.createElement('form');
|
||||
form.method = 'POST';
|
||||
form.action = 'https://pub.us7.list-manage.com/subscribe/post?u=f1f718a93795f42a604d558d8&id=f7271442a0&f_id=00ffa3e4f0';
|
||||
form.target = '_blank'; // Open in new tab
|
||||
form.style.display = 'none';
|
||||
|
||||
// Add email field
|
||||
const emailInput = document.createElement('input');
|
||||
emailInput.type = 'email';
|
||||
emailInput.name = 'EMAIL';
|
||||
emailInput.value = email.trim();
|
||||
form.appendChild(emailInput);
|
||||
|
||||
// Add tag field with the new Shakespeare tag ID
|
||||
const tagInput = document.createElement('input');
|
||||
tagInput.type = 'hidden';
|
||||
tagInput.name = 'tags';
|
||||
tagInput.value = '8982396';
|
||||
form.appendChild(tagInput);
|
||||
|
||||
// Add npub if available
|
||||
if (user?.pubkey) {
|
||||
const npubInput = document.createElement('input');
|
||||
npubInput.type = 'text';
|
||||
npubInput.name = 'NPUB';
|
||||
npubInput.value = nip19.npubEncode(user.pubkey);
|
||||
npubInput.style.display = 'none';
|
||||
form.appendChild(npubInput);
|
||||
}
|
||||
|
||||
// Add honeypot field
|
||||
const honeypotInput = document.createElement('input');
|
||||
honeypotInput.type = 'text';
|
||||
honeypotInput.name = 'b_f1f718a93795f42a604d558d8_f7271442a0';
|
||||
honeypotInput.tabIndex = -1;
|
||||
honeypotInput.style.position = 'absolute';
|
||||
honeypotInput.style.left = '-5000px';
|
||||
form.appendChild(honeypotInput);
|
||||
|
||||
// Add form to document and submit
|
||||
document.body.appendChild(form);
|
||||
form.submit();
|
||||
|
||||
// Clean up after a short delay
|
||||
setTimeout(() => {
|
||||
document.body.removeChild(form);
|
||||
}, 1000);
|
||||
|
||||
// Save subscription status to localStorage
|
||||
localStorage.setItem('shakespeare-email-subscribed', 'true');
|
||||
|
||||
setIsSubmitted(true);
|
||||
toast({
|
||||
title: "Successfully subscribed!",
|
||||
description: "You'll receive Shakespeare updates and resources occasionally.",
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Email signup error:', error);
|
||||
toast({
|
||||
title: "Subscription failed",
|
||||
description: "There was an error subscribing you to updates. Please try again.",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (isSubmitted) {
|
||||
return (
|
||||
<div className="p-6 space-y-6">
|
||||
{isMobile && (
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => navigate('/settings')}
|
||||
className="h-8 w-auto px-2 -ml-2"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4 mr-2" />
|
||||
{t('backToSettings')}
|
||||
</Button>
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-2xl font-bold flex items-center gap-3">
|
||||
<Mail className="h-6 w-6 text-primary" />
|
||||
{t('emailUpdates')}
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{t('emailUpdatesDescriptionLong')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isMobile && (
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-2xl font-bold flex items-center gap-3">
|
||||
<Mail className="h-6 w-6 text-primary" />
|
||||
{t('emailUpdates')}
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{t('emailUpdatesDescriptionLong')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="max-w-md">
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="text-center space-y-4">
|
||||
<CheckCircle className="h-12 w-12 mx-auto text-green-500" />
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-lg font-semibold">
|
||||
Thanks for subscribing!
|
||||
</h3>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
You can opt out at any time using the unsubscribe link in our emails.
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Button
|
||||
onClick={() => navigate('/settings')}
|
||||
className="w-full"
|
||||
>
|
||||
Back to Settings
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => {
|
||||
localStorage.removeItem('shakespeare-email-subscribed');
|
||||
setIsSubmitted(false);
|
||||
setEmail('');
|
||||
}}
|
||||
variant="outline"
|
||||
className="w-full text-xs"
|
||||
>
|
||||
Subscribe with different email
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6">
|
||||
{isMobile && (
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => navigate('/settings')}
|
||||
className="h-8 w-auto px-2 -ml-2"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4 mr-2" />
|
||||
{t('backToSettings')}
|
||||
</Button>
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-2xl font-bold flex items-center gap-3">
|
||||
<Mail className="h-6 w-6 text-primary" />
|
||||
{t('emailUpdates')}
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{t('emailUpdatesDescriptionLong')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isMobile && (
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-2xl font-bold flex items-center gap-3">
|
||||
<Mail className="h-6 w-6 text-primary" />
|
||||
{t('emailUpdates')}
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{t('emailUpdatesDescriptionLong')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="max-w-md">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">
|
||||
Stay Updated with Shakespeare
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">
|
||||
Email Address
|
||||
</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder="[email protected]"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
disabled={isSubmitting}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full"
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
{isSubmitting ? 'Subscribing...' : 'Subscribe to Updates'}
|
||||
</Button>
|
||||
|
||||
<p className="text-xs text-muted-foreground text-center">
|
||||
You can opt out at any time using the unsubscribe link in our emails.
|
||||
</p>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default EmailSettings;
|
||||
+56
-47
@@ -7,11 +7,11 @@ import { useFS } from '@/hooks/useFS';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { AppLayout } from '@/components/AppLayout';
|
||||
import { OnboardingDialog } from '@/components/OnboardingDialog';
|
||||
import { Act1Dialog } from '@/components/Act1Dialog';
|
||||
import { Quilly } from '@/components/Quilly';
|
||||
import { DotAI } from '@/lib/DotAI';
|
||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
import type { AIMessage } from '@/lib/SessionManager';
|
||||
import { saveFileToTmp } from '@/lib/fileUtils';
|
||||
import type OpenAI from 'openai';
|
||||
@@ -19,9 +19,9 @@ import { Button } from '@/components/ui/button';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { ModelSelector } from '@/components/ModelSelector';
|
||||
import { FileAttachment } from '@/components/ui/file-attachment';
|
||||
import { ToastAction } from '@/components/ui/toast';
|
||||
import { Plus } from 'lucide-react';
|
||||
import { useSeoMeta } from '@unhead/react';
|
||||
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
||||
|
||||
export default function Index() {
|
||||
const { t } = useTranslation();
|
||||
@@ -29,12 +29,12 @@ export default function Index() {
|
||||
const [isCreating, setIsCreating] = useState(false);
|
||||
const [storedPrompt, setStoredPrompt] = useLocalStorage('shakespeare-draft-prompt', '');
|
||||
const [showOnboarding, setShowOnboarding] = useState(false);
|
||||
const [showAct1Dialog, setShowAct1Dialog] = useState(false);
|
||||
const navigate = useNavigate();
|
||||
const projectsManager = useProjectsManager();
|
||||
const { fs } = useFS();
|
||||
const { generateProjectId, isLoading: isGeneratingId } = useAIProjectId();
|
||||
const { settings, addRecentlyUsedModel } = useAISettings();
|
||||
const { toast } = useToast();
|
||||
const [providerModel, setProviderModel] = useState(() => {
|
||||
// Initialize with first recently used model if available, otherwise empty
|
||||
return settings.recentlyUsedModels?.[0] || '';
|
||||
@@ -42,45 +42,11 @@ export default function Index() {
|
||||
const isMobile = useIsMobile();
|
||||
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
|
||||
const [isDragOver, setIsDragOver] = useState(false);
|
||||
const [quillyError, setQuillyError] = useState<Error | null>(null);
|
||||
|
||||
// Check if any providers are configured
|
||||
const hasProvidersConfigured = settings.providers.length > 0;
|
||||
|
||||
// Check for API key failures and show appropriate toast
|
||||
const checkForKeyFailure = (error: unknown): boolean => {
|
||||
// Check for authentication errors
|
||||
// Note: useAIProjectId re-throws OpenAI errors as generic Error objects
|
||||
const isAuthError = error instanceof Error && error.message === '401 No auth credentials found';
|
||||
|
||||
if (isAuthError) {
|
||||
// Get provider name inline
|
||||
let providerName = 'Provider';
|
||||
try {
|
||||
const { provider } = parseProviderModel(providerModel, settings.providers);
|
||||
providerName = provider.id.charAt(0).toUpperCase() + provider.id.slice(1);
|
||||
} catch {
|
||||
// Keep default 'Provider'
|
||||
}
|
||||
|
||||
toast({
|
||||
title: t('apiAuthenticationFailed'),
|
||||
description: t('invalidApiKey', { provider: providerName }),
|
||||
variant: 'destructive',
|
||||
action: (
|
||||
<ToastAction
|
||||
altText={t('checkApiKeySettings')}
|
||||
onClick={() => navigate('/settings/ai')}
|
||||
>
|
||||
{t('checkApiKeySettings')}
|
||||
</ToastAction>
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
return isAuthError;
|
||||
};
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
if (!providerModel && settings.recentlyUsedModels?.length) {
|
||||
setProviderModel(settings.recentlyUsedModels[0]);
|
||||
@@ -99,6 +65,13 @@ export default function Index() {
|
||||
}
|
||||
}, [storedPrompt]);
|
||||
|
||||
// Check for Act 1 users and show welcome dialog
|
||||
useEffect(() => {
|
||||
if (localStorage.getItem('selectedNSPAddr')) {
|
||||
setShowAct1Dialog(true);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Sync prompt with local storage
|
||||
const handlePromptChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||
const newPrompt = e.target.value;
|
||||
@@ -187,6 +160,27 @@ export default function Index() {
|
||||
}
|
||||
};
|
||||
|
||||
// Quilly handlers
|
||||
const handleQuillyDismiss = () => {
|
||||
setQuillyError(null);
|
||||
};
|
||||
|
||||
const handleQuillyNewChat = () => {
|
||||
// Clear current prompt and start fresh
|
||||
setPrompt('');
|
||||
setStoredPrompt('');
|
||||
setAttachedFiles([]);
|
||||
setQuillyError(null);
|
||||
};
|
||||
|
||||
const handleQuillyOpenModelSelector = () => {
|
||||
// Focus on model selector or open AI settings if no providers
|
||||
if (!hasProvidersConfigured) {
|
||||
setShowOnboarding(true);
|
||||
}
|
||||
setQuillyError(null);
|
||||
};
|
||||
|
||||
const handleCreateProject = async () => {
|
||||
if (!prompt.trim() || !providerModel.trim()) return;
|
||||
|
||||
@@ -261,13 +255,7 @@ export default function Index() {
|
||||
navigate(`/project/${project.id}?${searchParams.toString()}`);
|
||||
} catch (error) {
|
||||
console.error('Failed to create project:', error);
|
||||
if (!checkForKeyFailure(error)) {
|
||||
toast({
|
||||
title: "Project Creation Failed",
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
setQuillyError(error instanceof Error ? error : new Error("An unexpected error occurred"));
|
||||
} finally {
|
||||
setIsCreating(false);
|
||||
}
|
||||
@@ -280,7 +268,9 @@ export default function Index() {
|
||||
<AppLayout headerContent={headerContent}>
|
||||
<div className="max-w-4xl mx-auto">
|
||||
<div className="text-center mb-8 md:mb-12">
|
||||
<div className="text-4xl md:text-6xl mb-4 md:mb-6">🎭</div>
|
||||
<div className="mb-4 md:mb-6">
|
||||
<ShakespeareLogo className="w-20 h-20 md:w-24 md:h-24 mx-auto" />
|
||||
</div>
|
||||
<h1 className="text-3xl md:text-4xl font-bold mb-3 md:mb-4 bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||
{t('buildNostrApps')}
|
||||
</h1>
|
||||
@@ -290,6 +280,19 @@ export default function Index() {
|
||||
</div>
|
||||
|
||||
<div className="mb-8 md:mb-12">
|
||||
{/* Quilly Helper - shows when there are errors */}
|
||||
{quillyError && (
|
||||
<div className="mb-4">
|
||||
<Quilly
|
||||
error={quillyError}
|
||||
onDismiss={handleQuillyDismiss}
|
||||
onNewChat={handleQuillyNewChat}
|
||||
onOpenModelSelector={handleQuillyOpenModelSelector}
|
||||
providerModel={providerModel}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Chat Input Container - matching the ChatPane style */}
|
||||
<div
|
||||
className={`relative rounded-2xl border border-input bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 transition-all ${isDragOver ? 'border-primary bg-primary/5 ring-2 ring-primary/20' : ''
|
||||
@@ -383,6 +386,12 @@ export default function Index() {
|
||||
open={showOnboarding}
|
||||
onOpenChange={setShowOnboarding}
|
||||
/>
|
||||
|
||||
{/* Act 1 Welcome Dialog */}
|
||||
<Act1Dialog
|
||||
open={showAct1Dialog}
|
||||
onOpenChange={setShowAct1Dialog}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -92,15 +92,13 @@ export function NostrSettings() {
|
||||
{isLoading ? (
|
||||
<div className="border rounded-lg overflow-hidden">
|
||||
{/* Loading skeleton for accounts */}
|
||||
{[...Array(2)].map((_, i) => (
|
||||
<div key={i} className="flex items-center gap-3 p-3 border-b last:border-b-0">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
<div className="flex-1 space-y-1">
|
||||
<Skeleton className="h-4 w-32" />
|
||||
</div>
|
||||
<Skeleton className="h-8 w-8 rounded" />
|
||||
<div className="flex items-center gap-3 p-3 border-b last:border-b-0">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
<div className="flex-1 space-y-1">
|
||||
<Skeleton className="h-4 w-32" />
|
||||
</div>
|
||||
))}
|
||||
<Skeleton className="h-8 w-8 rounded" />
|
||||
</div>
|
||||
{/* Add account button skeleton */}
|
||||
<div className="flex items-center gap-3 p-3">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
|
||||
+30
-38
@@ -14,12 +14,11 @@ import { ArrowLeft, MessageSquare, Eye, Code, Menu } from 'lucide-react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { ActionsMenu } from '@/components/ActionsMenu';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { useKeepAlive } from '@/hooks/useKeepAlive';
|
||||
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
|
||||
import { StarButton } from '@/components/StarButton';
|
||||
|
||||
import { useBuildProject } from '@/hooks/useBuildProject';
|
||||
import { useIsProjectPreviewable } from '@/hooks/useIsProjectPreviewable';
|
||||
import { clearConsoleMessages, ProjectPreviewConsoleError, addErrorListener, removeErrorListener } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||
|
||||
export function ProjectView() {
|
||||
const { projectId } = useParams<{ projectId: string }>();
|
||||
@@ -30,6 +29,8 @@ export function ProjectView() {
|
||||
const [mobileView, setMobileView] = useState<'chat' | 'preview' | 'code'>('chat');
|
||||
const [isAILoading, setIsAILoading] = useState(false);
|
||||
const [isProjectDetailsOpen, setIsProjectDetailsOpen] = useState(false);
|
||||
const [consoleError, setConsoleError] = useState<ProjectPreviewConsoleError | null>(null);
|
||||
|
||||
const projectsManager = useProjectsManager();
|
||||
const chatPaneRef = useRef<ChatPaneRef>(null);
|
||||
const navigate = useNavigate();
|
||||
@@ -40,26 +41,15 @@ export function ProjectView() {
|
||||
const build = useBuildProject(projectId!);
|
||||
const { data: isPreviewable = false } = useIsProjectPreviewable(projectId!);
|
||||
|
||||
// Keep-alive functionality to prevent tab throttling during AI processing
|
||||
const { updateMetadata } = useKeepAlive({
|
||||
enabled: isAILoading || build.isPending,
|
||||
title: 'Shakespeare',
|
||||
artist: project ? `Working on ${project.name}...` : 'Working...',
|
||||
artwork: [
|
||||
{
|
||||
src: '/favicon.png',
|
||||
sizes: '512x512',
|
||||
type: 'image/png'
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
const loadProject = useCallback(async () => {
|
||||
if (!projectId) return;
|
||||
|
||||
try {
|
||||
const projectData = await projectsManager.getProject(projectId);
|
||||
setProject(projectData);
|
||||
// Clear console messages and error state when switching projects
|
||||
clearConsoleMessages();
|
||||
setConsoleError(null);
|
||||
} catch (error) {
|
||||
console.error('Failed to load project:', error);
|
||||
} finally {
|
||||
@@ -91,19 +81,15 @@ export function ProjectView() {
|
||||
}
|
||||
}, [isPreviewable, mobileView, activeTab]);
|
||||
|
||||
const runBuild = async () => {
|
||||
if (build.isPending || !project) return;
|
||||
updateMetadata('Shakespeare', `Building ${project.name}...`);
|
||||
// Global console error listener (always active regardless of current tab)
|
||||
useEffect(() => {
|
||||
const handleConsoleError = (error: ProjectPreviewConsoleError) => {
|
||||
setConsoleError(error);
|
||||
};
|
||||
|
||||
await build.mutateAsync(undefined, {
|
||||
onSuccess(result) {
|
||||
console.log('Project built:', result);
|
||||
},
|
||||
onError(error) {
|
||||
console.error('Build failed:', error);
|
||||
},
|
||||
});
|
||||
};
|
||||
addErrorListener(handleConsoleError);
|
||||
return () => removeErrorListener(handleConsoleError);
|
||||
}, []);
|
||||
|
||||
const handleNewChat = () => {
|
||||
// Reset to chat view on mobile when starting new chat
|
||||
@@ -126,6 +112,10 @@ export function ProjectView() {
|
||||
// when isAILoading becomes true after user interaction
|
||||
};
|
||||
|
||||
const handleDismissConsoleError = () => {
|
||||
setConsoleError(null);
|
||||
};
|
||||
|
||||
const handleProjectDeleted = async () => {
|
||||
setProject(null);
|
||||
navigate('/');
|
||||
@@ -147,7 +137,7 @@ export function ProjectView() {
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<div className="h-dvh flex flex-col bg-background">
|
||||
<div className="h-dvh flex flex-col bg-background safe-area-inset-top">
|
||||
<header className="overflow-hidden border-b bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10 backdrop-blur supports-[backdrop-filter]:bg-gradient-to-r supports-[backdrop-filter]:from-primary/10 supports-[backdrop-filter]:via-accent/5 supports-[backdrop-filter]:to-primary/10 px-4 py-3 flex items-center justify-between">
|
||||
<div className="flex items-center space-x-2 overflow-hidden">
|
||||
<Button
|
||||
@@ -234,11 +224,12 @@ export function ProjectView() {
|
||||
ref={chatPaneRef}
|
||||
projectId={project.id}
|
||||
onNewChat={handleNewChat}
|
||||
onBuild={runBuild}
|
||||
onFirstInteraction={handleFirstInteraction}
|
||||
onLoadingChange={handleAILoadingChange}
|
||||
isLoading={isAILoading}
|
||||
isBuildLoading={build.isPending}
|
||||
consoleError={consoleError}
|
||||
onDismissConsoleError={handleDismissConsoleError}
|
||||
/>
|
||||
) : (
|
||||
<div className="h-full p-4 space-y-4">
|
||||
@@ -266,13 +257,13 @@ export function ProjectView() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="border-t bg-gradient-to-r from-primary/5 via-background to-accent/5 backdrop-blur">
|
||||
<div className="border-t bg-gradient-to-r from-primary/5 via-background to-accent/5 backdrop-blur safe-area-inset-bottom">
|
||||
<div className="flex">
|
||||
<Button
|
||||
variant={mobileView === 'chat' ? 'default' : 'ghost'}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setMobileView('chat')}
|
||||
className="flex-1 rounded-none"
|
||||
className={`flex-1 rounded-none mobile-nav-button ${mobileView === 'chat' ? 'mobile-nav-button-active' : ''}`}
|
||||
disabled={!project}
|
||||
>
|
||||
<MessageSquare className="h-4 w-4 mr-1" />
|
||||
@@ -280,10 +271,10 @@ export function ProjectView() {
|
||||
</Button>
|
||||
{isPreviewable && (
|
||||
<Button
|
||||
variant={mobileView === 'preview' ? 'default' : 'ghost'}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setMobileView('preview')}
|
||||
className="flex-1 rounded-none"
|
||||
className={`flex-1 rounded-none mobile-nav-button ${mobileView === 'preview' ? 'mobile-nav-button-active' : ''}`}
|
||||
disabled={!project}
|
||||
>
|
||||
<Eye className="h-4 w-4 mr-1" />
|
||||
@@ -291,10 +282,10 @@ export function ProjectView() {
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant={mobileView === 'code' ? 'default' : 'ghost'}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setMobileView('code')}
|
||||
className="flex-1 rounded-none"
|
||||
className={`flex-1 rounded-none mobile-nav-button ${mobileView === 'code' ? 'mobile-nav-button-active' : ''}`}
|
||||
disabled={!project}
|
||||
>
|
||||
<Code className="h-4 w-4 mr-1" />
|
||||
@@ -414,11 +405,12 @@ export function ProjectView() {
|
||||
ref={chatPaneRef}
|
||||
projectId={project.id}
|
||||
onNewChat={handleNewChat}
|
||||
onBuild={runBuild}
|
||||
onFirstInteraction={handleFirstInteraction}
|
||||
onLoadingChange={handleAILoadingChange}
|
||||
isLoading={isAILoading}
|
||||
isBuildLoading={build.isPending}
|
||||
consoleError={consoleError}
|
||||
onDismissConsoleError={handleDismissConsoleError}
|
||||
/>
|
||||
) : (
|
||||
<div className="h-full p-4 space-y-4">
|
||||
|
||||
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user